Skip to content

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

//! code-explainer — language guessing, depth-graded prompts, reply cleanup.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
//! src/lib/code-explainer.ts (the canonical TypeScript implementation).
//!
//! The TS heuristics lean on regex and std Rust has no regex crate, so each
//! rule becomes a small hand-rolled scanner over the same tokens in the same
//! priority order — that substitution is why this port runs longer than the
//! lib it mirrors. Truncation, prompt assembly, and fence-stripping port
//! directly; `\s` here is ASCII whitespace (JS `\s` adds a few Unicode
//! spaces, irrelevant for code).
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// Depth knobs for the prompt, mirroring the TS `ExplanationLevel` union.
pub const LEVELS: [&str; 3] = ["beginner", "developer", "expert"];

/// Guess the language from (and prompt with) at most this many chars.
pub const MAX_CODE_CHARS: usize = 12_000;

/// Per-level explanation contract, verbatim from the TS lib. (The TS template
/// would interpolate "undefined" for an unknown level; we interpolate empty.)
fn level_contract(level: &str) -> &'static str {
    match level {
        "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.",
        "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.",
        "expert" => "Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.",
        _ => "",
    }
}

fn is_word(b: u8) -> bool { b.is_ascii_alphanumeric() || b == b'_' }
fn is_ws(b: u8) -> bool { matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) }

/// First index at/after `from` where `kw` occurs as a whole word (JS `\b` on
/// both sides), byte-wise or case-insensitively when `ci`.
fn word_at(hay: &[u8], kw: &[u8], from: usize, ci: bool) -> Option<usize> {
    let mut i = from;
    while i + kw.len() <= hay.len() {
        let hit = if ci { hay[i..i + kw.len()].eq_ignore_ascii_case(kw) } else { &hay[i..i + kw.len()] == kw };
        let bounded = (i == 0 || !is_word(hay[i - 1])) && (i + kw.len() == hay.len() || !is_word(hay[i + kw.len()]));
        if hit && bounded {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// `\b kw \s{min,}` — whole-word `kw`, then whitespace; hands `rest` the byte
/// index just past it for each candidate match.
fn kw_then(hay: &[u8], kw: &[u8], min_ws: usize, rest: &mut dyn FnMut(usize) -> bool) -> bool {
    let mut from = 0;
    while let Some(p) = word_at(hay, kw, from, false) {
        let (ws0, mut j) = (p + kw.len(), p + kw.len());
        while j < hay.len() && is_ws(hay[j]) { j += 1; }
        if j - ws0 >= min_ws && rest(j) { return true; }
        from = p + 1;
    }
    false
}

/// `\w+ \s* X` at `j` — a word run, optional whitespace, then byte `x`.
fn word_ws_x(hay: &[u8], j: usize, x: u8) -> bool {
    let mut k = j;
    while k < hay.len() && is_word(hay[k]) { k += 1; }
    if k == j { return false; }
    while k < hay.len() && is_ws(hay[k]) { k += 1; }
    k < hay.len() && hay[k] == x
}

/// `\bimport\s+\w+\s*$` (multiline). `\s*` may backtrack before `$`, so the
/// trailing whitespace scan never crosses the newline it must stop at.
fn import_eol(b: &[u8]) -> bool {
    kw_then(b, b"import", 1, &mut |j| {
        let mut k = j;
        while k < b.len() && is_word(b[k]) { k += 1; }
        if k == j { return false; }
        while k < b.len() && is_ws(b[k]) && b[k] != b'\n' { k += 1; }
        k == b.len() || b[k] == b'\n' || b[k] == b'\r'
    })
}

/// `(?i)\bSELECT\b.+\bFROM\b` — `.` never matches a newline, so both keywords
/// must sit on the same line with at least one character between them.
fn rule_sql(c: &str) -> bool {
    c.split('\n').any(|line| {
        let b = line.as_bytes();
        let mut from = 0;
        while let Some(p) = word_at(b, b"SELECT", from, true) {
            if word_at(b, b"FROM", p + 7, true).is_some() { return true; }
            from = p + 1;
        }
        false
    })
}

/// `:\s*(string|number|boolean)\b` — a type annotation naming a TS primitive.
fn colon_type(b: &[u8]) -> bool {
    (0..b.len()).any(|i| {
        if b[i] != b':' { return false; }
        let mut j = i + 1;
        while j < b.len() && is_ws(b[j]) { j += 1; }
        [&b"string"[..], b"number", b"boolean"].iter().any(|ty| {
            j + ty.len() <= b.len()
                && &b[j..j + ty.len()] == *ty
                && (j + ty.len() == b.len() || !is_word(b[j + ty.len()]))
        })
    })
}

/// `[.#]?[\w-]+\s*\{[^}]*:[^}]*;` — a selector-ish brace block whose body
/// (before any `}`) contains `name: value;`.
fn rule_css(c: &str) -> bool {
    let b = c.as_bytes();
    (0..b.len()).any(|k| {
        if b[k] != b'{' { return false; }
        let mut j = k;
        while j > 0 && is_ws(b[j - 1]) { j -= 1; }
        let mut w = j;
        while w > 0 && (is_word(b[w - 1]) || b[w - 1] == b'-') { w -= 1; }
        if w == j { return false; } // no selector chars before the brace
        let (mut colon, mut m) = (false, k + 1);
        while m < b.len() && b[m] != b'}' {
            if b[m] == b':' { colon = true; }
            if b[m] == b';' && colon { return true; }
            m += 1;
        }
        false
    })
}

/// `(?i)</?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*/?>` — opening or closing tag;
/// attribute groups backtrack, so a failed group restarts the tail at `save`.
fn rule_html(c: &str) -> bool {
    let b = c.as_bytes();
    (0..b.len()).any(|i| {
        if b[i] != b'<' { return false; }
        let mut j = i + 1;
        if j < b.len() && b[j] == b'/' { j += 1; }
        if j >= b.len() || !b[j].is_ascii_alphabetic() { return false; }
        while j < b.len() && (is_word(b[j]) || b[j] == b'-') { j += 1; }
        loop {
            let (save, mut k) = (j, j);
            while k < b.len() && is_ws(b[k]) { k += 1; }
            if k == save { break; } // `\s+` unmet: no (more) attributes
            let name0 = k;
            while k < b.len() && (is_word(b[k]) || b[k] == b'-') { k += 1; }
            if k == name0 || k >= b.len() || b[k] != b'=' || k + 1 >= b.len() || b[k + 1] != b'"' {
                j = save;
                break;
            }
            k += 2;
            while k < b.len() && b[k] != b'"' { k += 1; }
            if k >= b.len() { j = save; break; } // unterminated quote
            j = k + 1;
        }
        while j < b.len() && is_ws(b[j]) { j += 1; }
        if j < b.len() && b[j] == b'/' { j += 1; }
        j < b.len() && b[j] == b'>'
    })
}

/// Guess the language of a code sample. Falls back to "text" when no rule
/// matches, so the prompt can ask the model to treat the paste as pseudocode.
/// First match wins, so order matters: go before rust before python before
/// the web trio.
pub fn guess_language(code: &str) -> &'static str {
    let rules: [(&str, fn(&str) -> bool); 8] = [
        ("go", |c| {
            let b = c.as_bytes();
            kw_then(b, b"package", 1, &mut |j| j < b.len() && is_word(b[j]))
                || kw_then(b, b"func", 1, &mut |j| j < b.len() && is_word(b[j]))
                || c.contains(":=")
        }),
        ("rust", |c| {
            let b = c.as_bytes();
            kw_then(b, b"fn", 1, &mut |j| j < b.len() && is_word(b[j]))
                || kw_then(b, b"let", 1, &mut |j| word_at(b, b"mut", j, false) == Some(j))
                || word_at(b, b"impl", 0, false).is_some()
        }),
        ("python", |c| {
            let b = c.as_bytes();
            kw_then(b, b"def", 1, &mut |j| word_ws_x(b, j, b'('))
                || kw_then(b, b"print", 0, &mut |j| j < b.len() && b[j] == b'(')
                || import_eol(b)
        }),
        ("sql", rule_sql),
        ("typescript", |c| {
            let b = c.as_bytes();
            kw_then(b, b"interface", 1, &mut |j| word_ws_x(b, j, b'{'))
                || kw_then(b, b"type", 1, &mut |j| word_ws_x(b, j, b'='))
                || colon_type(b)
        }),
        ("javascript", |c| {
            let b = c.as_bytes();
            kw_then(b, b"const", 1, &mut |j| word_ws_x(b, j, b'='))
                || c.contains("=>")
                || c.contains("console.log")
        }),
        ("css", rule_css),
        ("html", rule_html),
    ];
    for (lang, rule) in rules {
        if rule(code) {
            return lang;
        }
    }
    "text"
}

/// One entry of the provider-layer conversation.
pub struct ChatMessage {
    pub role: &'static str,
    pub content: String,
}

/// Build the [system, user] chat messages for the provider layer. The code is
/// truncated BEFORE guessing: the heuristics only need a sample, and running
/// them over a 30k-char paste is pure waste. The TS lib slices UTF-16 code
/// units; we count chars (Unicode scalars) — identical for BMP text.
pub fn build_prompt_messages(code: &str, level: &str) -> [ChatMessage; 2] {
    let truncated = code.chars().count() > MAX_CODE_CHARS;
    let body = if truncated {
        format!("{}\n… (code truncated)", code.chars().take(MAX_CODE_CHARS).collect::<String>())
    } else {
        code.to_string()
    };
    let lang = guess_language(&body);
    let pseudo = if lang == "text" {
        " (no clear language — say so and reason about it as pseudocode)"
    } else {
        ""
    };
    let system = format!(
        "You explain code. {} The code appears to be {}{}. Use short paragraphs or bullets; markdown is fine.",
        level_contract(level),
        lang,
        pseudo
    );
    [
        ChatMessage { role: "system", content: system },
        ChatMessage { role: "user", content: body },
    ]
}

/// Clean the model's reply into displayable explanation text: strip markdown
/// code fences (```lang plus one newline), then trim. `None` only when nothing
/// survives cleaning — there is no strict format contract beyond "non-empty".
pub fn parse_explanation(text: &str) -> Option<String> {
    let b = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < b.len() {
        if b[i..].starts_with(b"```") {
            i += 3;
            while i < b.len() && b[i].is_ascii_lowercase() { i += 1; }
            if i < b.len() && b[i] == b'\n' { i += 1; }
        } else {
            let n = b[i].leading_ones().max(1) as usize; // UTF-8 scalar length (valid &str)
            out.push_str(&text[i..i + n]);
            i += n;
        }
    }
    let trimmed = out.trim();
    if trimmed.is_empty() { None } else { Some(trimmed.to_string()) }
}

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 →