File size: 5,108 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | 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<CodingLanguage, Set<string>> = {
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<Record<CodingLanguage, boolean>> = { 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;
}
|