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++ (C++17, standard library only — <regex> speaks the
// ECMAScript dialect JavaScript borrowed, so the TS heuristic
// rules port verbatim: .icase for the sql/html rules, the C++17
// multiline flag for the python rule's $ anchor)
// 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. std::regex's ECMAScript grammar is ASCII-only for \w and \b,
// matching JavaScript exactly, so all eight rules are one-line regexes.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Build: c++ -std=c++17 cpp.cpp && ./a.out
#include <cstdio>
#include <optional>
#include <regex>
#include <string>
#include <vector>
namespace {
/// Prompt cap: guess from (and prompt with) at most this many chars.
constexpr size_t kMaxCodeChars = 12000;
/// Per-level explanation contract, verbatim from the TS lib. An unknown
/// level yields "" rather than the TS template's literal "undefined".
std::string level_contract(const std::string& level) {
if (level == "beginner")
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 (level == "developer")
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 (level == "expert")
return "Explain for an expert: dense and precise. Cover invariants, "
"complexity, edge cases, and anything subtle an experienced "
"reviewer would flag.";
return "";
}
/// One heuristic rule: the language it names and the regex that claims it.
struct Rule {
const char* lang;
std::regex 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 web trio.
const std::vector<Rule>& rules() {
static const std::vector<Rule> kRules = {
{"go", std::regex(R"(\bpackage\s+\w+|\bfunc\s+\w+|:=)")},
{"rust", std::regex(R"(\bfn\s+\w+|\blet\s+mut\b|\bimpl\b)")},
{"python",
std::regex(R"(\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$)",
std::regex::multiline)},
{"sql", std::regex(R"(\bSELECT\b.+\bFROM\b)", std::regex::icase)},
{"typescript",
std::regex(R"(\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b)")},
{"javascript", std::regex(R"(\bconst\s+\w+\s*=|=>|console\.log)")},
{"css", std::regex(R"([.#]?[\w-]+\s*\{[^}]*:[^}]*;)")},
{"html",
std::regex(R"(</?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*/?>)",
std::regex::icase)},
};
return kRules;
}
} // namespace
/// 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.
std::string guess_language(const std::string& code) {
for (const Rule& rule : rules())
if (std::regex_search(code, rule.re)) return rule.lang;
return "text";
}
/// One [system, user] chat message for the provider layer.
struct ChatMessage {
std::string role;
std::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.
std::vector<ChatMessage> build_prompt_messages(const std::string& code,
const std::string& level) {
const bool truncated = code.size() > kMaxCodeChars;
const std::string body = truncated
? code.substr(0, kMaxCodeChars) + "\n… (code truncated)"
: code;
const std::string lang = guess_language(body);
const std::string uncertainty =
lang == "text"
? " (no clear language — say so and reason about it as pseudocode)"
: "";
return {
{"system", "You explain code. " + level_contract(level)
+ " The code appears to be " + lang + uncertainty
+ ". Use short paragraphs or bullets; markdown is fine."},
{"user", body},
};
}
/// Strips ``` fences, with their optional language tag and newline
/// (TS: /```[a-z]*\n?/g).
const std::regex& fence_pattern() {
static const std::regex kFence(R"(```[a-z]*\n?)");
return kFence;
}
/// Clean the model's reply into displayable explanation text: strip markdown
/// code fences, then trim. nullopt only when nothing survives cleaning —
/// there is no strict format contract beyond "non-empty". Twin of
/// parseExplanation() in src/lib/code-explainer.ts.
std::optional<std::string> parse_explanation(const std::string& text) {
std::string cleaned = std::regex_replace(text, fence_pattern(), "");
static const char kWhitespace[] = " \t\n\r\v\f"; // JS .trim(), ASCII set
const size_t begin = cleaned.find_first_not_of(kWhitespace);
if (begin == std::string::npos) return std::nullopt;
const size_t end = cleaned.find_last_not_of(kWhitespace);
return cleaned.substr(begin, end - begin + 1);
}
// Demo
int main() {
std::printf("guess: %s\n", guess_language("package main\nfunc main() {}").c_str());
std::printf("guess: %s\n", guess_language("def hi():\n print(hi())").c_str());
std::printf("guess: %s\n", guess_language("SELECT id FROM users").c_str());
std::printf("guess: %s\n", guess_language("plain thoughts").c_str());
for (const ChatMessage& message : build_prompt_messages("x = 1", "expert"))
std::printf("%s: %s\n", message.role.c_str(), message.content.c_str());
const auto cleaned = parse_explanation("```python\nprint('hi')\n```\nIt prints!");
std::printf("cleaned: %s\n", cleaned ? cleaned->c_str() : "(none)");
std::printf("empty: %s\n",
parse_explanation("```\n```").has_value() ? "(non-null)" : "(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 →