Skip to content

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

// code-explainer — language guessing, depth-graded prompts, reply cleanup.
//
// Language: Swift (5, Foundation allowed — NSRegularExpression is the ICU
//           engine, the same family of patterns JavaScript's RegExp grew
//           out of; its \w / \b are ASCII-only, so the TS heuristic rules
//           port verbatim, with .anchorsMatchLines and .caseInsensitive
//           mirroring 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. One nuance: the TS lib truncates by UTF-16 unit, Swift slices
// by grapheme — identical for the BMP text code is made of.
//
// Run: swift swift.swift

import Foundation

/// One [system, user] chat message for the provider layer.
struct ChatMessage {
    let role: String
    let content: String
}

/// One heuristic rule: the language it names and the regex that claims it.
struct LangRule {
    let lang: String
    let re: NSRegularExpression
}

/// Guess the language from (and prompt with) at most this many chars.
let maxCodeChars = 12_000

/// Per-level explanation contract, verbatim from the TS lib. An unknown
/// level yields "" rather than the TS template's literal "undefined".
let levelContract: [String: String] = [
    "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.",
]

// 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.
let rules: [LangRule] = [
    LangRule(lang: "go", re: try! NSRegularExpression(pattern: #"\bpackage\s+\w+|\bfunc\s+\w+|:="#)),
    LangRule(lang: "rust", re: try! NSRegularExpression(pattern: #"\bfn\s+\w+|\blet\s+mut\b|\bimpl\b"#)),
    LangRule(lang: "python", re: try! NSRegularExpression(
        pattern: #"\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$"#,
        options: .anchorsMatchLines)),
    LangRule(lang: "sql", re: try! NSRegularExpression(
        pattern: #"\bSELECT\b.+\bFROM\b"#, options: .caseInsensitive)),
    LangRule(lang: "typescript", re: try! NSRegularExpression(
        pattern: #"\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b"#)),
    LangRule(lang: "javascript", re: try! NSRegularExpression(pattern: #"\bconst\s+\w+\s*=|=>|console\.log"#)),
    LangRule(lang: "css", re: try! NSRegularExpression(pattern: #"[.#]?[\w-]+\s*\{[^}]*:[^}]*;"#)),
    LangRule(lang: "html", re: try! NSRegularExpression(
        pattern: #"</?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*/?>"#,
        options: .caseInsensitive)),
]

/// 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.
func guessLanguage(_ code: String) -> String {
    let range = NSRange(code.startIndex..., in: code)
    for rule in rules where rule.re.firstMatch(in: code, range: range) != nil {
        return rule.lang
    }
    return "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.
func buildPromptMessages(_ code: String, level: String) -> [ChatMessage] {
    let truncated = code.utf16.count > maxCodeChars
    let body: String = truncated
        ? String(code.prefix(maxCodeChars)) + "\n… (code truncated)"
        : code
    let lang = guessLanguage(body)
    let uncertainty =
        lang == "text"
        ? " (no clear language — say so and reason about it as pseudocode)" : ""
    let contract = levelContract[level] ?? ""
    return [
        ChatMessage(
            role: "system",
            content: "You explain code. \(contract) The code appears to be "
                + "\(lang)\(uncertainty). Use short paragraphs or bullets; "
                + "markdown is fine."),
        ChatMessage(role: "user", content: body),
    ]
}

/// Clean the model's reply into displayable explanation text: strip markdown
/// code fences, then trim. Returns nil only when nothing survives cleaning —
/// there is no strict format contract beyond "non-empty". Twin of
/// parseExplanation() in src/lib/code-explainer.ts.
func parseExplanation(_ text: String) -> String? {
    let cleaned = text
        .replacingOccurrences(
            of: #"```[a-z]*\n?"#, with: "", options: .regularExpression)
        .trimmingCharacters(in: .whitespacesAndNewlines)
    return cleaned.isEmpty ? nil : cleaned
}

// Demo — `swift swift.swift`
print(guessLanguage("package main\nfunc main() {}"))  // go
print(guessLanguage("def hi():\n    print(hi())"))    // python
print(guessLanguage("SELECT id FROM users"))          // sql
print(guessLanguage("plain thoughts"))                // text

for message in buildPromptMessages("x = 1", level: "expert") {
    print("\(message.role): \(message.content)")
}

print(parseExplanation("```python\nprint('hi')\n```\nIt prints!") ?? "(nil)")
print(parseExplanation("```\n```") ?? "(nil)")

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 →