import type { CodingLanguage } from "./types"; // --------------------------------------------------------------------------- // Tiny, dependency-free syntax tokenizer. // // Produces a flat, *lossless* token stream (concatenating token text always // reproduces the input) that a React component renders with colored spans. // Good enough for clear, readable highlighting of the languages we support // without pulling in a heavy highlighter dependency. // --------------------------------------------------------------------------- export type TokenKind = | "keyword" | "string" | "comment" | "number" | "plain"; export interface Token { text: string; kind: TokenKind; } const KEYWORDS: Record> = { javascript: new Set([ "function", "return", "const", "let", "var", "if", "else", "for", "while", "do", "switch", "case", "break", "continue", "new", "class", "extends", "super", "this", "typeof", "instanceof", "in", "of", "try", "catch", "finally", "throw", "async", "await", "yield", "import", "export", "from", "default", "null", "undefined", "true", "false", "void", "delete", ]), typescript: new Set([ "function", "return", "const", "let", "var", "if", "else", "for", "while", "do", "switch", "case", "break", "continue", "new", "class", "extends", "super", "this", "typeof", "instanceof", "in", "of", "try", "catch", "finally", "throw", "async", "await", "yield", "import", "export", "from", "default", "null", "undefined", "true", "false", "void", "delete", "interface", "type", "enum", "implements", "public", "private", "protected", "readonly", "as", "namespace", "declare", "abstract", "string", "number", "boolean", "any", "unknown", "never", ]), python: new Set([ "def", "return", "if", "elif", "else", "for", "while", "break", "continue", "class", "import", "from", "as", "try", "except", "finally", "raise", "with", "lambda", "yield", "global", "nonlocal", "pass", "and", "or", "not", "in", "is", "None", "True", "False", "async", "await", "self", ]), go: new Set([ "func", "return", "if", "else", "for", "range", "switch", "case", "default", "break", "continue", "var", "const", "type", "struct", "interface", "map", "chan", "go", "defer", "select", "package", "import", "nil", "true", "false", "make", "new", "string", "int", "bool", "error", "byte", "rune", ]), }; /** Languages that use `#` for line comments (otherwise `//`). */ const HASH_COMMENT: Partial> = { python: true }; const WORD_RE = /[A-Za-z_$][A-Za-z0-9_$]*/y; const NUMBER_RE = /\d+(?:\.\d+)?/y; const DQ_STRING_RE = /"(?:\\.|[^"\\])*"?/y; const SQ_STRING_RE = /'(?:\\.|[^'\\])*'?/y; const TPL_STRING_RE = /`(?:\\.|[^`\\])*`?/y; const BLOCK_COMMENT_RE = /\/\*[\s\S]*?(?:\*\/|$)/y; const SLASH_COMMENT_RE = /\/\/[^\n]*/y; const HASH_COMMENT_RE = /#[^\n]*/y; function tryMatch(re: RegExp, code: string, pos: number): string | null { re.lastIndex = pos; const m = re.exec(code); return m && m.index === pos ? m[0] : null; } export function tokenize(code: string, language: CodingLanguage): Token[] { const keywords = KEYWORDS[language]; const usesHash = HASH_COMMENT[language] ?? false; const tokens: Token[] = []; let plain = ""; let pos = 0; const flushPlain = () => { if (plain) { tokens.push({ text: plain, kind: "plain" }); plain = ""; } }; while (pos < code.length) { // Comments let m: string | null; if (!usesHash && (m = tryMatch(BLOCK_COMMENT_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "comment" }); pos += m.length; continue; } if (!usesHash && (m = tryMatch(SLASH_COMMENT_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "comment" }); pos += m.length; continue; } if (usesHash && (m = tryMatch(HASH_COMMENT_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "comment" }); pos += m.length; continue; } // Strings if ((m = tryMatch(DQ_STRING_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "string" }); pos += m.length; continue; } if ((m = tryMatch(SQ_STRING_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "string" }); pos += m.length; continue; } if (!usesHash && (m = tryMatch(TPL_STRING_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "string" }); pos += m.length; continue; } // Numbers if ((m = tryMatch(NUMBER_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: "number" }); pos += m.length; continue; } // Words (keyword vs identifier) if ((m = tryMatch(WORD_RE, code, pos))) { flushPlain(); tokens.push({ text: m, kind: keywords.has(m) ? "keyword" : "plain" }); pos += m.length; continue; } // Anything else: accumulate as plain. plain += code[pos]; pos += 1; } flushPlain(); return tokens; }