Skip to content

AI Code Explainer — Zig source

Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.

This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! code-explainer — language guessing, depth-graded prompts, reply cleanup.
//!
//! Language: Zig (0.13+, standard library only — std has no regex engine,
//!           so the eight heuristic rules are hand-rolled scanners, the
//!           same route src/tool-sources/base64/zig.zig took for its codec)
//! CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
//! src/lib/code-explainer.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: the whole explainer pipeline is three pure functions
//! — guess a language, wrap a paste in a depth-graded chat prompt, strip code
//! fences from the reply — so every runtime runs the identical heuristics.
//! The scanners reproduce the TS regexes' semantics: ASCII-only \w and \b,
//! first match wins, `.` never crossing a newline, and `$` as an end-of-line
//! anchor for the python rule (the /m flag). Zig never names a field `error`.
//!
//! Test: zig test zig.zig

const std = @import("std");

/// Guess the language from (and prompt with) at most this many bytes.
pub const max_code_chars: usize = 12000;

/// One [system, user] chat message for the provider layer.
pub const ChatMessage = struct {
    role: []const u8,
    content: []const u8,
};

/// Per-level explanation contract, verbatim from the TS lib. An unknown
/// level yields "" rather than the TS template's literal "undefined".
pub fn levelContract(level: []const u8) []const u8 {
    const beginner = "Explain for a smart newcomer: no unexplained jargon, short sentences, one everyday analogy if it helps. Say what it does first, then how, step by step.";
    const developer = "Explain for a working developer: concise and practical. Lead with what it does, then the flow, the patterns used, and the pitfalls an editor should catch.";
    const expert = "Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.";
    if (std.mem.eql(u8, level, "beginner")) return beginner;
    if (std.mem.eql(u8, level, "developer")) return developer;
    if (std.mem.eql(u8, level, "expert")) return expert;
    return "";
}

// ---- scanner kit: the pieces the eight rule checkers share ----------------

fn isWord(c: u8) bool {
    return std.ascii.isAlphanumeric(c) or c == '_';
}

fn isSpace(c: u8) bool {
    return c == ' ' or c == '\t' or c == '\n' or c == 0x0b or c == 0x0c or c == '\r';
}

/// First whole-word hit of `lit` (\blit\b: a non-word char or an edge on
/// both flanks). Returns its offset, or null.
fn wordAt(hay: []const u8, lit: []const u8) ?usize {
    var i: usize = 0;
    while (std.mem.indexOfPos(u8, hay, i, lit)) |at| {
        const end = at + lit.len;
        const left = at == 0 or !isWord(hay[at - 1]);
        const right = end == hay.len or !isWord(hay[end]);
        if (left and right) return at;
        i = at + 1;
    }
    return null;
}

/// \b<kw>\s+\w+ — whole-word keyword, at least one space, then a word run.
/// Returns the offset just past the run, or null. Shared by the go / rust /
/// python / typescript / javascript rules.
fn kwRunEnd(hay: []const u8, kw: []const u8) ?usize {
    var at = wordAt(hay, kw) orelse return null;
    while (true) {
        var e = at + kw.len;
        const ws_start = e;
        while (e < hay.len and isSpace(hay[e])) e += 1;
        if (e > ws_start and e < hay.len and isWord(hay[e])) {
            while (e < hay.len and isWord(hay[e])) e += 1;
            return e;
        }
        at = (wordAt(hay[at + 1 ..], kw) orelse return null) + at + 1;
    }
}

/// \s* followed by `c`, from the end of a keyword's word run.
fn thenChar(hay: []const u8, e: usize, c: u8) bool {
    var i = e;
    while (i < hay.len and isSpace(hay[i])) i += 1;
    return i < hay.len and hay[i] == c;
}

/// Case-insensitive prefix match (the /i flag), lowercased `lit`.
fn ciPrefix(s: []const u8, lit: []const u8) bool {
    if (s.len < lit.len) return false;
    for (s[0..lit.len], lit) |x, y| {
        if (std.ascii.toLower(x) != y) return false;
    }
    return true;
}

// ---- the eight rules, in priority order -----------------------------------

// \bpackage\s+\w+ | \bfunc\s+\w+ | :=
fn ruleGo(s: []const u8) bool {
    return kwRunEnd(s, "package") != null or kwRunEnd(s, "func") != null or
        std.mem.indexOf(u8, s, ":=") != null;
}

// \bfn\s+\w+ | \blet\s+mut\b | \bimpl\b
fn ruleRust(s: []const u8) bool {
    if (wordAt(s, "let")) |at| {
        var e = at + 3;
        const ws_start = e;
        while (e < s.len and isSpace(s[e])) e += 1;
        if (e > ws_start and ciPrefix(s[e..], "mut") and
            (e + 3 == s.len or !isWord(s[e + 3]))) return true;
    }
    return kwRunEnd(s, "fn") != null or wordAt(s, "impl") != null;
}

// \bdef\s+\w+\s*\( | \bprint\s*\( | \bimport\s+\w+\s*$ — the TS /m flag,
// so the $ also matches just before a newline.
fn rulePython(s: []const u8) bool {
    if (kwRunEnd(s, "def")) |e| {
        if (thenChar(s, e, '(')) return true;
    }
    if (wordAt(s, "print")) |at| {
        if (thenChar(s, at + 5, '(')) return true;
    }
    const e = kwRunEnd(s, "import") orelse return false;
    var i = e;
    while (i < s.len and isSpace(s[i]) and s[i] != '\n') i += 1; // \s*$, line-wise
    return i == s.len or s[i] == '\n';
}

// \bSELECT\b.+\bFROM\b case-insensitively; JS `.` never crosses a newline,
// so the two words must share a line, with at least one char between.
fn ruleSql(s: []const u8) bool {
    var from: usize = 0;
    while (true) {
        const at = blk: {
            const rel = wordAt(s[from..], "select") orelse return false;
            break :blk from + rel;
        };
        const e = at + 6;
        if (e < s.len and s[e] != '\n') { // .+ needs a same-line char
            var q = e + 1;
            while (q < s.len and s[q] != '\n') : (q += 1) {
                if (q + 4 <= s.len and !isWord(s[q - 1]) and
                    ciPrefix(s[q..], "from") and
                    (q + 4 == s.len or !isWord(s[q + 4]))) return true;
            }
        }
        from = at + 1;
    }
}

// (string|number|boolean)\b at i — the tail of the colon-type rule.
fn tsTypeAt(s: []const u8, i: usize) bool {
    const lits = [_][]const u8{ "string", "number", "boolean" };
    for (lits) |lit| {
        if (i + lit.len <= s.len and std.mem.eql(u8, s[i..][0..lit.len], lit) and
            (i + lit.len == s.len or !isWord(s[i + lit.len]))) return true;
    }
    return false;
}

// \binterface\s+\w+\s*\{ | \btype\s+\w+\s*= | :\s*(string|number|boolean)\b
fn ruleTypescript(s: []const u8) bool {
    if (kwRunEnd(s, "interface")) |e| {
        if (thenChar(s, e, '{')) return true;
    }
    if (kwRunEnd(s, "type")) |e| {
        if (thenChar(s, e, '=')) return true;
    }
    var i: usize = 0;
    while (std.mem.indexOfScalarPos(u8, s, i, ':')) |c| {
        var q = c + 1; // : \s*
        while (q < s.len and isSpace(s[q])) q += 1;
        if (tsTypeAt(s, q)) return true;
        i = c + 1;
    }
    return false;
}

// \bconst\s+\w+\s*= | => | console\.log
fn ruleJavascript(s: []const u8) bool {
    if (kwRunEnd(s, "const")) |e| {
        if (thenChar(s, e, '=')) return true;
    }
    return std.mem.indexOf(u8, s, "=>") != null or
        std.mem.indexOf(u8, s, "console.log") != null;
}

// [.#]?[\w-]+\s*\{[^}]*:[^}]*; — a selector, then inside the braces (or up
// to end of input; [^}]* needs no closing brace) a `prop: value;` pair.
fn ruleCss(s: []const u8) bool {
    var i: usize = 0;
    while (std.mem.indexOfScalarPos(u8, s, i, '{')) |b| {
        var q = b; // \s* backwards
        while (q > 0 and isSpace(s[q - 1])) q -= 1;
        var n: usize = 0; // [\w-]+ backwards
        while (q > 0 and (isWord(s[q - 1]) or s[q - 1] == '-')) {
            q -= 1;
            n += 1;
        }
        if (n > 0) {
            if (q > 0 and (s[q - 1] == '.' or s[q - 1] == '#')) q -= 1; // [.#]?
            const e = std.mem.indexOfScalarPos(u8, s, b + 1, '}') orelse s.len;
            if (std.mem.indexOfScalar(u8, s[b + 1 .. e], ':')) |c2| {
                if (std.mem.indexOfScalar(u8, s[b + 2 + c2 .. e], ';') != null) return true;
            }
        }
        i = b + 1;
    }
    return false;
}

// </?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*\/?> case-insensitively
fn ruleHtml(s: []const u8) bool {
    var i: usize = 0;
    while (std.mem.indexOfScalarPos(u8, s, i, '<')) |p| {
        var q = p + 1;
        if (q < s.len and s[q] == '/') q += 1;
        if (q >= s.len or !std.ascii.isAlphabetic(s[q])) {
            i = p + 1;
            continue;
        }
        q += 1;
        while (q < s.len and (isWord(s[q]) or s[q] == '-')) q += 1; // [\w-]*
        while (true) { // (\s+[\w-]+="[^"]*")*
            var k = q;
            while (k < s.len and isSpace(s[k])) k += 1; // \s+
            var a = k;
            while (a < s.len and (isWord(s[a]) or s[a] == '-')) a += 1; // [\w-]+
            if (a > k and a + 1 < s.len and s[a] == '=' and s[a + 1] == '"') {
                const close = std.mem.indexOfScalarPos(u8, s, a + 2, '"') orelse break;
                q = close + 1;
            } else break;
        }
        while (q < s.len and isSpace(s[q])) q += 1; // \s*
        if (q < s.len and s[q] == '/') q += 1; // \/?
        if (q < s.len and s[q] == '>') return true;
        i = p + 1;
    }
    return false;
}

/// Guess which language a code sample is written in. Falls back to "text"
/// when no rule matches, so the prompt can ask the model to reason about the
/// paste as pseudocode. Twin of guessLanguage() in src/lib/code-explainer.ts.
pub fn guessLanguage(code: []const u8) []const u8 {
    if (ruleGo(code)) return "go";
    if (ruleRust(code)) return "rust";
    if (rulePython(code)) return "python";
    if (ruleSql(code)) return "sql";
    if (ruleTypescript(code)) return "typescript";
    if (ruleJavascript(code)) return "javascript";
    if (ruleCss(code)) return "css";
    if (ruleHtml(code)) return "html";
    return "text";
}

/// Build the [system, user] chat messages for the provider layer. The code
/// is truncated BEFORE guessing: the heuristics only need a sample. Both
/// message contents are allocator-owned — free them when done. Twin of
/// buildPromptMessages() in src/lib/code-explainer.ts.
pub fn buildPromptMessages(
    allocator: std.mem.Allocator,
    code: []const u8,
    level: []const u8,
) ![2]ChatMessage {
    // Zig slices are bytes, so the truncation is byte-wise — identical to
    // the TS UTF-16 slice for all the BMP text code is made of.
    const body: []const u8 = if (code.len > max_code_chars)
        try std.fmt.allocPrint(allocator, "{s}\n… (code truncated)", .{code[0..max_code_chars]})
    else
        try allocator.dupe(u8, code);
    const lang = guessLanguage(body);
    const uncertainty: []const u8 = if (std.mem.eql(u8, lang, "text"))
        " (no clear language — say so and reason about it as pseudocode)"
    else
        "";
    const system = try std.fmt.allocPrint(
        allocator,
        "You explain code. {s} The code appears to be {s}{s}. Use short paragraphs or bullets; markdown is fine.",
        .{ levelContract(level), lang, uncertainty },
    );
    return .{
        .{ .role = "system", .content = system },
        .{ .role = "user", .content = body },
    };
}

/// Clean the model's reply into displayable explanation text: strip markdown
/// code fences (``` plus an optional [a-z] tag and newline), then trim.
/// Returns null when nothing survives cleaning (the TS port's null). The
/// caller owns the returned slice. Twin of parseExplanation().
pub fn parseExplanation(allocator: std.mem.Allocator, text: []const u8) !?[]u8 {
    const stripped = try allocator.alloc(u8, text.len);
    defer allocator.free(stripped);
    var o: usize = 0;
    var i: usize = 0;
    while (i < text.len) {
        if (i + 3 <= text.len and std.mem.eql(u8, text[i..][0..3], "```")) {
            i += 3;
            while (i < text.len and text[i] >= 'a' and text[i] <= 'z') i += 1;
            if (i < text.len and text[i] == '\n') i += 1;
            continue;
        }
        stripped[o] = text[i];
        o += 1;
        i += 1;
    }
    const trimmed = std.mem.trim(u8, stripped[0..o], " \t\n\r\x0b\x0c");
    if (trimmed.len == 0) return null;
    return try allocator.dupe(u8, trimmed);
}

test "guess the showcase languages" {
    const t = std.testing;
    try t.expectEqualStrings("go", guessLanguage("package main\nfunc main() {}"));
    try t.expectEqualStrings("rust", guessLanguage("fn main() { let mut x = 1; }"));
    try t.expectEqualStrings("python", guessLanguage("def hi():\n    print(hi())"));
    try t.expectEqualStrings("sql", guessLanguage("SELECT id FROM users"));
    try t.expectEqualStrings("typescript", guessLanguage("const x: number = 1"));
    try t.expectEqualStrings("text", guessLanguage("plain thoughts"));
}

test "build prompt and clean reply" {
    const t = std.testing;
    const allocator = t.allocator;

    const messages = try buildPromptMessages(allocator, "x = 1", "expert");
    defer allocator.free(messages[0].content);
    defer allocator.free(messages[1].content);
    try t.expectEqualStrings("x = 1", messages[1].content);
    try t.expect(std.mem.startsWith(
        u8,
        messages[0].content,
        "You explain code. Explain for an expert",
    ));
    try t.expect(std.mem.endsWith(
        u8,
        messages[0].content,
        "The code appears to be text (no clear language — say so and reason about it as pseudocode). Use short paragraphs or bullets; markdown is fine.",
    ));

    // Truncation appends the marker after max_code_chars bytes.
    const big = "a" ** 12010; // max_code_chars + 10
    const truncated = try buildPromptMessages(allocator, big, "beginner");
    defer allocator.free(truncated[0].content);
    defer allocator.free(truncated[1].content);
    try t.expectEqualStrings(big[0..max_code_chars] ++ "\n… (code truncated)", truncated[1].content);

    const cleaned = (try parseExplanation(allocator, "```python\nprint('hi')\n```\nIt prints!")).?;
    defer allocator.free(cleaned);
    try t.expectEqualStrings("It prints!", cleaned);

    try t.expectEqual(@as(?[]u8, null), try parseExplanation(allocator, "```\n```"));
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →