AI Code Explainer — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package codeexplainer is the Go port of CosmoDev's src/lib/code-explainer.ts
// — language guessing, depth-graded prompt building, and reply cleanup for the
// AI code explainer (AI Studio tool #4, FEAT-076).
//
// Language: Go (standard library only).
// CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
// src/lib/code-explainer.ts (the canonical TypeScript implementation).
//
// Go's stdlib regexp (RE2) speaks the TS regex dialect, so the heuristic rules
// port verbatim; the level contract and truncation marker are byte-for-byte
// the TS strings. "No explanation survives" is reported as ok=false instead of
// the TS null, and an unknown level yields an empty contract rather than the
// literal "undefined" the TS template would interpolate.
//
// display source — part of CosmoDev's polyglot tool pages.
package codeexplainer
import (
"fmt"
"regexp"
"strings"
"unicode/utf8"
)
// MaxCodeChars caps how much code is sampled for language guessing and sent
// in the prompt (TS: MAX_CODE_CHARS).
const MaxCodeChars = 12000
// ExplanationLevel selects the depth contract baked into the system message.
type ExplanationLevel string
// The three depth knobs, mirroring the TS ExplanationLevel union.
const (
LevelBeginner ExplanationLevel = "beginner"
LevelDeveloper ExplanationLevel = "developer"
LevelExpert ExplanationLevel = "expert"
)
// levelContract is the per-level explanation contract, verbatim from the TS lib.
var levelContract = map[ExplanationLevel]string{
LevelBeginner: "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.",
LevelDeveloper: "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.",
LevelExpert: "Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.",
}
// langRules holds the cheap keyword heuristics in priority order — enough to
// name the language in the prompt so the model starts right; never a language
// detector. First match wins, so order matters: go before rust before python
// before the web trio.
var langRules = []struct {
lang string
re *regexp.Regexp
}{
{"go", regexp.MustCompile(`\bpackage\s+\w+|\bfunc\s+\w+|:=`)},
{"rust", regexp.MustCompile(`\bfn\s+\w+|\blet\s+mut\b|\bimpl\b`)},
{"python", regexp.MustCompile(`(?m)\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$`)},
{"sql", regexp.MustCompile(`(?i)\bSELECT\b.+\bFROM\b`)},
{"typescript", regexp.MustCompile(`\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b`)},
{"javascript", regexp.MustCompile(`\bconst\s+\w+\s*=|=>|console\.log`)},
{"css", regexp.MustCompile(`[.#]?[\w-]+\s*\{[^}]*:[^}]*;`)},
{"html", regexp.MustCompile(`(?i)</?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*/?>`)},
}
// GuessLanguage guesses which language a code sample is written in, falling
// back to "text" so the prompt can ask the model to treat the paste as
// pseudocode. Twin of guessLanguage() in src/lib/code-explainer.ts.
func GuessLanguage(code string) string {
for _, rule := range langRules {
if rule.re.MatchString(code) {
return rule.lang
}
}
return "text"
}
// ChatMessage is one entry of the provider-layer conversation.
type ChatMessage struct {
Role string // "system" or "user"
Content string
}
// BuildPromptMessages builds 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. Twin of
// buildPromptMessages() in src/lib/code-explainer.ts.
func BuildPromptMessages(code string, level ExplanationLevel) []ChatMessage {
body := code
if utf8.RuneCountInString(code) > MaxCodeChars {
body = truncateRunes(code, MaxCodeChars) + "\n… (code truncated)"
}
lang := GuessLanguage(body)
pseudo := ""
if lang == "text" {
pseudo = " (no clear language — say so and reason about it as pseudocode)"
}
system := fmt.Sprintf(
"You explain code. %s The code appears to be %s%s. Use short paragraphs or bullets; markdown is fine.",
levelContract[level], lang, pseudo,
)
return []ChatMessage{{Role: "system", Content: system}, {Role: "user", Content: body}}
}
// ParseExplanation cleans the model's reply into displayable explanation text:
// strip markdown code fences, then trim. ok is false only when nothing
// survives cleaning (the TS port returns null). Twin of parseExplanation().
func ParseExplanation(text string) (cleaned string, ok bool) {
cleaned = strings.TrimSpace(fencePattern.ReplaceAllString(text, ""))
return cleaned, cleaned != ""
}
// fencePattern strips ``` fences, with their optional language tag and newline
// (TS: /```[a-z]*\n?/g). RE2 replaces every non-overlapping match, like the
// TS /g flag.
var fencePattern = regexp.MustCompile("```[a-z]*\n?")
// truncateRunes keeps the first n runes of s. The TS lib slices UTF-16 code
// units; counting runes is the closest UTF-8-native equivalent and identical
// for BMP text (i.e. all code).
func truncateRunes(s string, n int) string {
if utf8.RuneCountInString(s) <= n {
return s
}
count := 0
for i := range s {
if count == n {
return s[:i]
}
count++
}
return s
}
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 →