Skip to content

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

// code-explainer — language guessing, depth-graded prompts, reply cleanup.
//
// Language: Java (17, standard library only — java.util.regex speaks the
//           Perl dialect JavaScript borrowed, and \w / \b are ASCII-only
//           by default, so the TS heuristic rules port verbatim; Pattern
//           .MULTILINE and .CASE_INSENSITIVE 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. Java strings are UTF-16, so the truncation substring at
// MAX_CODE_CHARS is unit-for-unit identical to the TS code.slice(0, n).
// The top-level class is non-public so the filename may differ.
//
// Run: java java.java   (single-file source launch, Java 11+)

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/** code-explainer — pure logic, no I/O. */
final class CodeExplainer {

    /** Guess the language from (and prompt with) at most this many chars. */
    static final int 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". */
    private static final Map<String, String> LEVEL_CONTRACT = Map.of(
            "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.");

    /** One heuristic rule: the language it names and the regex that claims it. */
    private record LangRule(String lang, Pattern re) {}

    // 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 trio.
    private static final List<LangRule> RULES = List.of(
            new LangRule("go",
                    Pattern.compile("\\bpackage\\s+\\w+|\\bfunc\\s+\\w+|:=")),
            new LangRule("rust",
                    Pattern.compile("\\bfn\\s+\\w+|\\blet\\s+mut\\b|\\bimpl\\b")),
            new LangRule("python",
                    Pattern.compile(
                            "\\bdef\\s+\\w+\\s*\\(|\\bprint\\s*\\(|\\bimport\\s+\\w+\\s*$",
                            Pattern.MULTILINE)),
            new LangRule("sql",
                    Pattern.compile("\\bSELECT\\b.+\\bFROM\\b",
                            Pattern.CASE_INSENSITIVE)),
            new LangRule("typescript",
                    Pattern.compile(
                            "\\binterface\\s+\\w+\\s*\\{|\\btype\\s+\\w+\\s*=|:\\s*(string|number|boolean)\\b")),
            new LangRule("javascript",
                    Pattern.compile("\\bconst\\s+\\w+\\s*=|=>|console\\.log")),
            new LangRule("css",
                    Pattern.compile("[.#]?[\\w-]+\\s*\\{[^}]*:[^}]*;")),
            new LangRule("html",
                    Pattern.compile("</?[a-z][\\w-]*(\\s+[\\w-]+=\"[^\"]*\")*\\s*/?>",
                            Pattern.CASE_INSENSITIVE)));

    /**
     * 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. Twin of guessLanguage() in
     * src/lib/code-explainer.ts.
     */
    static String guessLanguage(String code) {
        for (LangRule rule : RULES) {
            if (rule.re().matcher(code).find()) return rule.lang();
        }
        return "text";
    }

    /** One [system, user] chat message for the provider layer. */
    record ChatMessage(String role, String content) {}

    /**
     * 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.
     */
    static List<ChatMessage> buildPromptMessages(String code, String level) {
        boolean truncated = code.length() > MAX_CODE_CHARS;
        String body = truncated
                ? code.substring(0, MAX_CODE_CHARS) + "\n… (code truncated)"
                : code;
        String lang = guessLanguage(body);
        String uncertainty = lang.equals("text")
                ? " (no clear language — say so and reason about it as pseudocode)"
                : "";
        String system = "You explain code. " + LEVEL_CONTRACT.getOrDefault(level, "")
                + " The code appears to be " + lang + uncertainty
                + ". Use short paragraphs or bullets; markdown is fine.";
        return List.of(new ChatMessage("system", system),
                new ChatMessage("user", body));
    }

    /** Strips ``` fences, with their optional language tag and newline
     *  (TS: /```[a-z]*\n?/g). */
    private static final Pattern FENCE = Pattern.compile("```[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 the TS lib.
     */
    static String parseExplanation(String text) {
        String cleaned = FENCE.matcher(text).replaceAll("").strip();
        return cleaned.isEmpty() ? null : cleaned;
    }

    public static void main(String[] args) {
        System.out.println(guessLanguage("package main\nfunc main() {}")); // go
        System.out.println(guessLanguage("def hi():\n    print(hi())"));   // python
        System.out.println(guessLanguage("SELECT id FROM users"));         // sql
        System.out.println(guessLanguage("plain thoughts"));               // text

        for (ChatMessage message : buildPromptMessages("x = 1", "expert")) {
            System.out.println(message.role() + ": " + message.content());
        }

        System.out.println(
                parseExplanation("```python\nprint('hi')\n```\nIt prints!"));
        System.out.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 →