-
Notifications
You must be signed in to change notification settings - Fork 10
/
parser.ts
452 lines (426 loc) · 13.7 KB
/
parser.ts
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
** Copyright 2019 Bloomberg Finance L.P.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
import { FunctionDesc } from "../src/functionDesc";
import { FileType } from "./types";
import * as ts from "typescript";
/**
* Parse a source file and return descriptions of all functions present in the
* source file. Each description includes the name of the function, and start and
* end coordinates. For anonymous functions the name is "<anonymous>".
*
* @param source - the contents of a source file
* @param filetype - the type of the source file (e.g. ECMAScript or TypeScript)
*
* @throws if the filetype is not supported, or if the source file cannot be parsed.
*/
export function parse(source: string, filetype: FileType): FunctionDesc[] {
switch (filetype) {
case "TypeScript":
case "ECMAScript":
case "TSX":
case "JSX":
return parseTS(source, filetype);
default:
throw Error(`Unsupported FileType provided: ${filetype}`);
}
}
const tsScriptKind: ReadonlyMap<string, ts.ScriptKind> = new Map([
["TypeScript", ts.ScriptKind.TS],
["ECMAScript", ts.ScriptKind.JS],
["TSX", ts.ScriptKind.TSX],
["JSX", ts.ScriptKind.JSX],
]);
function parseTS(source: string, filetype: FileType): FunctionDesc[] {
const scriptKind = tsScriptKind.get(filetype);
const tsSource = ts.createSourceFile(
"",
source,
ts.ScriptTarget.ESNext,
true, // setParentNodes
scriptKind
);
validateScript(tsSource);
const topLevelDesc = visitSourceNode(tsSource);
const otherDescs = traverseNode(tsSource);
return [topLevelDesc, ...otherDescs];
}
let _program: ts.Program;
function getExpensiveProgram() {
return _program || (_program = ts.createProgram([""], {}));
}
function validateScript(tsSource: ts.SourceFile) {
const program = getExpensiveProgram();
const diag = program.getSyntacticDiagnostics(tsSource);
if (diag.length > 0) {
throw Error(`Syntax error in source, ${diag[0].messageText}`);
}
}
function traverseNode(
source: ts.SourceFile,
node: ts.Node = source
): FunctionDesc[] {
const functionDescs: FunctionDesc[] = [];
if (
ts.isFunctionDeclaration(node) ||
ts.isFunctionExpression(node) ||
ts.isArrowFunction(node) ||
ts.isMethodDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
ts.isGetAccessorDeclaration(node) ||
ts.isSetAccessorDeclaration(node)
) {
functionDescs.push(...visitFunctionNode(node, source));
}
node.getChildren().forEach((c) =>
functionDescs.push(...traverseNode(source, c))
);
return functionDescs;
}
function visitFunctionNode(
node: ts.FunctionLikeDeclaration,
source: ts.SourceFile
): FunctionDesc[] {
if (node.body) {
const name = getFunctionName(node);
const { startLine, startColumn, endLine, endColumn } = getPosition(
node,
source
);
return [
new FunctionDesc(name, startLine, startColumn, endLine, endColumn),
];
}
return [];
}
function visitSourceNode(source: ts.SourceFile): FunctionDesc {
const name = "<top-level>";
const { startLine, startColumn, endLine, endColumn } = getPosition(
source,
source
);
return new FunctionDesc(name, startLine, startColumn, endLine, endColumn);
}
function getPosition(
range: ts.TextRange,
source: ts.SourceFile
): {
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
} {
const { pos, end } = range;
const { line: startLine, character: startColumn } =
source.getLineAndCharacterOfPosition(pos);
const { line: endLine, character: endColumn } =
source.getLineAndCharacterOfPosition(end);
return {
startLine,
startColumn,
endLine,
endColumn,
};
}
function getFunctionName(func: ts.FunctionLikeDeclaration): string {
let nameText = "<anonymous>";
const name = func.name;
if (name) {
nameText = getNameText(name, func) || nameText;
} else if (ts.isConstructorDeclaration(func)) {
// set the name to "", the class name will be added later
nameText = "";
} else {
if (ts.isFunctionExpression(func) || ts.isArrowFunction(func)) {
let parent = func.parent;
if (ts.isParenthesizedExpression(parent)) {
parent = parent.parent;
}
if (
ts.isVariableDeclaration(parent) ||
ts.isPropertyAssignment(parent) ||
ts.isPropertyDeclaration(parent)
) {
nameText = getNameText(parent.name, func) || nameText;
} else if (
ts.isBinaryExpression(parent) &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
) {
if (
ts.isPropertyAccessExpression(parent.left) ||
ts.isElementAccessExpression(parent.left)
) {
nameText = getLeftHandSideName(parent.left);
}
}
}
}
const prefix = getPrefix(func);
if (prefix) {
return nameText === "" ? prefix : `${prefix}.${nameText}`;
}
return nameText;
}
function getPrefix(func: ts.FunctionLikeDeclaration): string | null {
let propValue: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration = func;
let prefix = null;
// get class prefix if function is inside a class
const classPrefix = getClassPrefix(func);
if (classPrefix) {
prefix = classPrefix;
const classPropValue = getParentClassProperty(func);
if (classPropValue) {
// if the class is a property of an object literal, we want to
// walk the object literal chain of the class instead of the function
propValue = classPropValue;
} else {
// this means the class is not inside an object literal and we are done
return prefix;
}
}
// get object literal prefix if function (or enclosing class)
// is inside an object literal
const objectLiteralPrefix = getObjectLiteralPrefix(propValue);
if (objectLiteralPrefix) {
prefix = prefix
? `${objectLiteralPrefix}.${prefix}`
: objectLiteralPrefix;
}
return prefix;
}
function isProperty(
func: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration
) {
return (
(ts.isFunctionExpression(func) ||
ts.isArrowFunction(func) ||
ts.isClassExpression(func)) &&
(ts.isPropertyDeclaration(func.parent) ||
ts.isPropertyAssignment(func.parent))
);
}
function getPropertyNodeForFunction(
func: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration
) {
if (
ts.isMethodDeclaration(func) ||
ts.isGetAccessor(func) ||
ts.isSetAccessor(func) ||
ts.isConstructorDeclaration(func)
) {
return func;
}
if (
ts.isFunctionExpression(func) ||
ts.isArrowFunction(func) ||
ts.isClassExpression(func)
) {
if (
ts.isPropertyDeclaration(func.parent) ||
ts.isPropertyAssignment(func.parent)
) {
return func.parent;
}
}
return null;
}
function getObjectLiteralPrefix(
func: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration
): string | null {
const propertyNode = getPropertyNodeForFunction(func);
// propertyNode === null means the function was neither a method nor a
// property, so it is not part of an object literal or class declaration
if (!propertyNode) {
return null;
}
// if the function is a property, and either has a local name,
// or is inside a class expression, we take the local name and
// and do not prefix it with the object literal chain
const isProp = isProperty(func);
if (isProp) {
if (
func.name !== undefined ||
ts.isClassExpression(propertyNode.parent)
) {
return null;
}
}
return getObjectLiteralPrefixR(propertyNode.parent);
}
function getObjectLiteralPrefixR(
node: ts.Node,
prefixWithObject = false
): string | null {
const parent = node.parent;
if (!parent) {
return null;
}
if (ts.isPropertyAssignment(parent)) {
const propertyAssignment = parent;
const prefix = getObjectLiteralPrefixR(
propertyAssignment.parent,
true
);
return `${prefix}.${getPropertyName(propertyAssignment.name)}`;
}
if (ts.isVariableDeclaration(parent)) {
if (ts.isIdentifier(parent.name)) {
return getPropertyName(parent.name);
}
} else if (
ts.isBinaryExpression(parent) &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
) {
if (ts.isIdentifier(parent.left)) {
return getPropertyName(parent.left);
}
if (
ts.isPropertyAccessExpression(parent.left) ||
ts.isElementAccessExpression(parent.left)
) {
return getLeftHandSideName(parent.left);
}
}
return prefixWithObject ? "<Object>" : null;
}
function getParentClassProperty(func: ts.FunctionLikeDeclaration) {
const propertyNode = getPropertyNodeForFunction(func);
if (propertyNode) {
const parent = propertyNode.parent;
if (ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) {
return parent;
}
}
return null;
}
function getClassPrefix(func: ts.FunctionLikeDeclaration): string | null {
const propertyNode = getPropertyNodeForFunction(func);
if (!propertyNode) {
return null;
}
const parent = propertyNode.parent;
if (ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) {
const className = getClassName(parent);
const isProp = isProperty(func);
if (isStatic(propertyNode)) {
if (!isProp || func.name === undefined) {
return className;
}
} else if (ts.isConstructorDeclaration(func)) {
return className;
} else if (!isProp) {
return `${className}.prototype`;
}
}
return null;
}
function getClassName(classNode: ts.ClassLikeDeclaration): string {
// if class has a local name, use it and return,
// not interested in left hand side
if (classNode.name) {
return classNode.name.text;
}
// try to get the name from the left hand side
if (ts.isClassExpression(classNode)) {
const parent = classNode.parent;
if (
ts.isVariableDeclaration(parent) ||
ts.isPropertyAssignment(parent) ||
ts.isPropertyDeclaration(parent)
) {
if (ts.isPropertyName(parent.name)) {
return getPropertyName(parent.name);
}
} else if (
ts.isBinaryExpression(parent) &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
) {
if (
ts.isPropertyAccessExpression(parent.left) ||
ts.isElementAccessExpression(parent.left)
) {
return getLeftHandSideName(parent.left);
}
}
}
return "<anonymous>";
}
function isStatic(func: ts.Node): boolean {
if (ts.canHaveModifiers(func) && func.modifiers) {
return func.modifiers.some(({ kind }) => {
return kind === ts.SyntaxKind.StaticKeyword;
});
}
return false;
}
function getLeftHandSideName(left: ts.Expression): string {
if (
ts.isIdentifier(left) ||
ts.isStringLiteral(left) ||
ts.isNumericLiteral(left)
) {
return left.text;
} else if (ts.isPropertyAccessExpression(left)) {
return getLeftHandSideName(left.expression) + "." + left.name.text;
} else if (ts.isElementAccessExpression(left)) {
return (
getLeftHandSideName(left.expression) +
"." +
computedName(left.argumentExpression)
);
}
return "<computed>";
}
function getPropertyName(name: ts.PropertyName): string {
switch (name.kind) {
case ts.SyntaxKind.Identifier:
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NumericLiteral:
case ts.SyntaxKind.PrivateIdentifier:
return name.text;
case ts.SyntaxKind.ComputedPropertyName:
return computedName(name.expression);
}
}
function getNameText(
name: ts.Node,
func: ts.FunctionLikeDeclaration
): string | null {
let nameText = null;
if (ts.isPropertyName(name)) {
nameText = getPropertyName(name);
if (ts.isGetAccessor(func)) {
return `get ${nameText}`;
}
if (ts.isSetAccessor(func)) {
return `set ${nameText}`;
}
}
if (ts.isPrivateIdentifier(name)) {
nameText = name.text;
}
return nameText;
}
function computedName(expression: ts.Expression): string {
if (ts.isIdentifier(expression)) {
return `<computed: ${expression.text}>`;
} else if (
ts.isStringLiteral(expression) ||
ts.isNumericLiteral(expression)
) {
return expression.text;
}
return "<computed>";
}