Skip to content

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

// code-explainer — language guessing, depth-graded prompts, reply cleanup.
//
// Language: Kotlin (JVM, standard library only — kotlin.text.Regex wraps
//           java.util.regex, whose \w and \b are ASCII-only by default, so
//           the TS heuristic rules port verbatim; RegexOption.MULTILINE and
//           .IGNORE_CASE mirror the /m and /i flags)
// 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 which language a paste is, wrap it in a depth-graded chat prompt,
// strip code fences from the reply — so every runtime runs the identical
// heuristics. Kotlin strings are UTF-16, so take(MAX_CODE_CHARS) slices
// unit-for-unit like the TS code.slice(0, n), and raw strings ("""...""")
// keep every rule regex backslash-free.
//
// Run: kotlinc kotlin.kt -include-runtime -d code-explainer.jar && java -jar code-explainer.jar

import java.util.regex.Pattern

/** One [system, user] chat message for the provider layer. */
data class ChatMessage(val role: String, val content: String)

/** One heuristic rule: the language it names and the regex that claims it. */
data class LangRule(val lang: String, val re: Regex)

/** Depth knob for the prompt: how much explanation contract the model gets. */
val EXPLANATION_LEVELS = listOf("beginner", "developer", "expert")

/** Guess the language from (and prompt with) at most this many chars. */
const val MAX_CODE_CHARS = 12000

/** Per-level explanation contract, verbatim from the TS lib. An unknown
 *  level yields "" rather than the TS template's literal "undefined". */
val LEVEL_CONTRACT: Map<String, String> = mapOf(
    "beginner" to
        "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" to
        "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" to
        "Explain for an expert: dense and precise. Cover invariants, " +
        "complexity, edge cases, and anything subtle an experienced " +
        "reviewer would flag.",
)

// Cheap keyword heuristics — 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.
private val RULES = listOf(
    LangRule("go", Regex("""\bpackage\s+\w+|\bfunc\s+\w+|:=""")),
    LangRule("rust", Regex("""\bfn\s+\w+|\blet\s+mut\b|\bimpl\b""")),
    LangRule(
        "python",
        Regex("""\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$""", RegexOption.MULTILINE),
    ),
    LangRule("sql", Regex("""\bSELECT\b.+\bFROM\b""", RegexOption.IGNORE_CASE)),
    LangRule(
        "typescript",
        Regex("""\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b"""),
    ),
    LangRule("javascript", Regex("""\bconst\s+\w+\s*=|=>|console\.log""")),
    LangRule("css", Regex("""[.#]?[\w-]+\s*\{[^}]*:[^}]*;""")),
    LangRule(
        "html",
        Regex("""</?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*/?>""", RegexOption.IGNORE_CASE),
    ),
)

/**
 * Guess which language a code sample is written in. Falls back to "text"
 * when no rule matches, so the prompt can tell the model to reason about
 * the paste as pseudocode instead of pretending to know better. Twin of
 * guessLanguage() in src/lib/code-explainer.ts.
 */
fun guessLanguage(code: String): String =
    RULES.firstOrNull { it.re.containsMatchIn(code) }?.lang ?: "text"

/**
 * 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. Twin of
 * buildPromptMessages() in src/lib/code-explainer.ts.
 */
fun buildPromptMessages(code: String, level: String): List<ChatMessage> {
    val body =
        if (code.length > MAX_CODE_CHARS) {
            code.take(MAX_CODE_CHARS) + "\n… (code truncated)"
        } else {
            code
        }
    val lang = guessLanguage(body)
    val uncertainty =
        if (lang == "text") {
            " (no clear language — say so and reason about it as pseudocode)"
        } else {
            ""
        }
    val system =
        "You explain code. ${LEVEL_CONTRACT[level] ?: ""} The code appears to be " +
            "$lang$uncertainty. Use short paragraphs or bullets; markdown is fine."
    return listOf(ChatMessage("system", system), ChatMessage("user", body))
}

/** Strips ``` fences, with their optional language tag and newline
 *  (TS: /```[a-z]*\n?/g). */
private val FENCE = Regex("""```[a-z]*\n?""")

/**
 * Clean the model's reply into displayable explanation text: strip markdown
 * code fences, then trim. Returns null only when nothing survives cleaning —
 * there is no strict format contract beyond "non-empty". Twin of
 * parseExplanation() in src/lib/code-explainer.ts.
 */
fun parseExplanation(text: String): String? =
    text.replace(FENCE, "").trim().ifEmpty { null }

fun main() {
    println(guessLanguage("package main\nfunc main() {}")) // go
    println(guessLanguage("def hi():\n    print(hi())"))   // python
    println(guessLanguage("SELECT id FROM users"))         // sql
    println(guessLanguage("plain thoughts"))               // text

    buildPromptMessages("x = 1", "expert").forEach { (role, content) ->
        println("$role: $content")
    }

    println(parseExplanation("```python\nprint('hi')\n```\nIt prints!"))
    println(parseExplanation("```\n```") ?: "(null)")
}

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 →