Skip to content
refs
148 lines · 5.2 KBRaw
1/** One token of TypeScript or JavaScript source. Comments and whitespace are dropped, except the doc comment kept on the next token. */
2export interface Token {
3 readonly kind: "name" | "punct" | "string" | "number" | "template" | "regex";
4 readonly text: string;
5 readonly line: number;
6 /** The text of the comment right before this token, when there is one. */
7 readonly comment?: string;
8}
9
10const NAME_START = /[A-Za-z_$#@]/;
11const NAME_PART = /[\w$]/;
12const PUNCT_3 = new Set(["===", "!==", "...", "**=", "<<=", ">>=", ">>>", "&&=", "||=", "??="]);
13const PUNCT_2 = new Set(["=>", "==", "!=", "<=", ">=", "&&", "||", "??", "?.", "++", "--", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "**", "<<", ">>"]);
14/** After these, a slash starts a regular expression, not a division. */
15const REGEX_AFTER_PUNCT = new Set(["(", ",", "=", ":", "[", "!", "&", "|", "?", "{", "}", ";", "&&", "||", "??", "=>", "==", "===", "!=", "!==", "+", "-", "*", "%", "<", ">", "~", "^", "return"]);
16const REGEX_AFTER_WORD = new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
17
18/**
19 * Splits source into tokens. It is a lexer for outlines, not a compiler: it knows strings, template literals with
20 * their `${}` code, comments, numbers and regular expressions well enough to find declarations and names.
21 */
22export function tokenize(source: string): Token[] {
23 const tokens: Token[] = [];
24 const text = source.replace(/\r\n?/g, "\n");
25 let i = 0;
26 let line = 1;
27 let comment: string | undefined;
28 const templates: number[] = [];
29 let braces = 0;
30
31 const push = (kind: Token["kind"], value: string, at: number) => {
32 tokens.push(comment === undefined ? { kind, text: value, line: at } : { kind, text: value, line: at, comment });
33 comment = undefined;
34 };
35 const regexAllowed = () => {
36 const last = tokens[tokens.length - 1];
37 if (!last) return true;
38 if (last.kind === "punct") return REGEX_AFTER_PUNCT.has(last.text);
39 return last.kind === "name" && REGEX_AFTER_WORD.has(last.text);
40 };
41
42 const readTemplate = (from: number): number => {
43 let j = from;
44 while (j < text.length) {
45 const c = text[j];
46 if (c === "\\") {
47 j += 2;
48 continue;
49 }
50 if (c === "`") return j + 1;
51 if (c === "$" && text[j + 1] === "{") {
52 templates.push(braces);
53 return j + 2;
54 }
55 if (c === "\n") line++;
56 j++;
57 }
58 return j;
59 };
60
61 while (i < text.length) {
62 const c = text[i];
63 if (c === "\n") {
64 line++;
65 i++;
66 continue;
67 }
68 if (c === " " || c === "\t" || c === "\f" || c === "\v" || c === " " || c === "") {
69 i++;
70 continue;
71 }
72 if (c === "/" && text[i + 1] === "/") {
73 const end = text.indexOf("\n", i);
74 const stop = end < 0 ? text.length : end;
75 comment = text.slice(i + 2, stop).trim();
76 i = stop;
77 continue;
78 }
79 if (c === "/" && text[i + 1] === "*") {
80 const end = text.indexOf("*/", i + 2);
81 const stop = end < 0 ? text.length : end + 2;
82 const body = text.slice(i + 2, stop - 2);
83 for (const ch of body) if (ch === "\n") line++;
84 comment = body.replace(/^\*+/, "").split("\n").map((part) => part.replace(/^\s*\*\s?/, "").trim()).filter(Boolean).join(" ");
85 i = stop;
86 continue;
87 }
88 const start = line;
89 if (c === "'" || c === '"') {
90 let j = i + 1;
91 while (j < text.length && text[j] !== c && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1;
92 push("string", text.slice(i, j + 1), start);
93 i = j + 1;
94 continue;
95 }
96 if (c === "`") {
97 const end = readTemplate(i + 1);
98 push("template", text.slice(i, end), start);
99 i = end;
100 continue;
101 }
102 if (c === "}" && templates.length && templates[templates.length - 1] === braces) {
103 templates.pop();
104 const end = readTemplate(i + 1);
105 push("template", text.slice(i, end), start);
106 i = end;
107 continue;
108 }
109 if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(text[i + 1] ?? ""))) {
110 let j = i + 1;
111 while (j < text.length && /[\w.]/.test(text[j])) j++;
112 push("number", text.slice(i, j), start);
113 i = j;
114 continue;
115 }
116 if (NAME_START.test(c)) {
117 let j = i + 1;
118 while (j < text.length && NAME_PART.test(text[j])) j++;
119 push("name", text.slice(i, j), start);
120 i = j;
121 continue;
122 }
123 if (c === "/" && text[i + 1] !== ">" && tokens[tokens.length - 1]?.text !== "<" && regexAllowed()) {
124 let j = i + 1;
125 let inClass = false;
126 while (j < text.length && text[j] !== "\n") {
127 if (text[j] === "\\") j += 2;
128 else if (text[j] === "[") (inClass = true), j++;
129 else if (text[j] === "]") (inClass = false), j++;
130 else if (text[j] === "/" && !inClass) break;
131 else j++;
132 }
133 j++;
134 while (j < text.length && /[a-z]/i.test(text[j])) j++;
135 push("regex", text.slice(i, j), start);
136 i = j;
137 continue;
138 }
139 const three = text.slice(i, i + 3);
140 const two = text.slice(i, i + 2);
141 const punct = PUNCT_3.has(three) ? three : PUNCT_2.has(two) ? two : c;
142 if (punct === "{") braces++;
143 if (punct === "}") braces--;
144 push("punct", punct, start);
145 i += punct.length;
146 }
147 return tokens;
148}