Skip to content
refs
History
377 lines · 16.1 KBRaw
1import { tokenize, type Token } from "./lexer.ts";
2
3export type SymbolKind = "function" | "class" | "method" | "field" | "interface" | "type" | "enum" | "const";
4
5export interface OutlineSymbol {
6 readonly name: string;
7 readonly kind: SymbolKind;
8 /** The index of the class that holds this member, or null for a top-level declaration. */
9 readonly parent: number | null;
10 readonly start: number;
11 readonly end: number;
12 readonly exported: boolean;
13 readonly doc: string | null;
14}
15
16/** A name used inside a declaration. `member` marks `this.name`, which points at a member of the enclosing class. */
17export interface Reference {
18 readonly name: string;
19 readonly member: boolean;
20 readonly call: boolean;
21 readonly construct: boolean;
22 readonly line: number;
23}
24
25export interface ImportBinding {
26 readonly local: string;
27 readonly module: string;
28 /** The exported name, `default`, or `*` for a namespace import. */
29 readonly imported: string;
30}
31
32/** `export { local as exported }`, `export { imported as exported } from "module"`, or `export * from "module"` (exported `*`). */
33export interface ExportBinding {
34 readonly exported: string;
35 readonly local?: string;
36 readonly module?: string;
37 readonly imported?: string;
38}
39
40export interface FileOutline {
41 readonly symbols: readonly OutlineSymbol[];
42 /** The names each symbol uses, by the symbol's index. */
43 readonly references: readonly (readonly Reference[])[];
44 readonly imports: readonly ImportBinding[];
45 readonly exports: readonly ExportBinding[];
46}
47
48const MODIFIERS = new Set(["declare", "async", "abstract", "default"]);
49const MEMBER_MODIFIERS = new Set(["static", "public", "private", "protected", "readonly", "abstract", "override", "declare", "async", "accessor"]);
50const STATEMENT_START = new Set(["export", "import", "const", "let", "var", "function", "class", "interface", "type", "enum", "declare", "async", "abstract"]);
51const OPEN: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
52const KEYWORDS = new Set(
53 "abstract any as async await boolean break case catch class const constructor continue debugger declare default delete do else enum export extends false finally for from function get if implements import in infer instanceof interface is keyof let module namespace never new null number object of package private protected public readonly return satisfies set static string super switch symbol this throw true try type typeof undefined unique unknown var void while with yield".split(" "),
54);
55const MAX_DOC = 240;
56
57/** Reads the declarations of one TypeScript or JavaScript file: its top-level symbols, class members, imports, exports and the names each symbol uses. */
58export function outline(source: string): FileOutline {
59 return new Outliner(tokenize(source)).run();
60}
61
62class Outliner {
63 readonly #tokens: readonly Token[];
64 readonly #symbols: OutlineSymbol[] = [];
65 readonly #ranges: [number, number][] = [];
66 readonly #imports: ImportBinding[] = [];
67 readonly #exports: ExportBinding[] = [];
68
69 constructor(tokens: readonly Token[]) {
70 this.#tokens = tokens;
71 }
72
73 run(): FileOutline {
74 let p = 0;
75 while (p < this.#tokens.length) p = this.#statement(p);
76 return { symbols: this.#symbols, references: this.#ranges.map(([from, to], index) => this.#references(from, to, index)), imports: this.#imports, exports: this.#exports };
77 }
78
79 #text(p: number): string | undefined {
80 return this.#tokens[p]?.text;
81 }
82
83 /** The index of the token that closes the bracket opened at `p`. */
84 #close(p: number): number {
85 const want = OPEN[this.#text(p)!];
86 const stack = [want];
87 let q = p + 1;
88 while (q < this.#tokens.length && stack.length) {
89 const t = this.#tokens[q];
90 if (t.kind === "punct") {
91 if (OPEN[t.text]) stack.push(OPEN[t.text]);
92 else if (t.text === stack[stack.length - 1]) stack.pop();
93 }
94 q++;
95 }
96 return Math.min(q - 1, this.#tokens.length - 1);
97 }
98
99 /** The last token of the statement that starts at `p`: a semicolon at depth 0, or the token before a new statement on a later line. */
100 #statementEnd(p: number, stopAtBlock = false): number {
101 let q = p;
102 while (q < this.#tokens.length) {
103 const t = this.#tokens[q];
104 if (t.kind === "punct" && OPEN[t.text]) {
105 const close = this.#close(q);
106 if (stopAtBlock && t.text === "{" && this.#endsAfterBlock(close)) return close;
107 q = close + 1;
108 if (this.#newStatementAt(q, this.#tokens[close].line)) return close;
109 continue;
110 }
111 if (t.kind === "punct" && (t.text === ";" || t.text === "}")) return t.text === ";" ? q : q - 1;
112 if (this.#newStatementAt(q + 1, t.line)) return q;
113 q++;
114 }
115 return this.#tokens.length - 1;
116 }
117
118 #endsAfterBlock(close: number): boolean {
119 const next = this.#tokens[close + 1];
120 return !next || next.line > this.#tokens[close].line || next.text === ";";
121 }
122
123 #newStatementAt(q: number, line: number): boolean {
124 const next = this.#tokens[q];
125 return !!next && next.line > line && next.kind === "name" && STATEMENT_START.has(next.text) && this.#text(q + 1) !== "(" && this.#text(q + 1) !== ".";
126 }
127
128 #statement(p: number): number {
129 const t = this.#tokens[p];
130 if (t.text === "import" && this.#text(p + 1) !== "(" && this.#text(p + 1) !== ".") return this.#import(p);
131 if (t.text === "export") return this.#export(p);
132 if (t.kind === "name" && this.#isDeclaration(p)) return this.#declaration(p, false, t.comment);
133 return this.#statementEnd(p) + 1;
134 }
135
136 #isDeclaration(p: number): boolean {
137 let q = p;
138 while (MODIFIERS.has(this.#text(q) ?? "") && this.#tokens[q + 1]?.kind === "name") q++;
139 const word = this.#text(q);
140 if (word === "function" || word === "class" || word === "enum") return true;
141 if (word === "interface" || word === "type") return this.#tokens[q + 1]?.kind === "name";
142 return (word === "const" || word === "let" || word === "var") && this.#tokens[q + 1]?.kind === "name" && this.#text(q + 1) !== "enum";
143 }
144
145 #import(p: number): number {
146 const end = this.#statementEnd(p);
147 const from = this.#moduleOf(p, end);
148 if (from === null) return end + 1;
149 let q = p + 1;
150 if (this.#text(q) === "type" && this.#text(q + 1) !== "from" && this.#text(q + 1) !== ",") q++;
151 while (q <= end) {
152 const t = this.#tokens[q];
153 if (t.text === "from" || t.kind === "string") break;
154 if (t.text === "*" && this.#text(q + 1) === "as") {
155 this.#imports.push({ local: this.#text(q + 2)!, module: from, imported: "*" });
156 q += 3;
157 } else if (t.text === "{") {
158 const close = this.#close(q);
159 for (const [name, alias] of this.#bindings(q + 1, close)) this.#imports.push({ local: alias, module: from, imported: name });
160 q = close + 1;
161 } else if (t.kind === "name") {
162 this.#imports.push({ local: t.text, module: from, imported: "default" });
163 q++;
164 } else q++;
165 }
166 return end + 1;
167 }
168
169 /** The names of a `{ a, b as c, type d }` list, as [name, alias] pairs. */
170 #bindings(from: number, to: number): [string, string][] {
171 const out: [string, string][] = [];
172 let q = from;
173 while (q < to) {
174 if (this.#text(q) === "type" && this.#tokens[q + 1]?.kind === "name" && this.#text(q + 1) !== "as") q++;
175 const name = this.#tokens[q];
176 if (name?.kind === "name" || name?.kind === "string") {
177 const alias = this.#text(q + 1) === "as" ? this.#text(q + 2)! : name.text;
178 out.push([name.text.replace(/^['"]|['"]$/g, ""), alias]);
179 q += this.#text(q + 1) === "as" ? 3 : 1;
180 }
181 while (q < to && this.#text(q) !== ",") q++;
182 q++;
183 }
184 return out;
185 }
186
187 #moduleOf(from: number, to: number): string | null {
188 for (let q = from; q <= to; q++) if (this.#tokens[q].kind === "string") return this.#tokens[q].text.slice(1, -1);
189 return null;
190 }
191
192 #export(p: number): number {
193 const next = this.#text(p + 1);
194 if (next === "*") {
195 const end = this.#statementEnd(p);
196 const module = this.#moduleOf(p, end);
197 const alias = this.#text(p + 2) === "as" ? this.#text(p + 3)! : "*";
198 if (module) this.#exports.push(alias === "*" ? { exported: "*", module } : { exported: alias, module, imported: "*" });
199 return end + 1;
200 }
201 const brace = next === "{" ? p + 1 : next === "type" && this.#text(p + 2) === "{" ? p + 2 : -1;
202 if (brace >= 0) {
203 const close = this.#close(brace);
204 const end = this.#statementEnd(close + 1 <= this.#tokens.length - 1 ? close : p);
205 const module = this.#text(close + 1) === "from" ? this.#tokens[close + 2]?.text.slice(1, -1) : undefined;
206 for (const [name, alias] of this.#bindings(brace + 1, close)) this.#exports.push(module ? { exported: alias, module, imported: name } : { exported: alias, local: name });
207 return Math.max(end, close) + 1;
208 }
209 if (next === "default") {
210 if (this.#isDeclaration(p + 2) || this.#text(p + 2) === "function" || this.#text(p + 2) === "class") {
211 const before = this.#symbols.length;
212 const end = this.#declaration(p + 2, true, this.#tokens[p].comment);
213 const declared = this.#symbols[before];
214 if (declared) this.#exports.push({ exported: "default", local: declared.name });
215 return end;
216 }
217 const end = this.#statementEnd(p);
218 if (end === p + 2 || (end === p + 3 && this.#text(end) === ";")) {
219 if (this.#tokens[p + 2]?.kind === "name") this.#exports.push({ exported: "default", local: this.#text(p + 2)! });
220 }
221 return end + 1;
222 }
223 if (this.#isDeclaration(p + 1)) return this.#declaration(p + 1, true, this.#tokens[p].comment);
224 return this.#statementEnd(p) + 1;
225 }
226
227 #declaration(p: number, exported: boolean, doc: string | undefined): number {
228 let q = p;
229 while (MODIFIERS.has(this.#text(q) ?? "") && this.#tokens[q + 1]?.kind === "name") q++;
230 const word = this.#text(q)!;
231 if (word === "function") {
232 if (this.#text(q + 1) === "*") q++;
233 const name = this.#tokens[q + 1];
234 const end = this.#statementEnd(q, true);
235 if (name?.kind === "name") this.#add(name.text, "function", null, p, end, exported, doc);
236 return end + 1;
237 }
238 if (word === "class") {
239 const name = this.#tokens[q + 1]?.kind === "name" && this.#text(q + 1) !== "extends" ? this.#text(q + 1)! : null;
240 let open = q + 1;
241 while (open < this.#tokens.length && this.#text(open) !== "{") open = this.#text(open) === "(" || this.#text(open) === "[" ? this.#close(open) + 1 : open + 1;
242 const close = this.#close(open);
243 if (name) {
244 const index = this.#add(name, "class", null, p, close, exported, doc);
245 this.#members(open + 1, close, index);
246 }
247 return close + 1;
248 }
249 if (word === "interface" || word === "enum") {
250 let open = q + 2;
251 while (open < this.#tokens.length && this.#text(open) !== "{") open++;
252 const close = this.#close(open);
253 this.#add(this.#text(q + 1)!, word === "enum" ? "enum" : "interface", null, p, close, exported, doc);
254 return close + 1;
255 }
256 if (word === "type") {
257 const end = this.#statementEnd(q);
258 this.#add(this.#text(q + 1)!, "type", null, p, end, exported, doc);
259 return end + 1;
260 }
261 const end = this.#statementEnd(q);
262 const name = this.#tokens[q + 1];
263 if (name?.kind === "name") {
264 let eq = q + 2;
265 while (eq < end && this.#text(eq) !== "=") eq = OPEN[this.#text(eq) ?? ""] ? this.#close(eq) + 1 : eq + 1;
266 this.#add(name.text, this.#isFunctionValue(eq + 1) ? "function" : "const", null, p, end, exported, doc);
267 }
268 return end + 1;
269 }
270
271 #isFunctionValue(p: number): boolean {
272 let q = p;
273 if (this.#text(q) === "async") q++;
274 if (this.#text(q) === "function") return true;
275 if (this.#text(q) === "<") while (q < this.#tokens.length && this.#text(q) !== "(") q++;
276 if (this.#text(q) === "(") {
277 const close = this.#close(q);
278 let after = close + 1;
279 if (this.#text(after) === ":") while (after < this.#tokens.length && this.#text(after) !== "=>" && this.#text(after) !== ";" && this.#text(after) !== "{") after++;
280 return this.#text(after) === "=>";
281 }
282 return this.#tokens[q]?.kind === "name" && this.#text(q + 1) === "=>";
283 }
284
285 #members(from: number, to: number, parent: number) {
286 let q = from;
287 while (q < to) {
288 const first = q;
289 const doc = this.#tokens[q].comment;
290 if (this.#text(q) === ";" || this.#text(q) === ",") {
291 q++;
292 continue;
293 }
294 while (this.#text(q)?.startsWith("@")) q = this.#text(q + 1) === "(" ? this.#close(q + 1) + 1 : q + 1;
295 while (q < to && (MEMBER_MODIFIERS.has(this.#text(q)!) || ((this.#text(q) === "get" || this.#text(q) === "set") && this.#tokens[q + 1]?.kind === "name") || this.#text(q) === "*")) q++;
296 const name = this.#tokens[q];
297 if (!name || q >= to) break;
298 if (name.text === "[") {
299 q = this.#memberEnd(this.#close(q) + 1, to) + 1;
300 continue;
301 }
302 const after = this.#text(q + 1);
303 const method = after === "(" || after === "<" || (after === "?" && this.#text(q + 2) === "(");
304 const end = method ? this.#methodEnd(q + 1, to) : this.#memberEnd(q + 1, to);
305 if (name.kind === "name" || name.kind === "string") this.#add(name.text.replace(/^['"]|['"]$/g, ""), method ? "method" : "field", parent, first, end, false, doc);
306 q = end + 1;
307 }
308 }
309
310 #methodEnd(p: number, to: number): number {
311 let q = p;
312 while (q < to) {
313 const t = this.#text(q)!;
314 if (t === ";") return q;
315 if (t === "{") {
316 const close = this.#close(q);
317 if (this.#text(close + 1) !== "|" && this.#text(close + 1) !== "&" && this.#text(close + 1) !== "[") {
318 const prev = this.#text(q - 1);
319 if (prev === ")" || prev === ">" || this.#tokens[q - 1]?.kind === "name" || prev === "]" || prev === "}") return close;
320 }
321 q = close + 1;
322 continue;
323 }
324 q = OPEN[t] ? this.#close(q) + 1 : q + 1;
325 }
326 return to - 1;
327 }
328
329 #memberEnd(p: number, to: number): number {
330 let q = p;
331 while (q < to) {
332 const t = this.#tokens[q];
333 if (t.text === ";") return q;
334 if (OPEN[t.text]) {
335 const close = this.#close(q);
336 q = close + 1;
337 if (this.#tokens[q] && this.#tokens[q].line > this.#tokens[close].line && this.#text(q) !== "." && this.#text(q) !== "?.") return close;
338 continue;
339 }
340 if (this.#tokens[q + 1] && this.#tokens[q + 1].line > t.line && q + 1 < to && !OPEN[t.text] && !/^[=,.:|&?+\-*/(<]$/.test(t.text) && !/^[=.,:|&?)]/.test(this.#text(q + 1)!)) return q;
341 q++;
342 }
343 return to - 1;
344 }
345
346 #add(name: string, kind: SymbolKind, parent: number | null, from: number, to: number, exported: boolean, doc: string | undefined): number {
347 this.#symbols.push({ name, kind, parent, start: this.#tokens[from].line, end: this.#tokens[Math.max(from, to)].line, exported, doc: doc ? doc.slice(0, MAX_DOC) : null });
348 this.#ranges.push([from, to]);
349 return this.#symbols.length - 1;
350 }
351
352 /** The names a symbol uses. A class's own range leaves out its members, which report their own names. */
353 #references(from: number, to: number, index: number): Reference[] {
354 const holes = this.#symbols.flatMap((symbol, i) => (symbol.parent === index ? [this.#ranges[i]] : []));
355 const own = this.#symbols[index].name;
356 const out: Reference[] = [];
357 for (let q = from; q <= to; q++) {
358 const hole = holes.find(([a, b]) => q >= a && q <= b);
359 if (hole) {
360 q = hole[1];
361 continue;
362 }
363 const t = this.#tokens[q];
364 if (t.kind !== "name" || KEYWORDS.has(t.text) || t.text.startsWith("@")) continue;
365 const prev = this.#text(q - 1);
366 const member = (prev === "." || prev === "?.") && this.#text(q - 2) === "this";
367 if ((prev === "." || prev === "?.") && !member) continue;
368 if (!member && t.text === own && q <= from + 4) continue;
369 if (!member && t.text.startsWith("#")) continue;
370 const next = this.#text(q + 1);
371 if (next === ":" && (prev === "{" || prev === ",") && !member) continue;
372 const call = next === "(" || ((prev === "<" || prev === "</") && /^[A-Z]/.test(t.text));
373 out.push({ name: t.text, member, call, construct: prev === "new", line: t.line });
374 }
375 return out;
376 }
377}