Skip to content

AI Code Explainer — C 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 C implementation — the same logic the interactive tool runs, in a shareable, citable form.

/*
 * code-explainer — language guessing, depth-graded prompts, reply cleanup.
 *
 * Language: C (C11, standard library only — C has no regex engine, so the
 *           eight heuristic rules are hand-rolled scanners, the same route
 *           src/tool-sources/base64/c.c took for its Base64 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 TS /m flag).
 *
 * display source — part of CosmoDev's polyglot tool pages.
 *
 * Build: cc -std=c11 c.c && ./a.out
 */

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/** Prompt cap: guess from (and send) at most this many bytes (TS: 12000). */
#define MAX_CODE_CHARS 12000

/** One [system, user] chat message for the provider layer. */
typedef struct {
    char *role;
    char *content;
} ChatMessage;

/** Per-level explanation contract, verbatim from the TS lib. An unknown
 *  level yields "" rather than the TS template's literal "undefined". */
static const char *level_contract(const char *level)
{
    if (strcmp(level, "beginner") == 0)
        return "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.";
    if (strcmp(level, "developer") == 0)
        return "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.";
    if (strcmp(level, "expert") == 0)
        return "Explain for an expert: dense and precise. Cover invariants, "
               "complexity, edge cases, and anything subtle an experienced "
               "reviewer would flag.";
    return "";
}

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

static bool is_word(char c) { return isalnum((unsigned char)c) || c == '_'; }

static bool is_sp(char c)
{
    return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f'
        || c == '\r';
}

/** malloc-copy the first n bytes of s, NUL-terminated. */
static char *dup_range(const char *s, size_t n)
{
    char *out = malloc(n + 1);
    if (out != NULL) {
        memcpy(out, s, n);
        out[n] = '\0';
    }
    return out;
}

/** First whole-word hit of `lit` at/after `from` (\blit\b: a non-word char
 *  or a string edge on both flanks). Returns its offset, or -1. */
static long word_at(const char *s, const char *lit, long from)
{
    size_t n = strlen(lit);
    for (const char *p = strstr(s + from, lit); p != NULL;
         p = strstr(p + 1, lit))
        if ((p == s || !is_word(p[-1])) && (p[n] == '\0' || !is_word(p[n])))
            return p - s;
    return -1;
}

/** word_at() with the /i flag: case-insensitive, lowercased `lit`. */
static long word_at_ci(const char *s, const char *lit, long from)
{
    size_t n = strlen(lit);
    for (const char *p = s + from; *p != '\0'; p++)
        if ((p == s || !is_word(p[-1])) && (p[n] == '\0' || !is_word(p[n]))) {
            size_t i = 0;
            while (i < n
                   && tolower((unsigned char)p[i]) == (unsigned char)lit[i])
                i++;
            if (i == n) return p - s;
        }
    return -1;
}

/** \b<kw>\s+\w+ — whole-word keyword, at least one space, then a word run.
 *  Returns the offset just past the run, or -1. Shared by the go / rust /
 *  python / typescript / javascript rules. */
static long kw_run_end(const char *s, const char *kw, long from)
{
    size_t n = strlen(kw);
    for (long at = word_at(s, kw, from); at >= 0;
         at = word_at(s, kw, at + 1)) {
        const char *q = s + at + n;
        while (is_sp(*q)) q++;                  /* \s+ */
        if (q > s + at + n && is_word(*q)) {    /* a \w+ run must follow */
            while (is_word(*q)) q++;
            return q - s;
        }
    }
    return -1;
}

/** \s* followed by `c`, from the end of a keyword's word run. */
static bool then_char(const char *e, char c)
{
    while (is_sp(*e)) e++;
    return *e == c;
}

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

/* \bpackage\s+\w+ | \bfunc\s+\w+ | := */
static bool rule_go(const char *s)
{
    return kw_run_end(s, "package", 0) >= 0 || kw_run_end(s, "func", 0) >= 0
        || strstr(s, ":=") != NULL;
}

/* \bfn\s+\w+ | \blet\s+mut\b | \bimpl\b */
static bool rule_rust(const char *s)
{
    long at = word_at(s, "let", 0);
    if (at >= 0) {
        const char *q = s + at + 3;
        while (is_sp(*q)) q++;                  /* \s+ */
        if (q > s + at + 3 && strncmp(q, "mut", 3) == 0 && !is_word(q[3]))
            return true;
    }
    return kw_run_end(s, "fn", 0) >= 0 || word_at(s, "impl", 0) >= 0;
}

/* \bdef\s+\w+\s*\( | \bprint\s*\( | \bimport\s+\w+\s*$ — the TS /m flag,
 * so the $ also matches just before a newline. */
static bool rule_python(const char *s)
{
    long e = kw_run_end(s, "def", 0);
    if (e >= 0 && then_char(s + e, '(')) return true;
    long p = word_at(s, "print", 0);
    if (p >= 0 && then_char(s + p + 5, '(')) return true;
    e = kw_run_end(s, "import", 0);
    if (e < 0) return false;
    const char *q = s + e;
    while (is_sp(*q) && *q != '\n') q++;        /* \s*$, line-wise */
    return *q == '\n' || *q == '\0';
}

/* \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. */
static bool rule_sql(const char *s)
{
    for (long at = word_at_ci(s, "select", 0); at >= 0;
         at = word_at_ci(s, "select", at + 1)) {
        const char *e = s + at + 6;
        if (*e == '\n' || *e == '\0') continue; /* .+ needs a same-line char */
        for (const char *q = e + 1; *q != '\0' && *q != '\n'; q++)
            if (!is_word(q[-1])
                && tolower((unsigned char)q[0]) == 'f'
                && tolower((unsigned char)q[1]) == 'r'
                && tolower((unsigned char)q[2]) == 'o'
                && tolower((unsigned char)q[3]) == 'm'
                && !is_word(q[4]))
                return true;
    }
    return false;
}

/* (string|number|boolean)\b at e — the tail of the colon-type rule. */
static bool ts_type_at(const char *e)
{
    static const char *const lits[] = {"string", "number", "boolean"};
    for (int i = 0; i < 3; i++) {
        size_t n = strlen(lits[i]);
        if (strncmp(e, lits[i], n) == 0 && !is_word(e[n])) return true;
    }
    return false;
}

/* \binterface\s+\w+\s*\{ | \btype\s+\w+\s*= | :\s*(string|number|boolean)\b */
static bool rule_typescript(const char *s)
{
    long e = kw_run_end(s, "interface", 0);
    if (e >= 0 && then_char(s + e, '{')) return true;
    e = kw_run_end(s, "type", 0);
    if (e >= 0 && then_char(s + e, '=')) return true;
    for (const char *c = strchr(s, ':'); c != NULL; c = strchr(c + 1, ':')) {
        const char *q = c + 1;                  /* : \s* */
        while (is_sp(*q)) q++;
        if (ts_type_at(q)) return true;
    }
    return false;
}

/* \bconst\s+\w+\s*= | => | console\.log */
static bool rule_javascript(const char *s)
{
    long e = kw_run_end(s, "const", 0);
    return (e >= 0 && then_char(s + e, '=')) || strstr(s, "=>") != NULL
        || strstr(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. */
static bool rule_css(const char *s)
{
    for (const char *b = strchr(s, '{'); b != NULL; b = strchr(b + 1, '{')) {
        const char *q = b;                      /* \s* backwards */
        while (q > s && is_sp(q[-1])) q--;
        long n = 0;                             /* [\w-]+ backwards */
        while (q > s && (is_word(q[-1]) || q[-1] == '-')) { q--; n++; }
        if (n == 0) continue;
        if (q > s && (q[-1] == '.' || q[-1] == '#')) q--;  /* [.#]? */
        const char *e = b;                      /* [^}]* ends at } or EOS */
        while (*e != '\0' && *e != '}') e++;
        const char *c = memchr(b + 1, ':', (size_t)(e - b - 1));
        if (c != NULL && memchr(c + 1, ';', (size_t)(e - c - 1)) != NULL)
            return true;
    }
    return false;
}

/* </?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*\/?> case-insensitively */
static bool rule_html(const char *s)
{
    for (const char *p = strchr(s, '<'); p != NULL; p = strchr(p + 1, '<')) {
        const char *q = p + 1;
        if (*q == '/') q++;
        if (!isalpha((unsigned char)*q)) continue;  /* [a-z], with /i */
        q++;
        while (is_word(*q) || *q == '-') q++;       /* [\w-]* */
        for (;;) {                                  /* (\s+[\w-]+="[^"]*")* */
            const char *k = q;
            while (is_sp(*k)) k++;                  /* \s+ */
            const char *a = k;
            while (is_word(*a) || *a == '-') a++;   /* [\w-]+ */
            if (a > k && *a == '=' && a[1] == '"') {
                const char *v = strchr(a + 2, '"');
                if (v == NULL) break;               /* [^"]* ran past EOS */
                q = v + 1;
            } else {
                break;                              /* no further attribute */
            }
        }
        while (is_sp(*q)) q++;                      /* \s* */
        if (*q == '/') q++;                         /* \/ ? */
        if (*q == '>') return true;
    }
    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.
 */
const char *guess_language(const char *code)
{
    if (rule_go(code)) return "go";
    if (rule_rust(code)) return "rust";
    if (rule_python(code)) return "python";
    if (rule_sql(code)) return "sql";
    if (rule_typescript(code)) return "typescript";
    if (rule_javascript(code)) return "javascript";
    if (rule_css(code)) return "css";
    if (rule_html(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
 *  strings are malloc'd — free() them when done; returns NULL-filled outs
 *  and -1 only on allocation failure. Twin of buildPromptMessages() in
 *  src/lib/code-explainer.ts. */
static const char PROMPT_FMT[] = "You explain code. %s The code appears to "
    "be %s%s. Use short paragraphs or bullets; markdown is fine.";

int build_prompt_messages(const char *code, const char *level, char **system,
                          char **user)
{
    char *body;
    if (strlen(code) > MAX_CODE_CHARS) {
        /* C strings are bytes, so the slice is byte-wise — identical to the
         * TS UTF-16 slice for all the BMP text code is made of. */
        body = malloc(MAX_CODE_CHARS + sizeof "\n… (code truncated)");
        if (body == NULL) return -1;
        memcpy(body, code, MAX_CODE_CHARS);
        memcpy(body + MAX_CODE_CHARS, "\n… (code truncated)",
               sizeof "\n… (code truncated)");
    } else {
        body = dup_range(code, strlen(code));
        if (body == NULL) return -1;
    }
    const char *lang = guess_language(body);
    const char *uncertainty =
        strcmp(lang, "text") == 0
            ? " (no clear language — say so and reason about it as pseudocode)"
            : "";
    const char *contract = level_contract(level);
    int need = snprintf(NULL, 0, PROMPT_FMT, contract, lang, uncertainty);
    if (need < 0) {
        free(body);
        return -1;
    }
    *system = malloc((size_t)need + 1);
    if (*system == NULL) {
        free(body);
        return -1;
    }
    (void)snprintf(*system, (size_t)need + 1, PROMPT_FMT, contract, lang,
                   uncertainty);
    *user = body;
    return 0;
}

/** Clean the model's reply into displayable explanation text: strip markdown
 *  code fences (``` plus an optional [a-z] tag and newline), then trim.
 *  Returns a malloc'd string, or NULL when nothing survives cleaning (the
 *  TS port's null). Twin of parseExplanation(). */
char *parse_explanation(const char *text)
{
    size_t len = strlen(text);
    char *out = malloc(len + 1);
    if (out == NULL) return NULL;
    size_t o = 0;
    for (size_t i = 0; i < len;) {
        if (i + 3 <= len && memcmp(text + i, "```", 3) == 0) {
            i += 3;
            while (i < len && text[i] >= 'a' && text[i] <= 'z') i++;
            if (i < len && text[i] == '\n') i++;
        } else {
            out[o++] = text[i++];
        }
    }
    out[o] = '\0';
    char *a = out;
    while (*a != '\0' && is_sp(*a)) a++;        /* JS .trim(), ASCII members */
    char *z = a + strlen(a);
    while (z > a && is_sp(z[-1])) z--;
    if (z == a) {                               /* nothing survived: null */
        free(out);
        return NULL;
    }
    memmove(out, a, (size_t)(z - a));
    out[z - a] = '\0';
    return out;
}

/* ---------------------------------------------------------------------------
 * Demo
 * ------------------------------------------------------------------------- */

int main(void)
{
    printf("guess: %s\n", guess_language("package main\nfunc main() {}"));
    printf("guess: %s\n", guess_language("def hi():\n    print(hi())"));
    printf("guess: %s\n", guess_language("SELECT id FROM users"));
    printf("guess: %s\n", guess_language("plain thoughts"));

    char *system_msg = NULL, *user_msg = NULL;
    if (build_prompt_messages("x = 1", "expert", &system_msg, &user_msg) == 0) {
        printf("system: %s\n", system_msg);
        printf("user:   %s\n", user_msg);
    }
    free(system_msg);
    free(user_msg);

    char *clean = parse_explanation("```python\nprint('hi')\n```\nIt prints!");
    printf("cleaned: %s\n", clean != NULL ? clean : "(null)");
    free(clean);

    printf("empty: %s\n",
           parse_explanation("```\n```") == NULL ? "(null)" : "(non-null)");
    return 0;
}

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 →