-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathParser.ts
402 lines (309 loc) · 10.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
// This file is part of readts, copyright (c) 2016 BusFaster Ltd.
// Released under the MIT license, see LICENSE.
import * as path from 'path';
import * as ts from 'typescript';
import * as readts from './index';
export interface SourcePos {
sourcePath: string;
firstLine: number;
lastLine: number;
}
/** @ignore internal use. */
export interface SymbolSpec {
name: string;
symbol: ts.Symbol;
declaration: ts.Declaration;
type: ts.Type;
pos: SourcePos;
doc: string;
}
export interface RefSpec {
[key: string]: any;
name?: string;
symbol?: ts.Symbol;
class?: readts.ClassSpec;
enum?: readts.EnumSpec;
}
/** Main parser class with public methods, also holding its internal state. */
export class Parser {
/** Parse a tsconfig.json file using TypeScript services API. */
parseConfig(tsconfigPath: string) {
var configJson = ts.parseConfigFileTextToJson(tsconfigPath, ts.sys.readFile(tsconfigPath)).config;
var config = ts.parseJsonConfigFileContent(configJson, ts.sys, tsconfigPath.replace(/[^/]+$/, ''), {}, tsconfigPath);
return(config);
}
/** Parse a TypeScript project using TypeScript services API and configuration. */
parse(
config: ts.ParsedCommandLine,
nameFilter?: (pathName: string) => boolean,
extension?: string
): readts.ModuleSpec[] {
var sourceNum = 0;
this.program = ts.createProgram(config.fileNames, config.options);
this.checker = this.program.getTypeChecker();
this.moduleList = [];
this.symbolTbl = {};
for(var source of this.program.getSourceFiles()) {
// Skip contents of the default library.
if(sourceNum++ == 0) continue;
// Call optional filter to check if file should be parsed.
if(
!nameFilter ||
!extension ||
nameFilter(this.getOwnEmitOutputFilePath(source, this.program, extension))
) {
this.parseSource(source);
}
}
return(this.moduleList);
}
/** Convert an otherwise unrecognized type to string. @ignore internal use. */
typeToString(type: ts.Type) {
return(this.checker.typeToString(type));
}
/** Get or change reference for a symbol. @ignore internal use. */
getRef(symbol: ts.Symbol, ref?: RefSpec) {
var name = symbol.getName();
var symbolList = this.symbolTbl[name];
if(!symbolList) {
symbolList = [];
this.symbolTbl[name] = symbolList;
} else {
for(var match of symbolList) {
if(symbol == match.symbol) {
if(ref) for(var key of Object.keys(ref)) match[key] = ref[key];
return(match);
}
}
}
if(!ref) ref = {};
ref.name = name;
ref.symbol = symbol;
symbolList.push(ref);
return(ref);
}
private parseType(type: ts.Type) {
var spec = new readts.TypeSpec(type, this);
return(spec);
}
private parseSource(source: ts.SourceFile) {
var symbol = this.checker.getSymbolAtLocation(source);
if(!symbol) return;
var exportTbl = symbol.exports;
for(var name of this.getKeys(exportTbl).sort()) {
var spec = this.parseSymbol(exportTbl.get(name));
// Resolve aliases.
while(1) {
var symbolFlags = spec.symbol.getFlags();
if(symbolFlags & ts.SymbolFlags.Alias) {
spec = this.parseSymbol(this.checker.getAliasedSymbol(spec.symbol));
} else break;
}
if(spec.declaration) {
var module = new readts.ModuleSpec();
this.parseDeclaration(spec, module);
this.moduleList.push(module);
}
}
}
/** Extract declared function, class or interface from a symbol. */
private parseDeclaration(spec: SymbolSpec, moduleSpec: readts.ModuleSpec) {
var node = spec.declaration as ts.Node;
switch(node.kind) {
case ts.SyntaxKind.FunctionDeclaration:
if(spec) {
var functionSpec = this.parseFunction(spec);
if(functionSpec) moduleSpec.addFunction(functionSpec);
}
break;
case ts.SyntaxKind.EnumDeclaration:
if (spec) {
var enumSpec = this.parseEnum(spec);
if(enumSpec) moduleSpec.addEnum(enumSpec);
}
break;
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.InterfaceDeclaration:
if(spec) {
var classSpec = this.parseClass(spec);
if(classSpec) {
if(node.kind == ts.SyntaxKind.InterfaceDeclaration) {
moduleSpec.addInterface(classSpec);
} else moduleSpec.addClass(classSpec);
}
}
break;
}
}
private parseComment(symbol: ts.Symbol | ts.Signature) {
return(ts.displayPartsToString(symbol.getDocumentationComment(this.checker)).trim());
}
private parsePos(node: ts.Declaration): SourcePos {
var source = node.getSourceFile();
return({
sourcePath: source.fileName,
firstLine: ts.getLineAndCharacterOfPosition(source, node.getStart()).line + 1,
lastLine: ts.getLineAndCharacterOfPosition(source, node.getEnd()).line + 1
});
}
private parseSymbol(symbol: ts.Symbol) {
var declaration = symbol.valueDeclaration;
var type: ts.Type = null;
var pos: SourcePos = null;
// Interfaces have no value declaration.
if(!declaration) declaration = symbol.getDeclarations()[0];
// On merged declaration with enums, valueDeclaration is ModuleDeclaration.
if(declaration.kind == ts.SyntaxKind.ModuleDeclaration) {
const first = symbol.getDeclarations()[0];
if(first.kind == ts.SyntaxKind.InterfaceDeclaration)
declaration = first;
}
if(declaration) {
pos = this.parsePos(declaration);
type = this.checker.getTypeOfSymbolAtLocation(symbol, declaration);
}
var spec: SymbolSpec = {
symbol: symbol,
declaration: declaration,
type: type,
name: symbol.getName(),
pos: pos,
doc: this.parseComment(symbol)
};
return(spec);
}
private parseEnum(spec: SymbolSpec) {
var enumSpec = new readts.EnumSpec(spec);
this.getRef(spec.symbol, { enum: enumSpec });
if(spec.symbol.getFlags() & ts.SymbolFlags.HasExports) {
var exportTbl = spec.symbol.exports;
for(let key of this.getKeys(exportTbl)) {
const symbol = exportTbl.get(key);
const spec = this.parseSymbol(exportTbl.get(key));
if(!spec) continue;
if(spec.symbol.getFlags() & ts.SymbolFlags.EnumMember) {
enumSpec.addMember(this.parseIdentifier(spec, false));
}
}
}
return(enumSpec);
}
private parseClass(spec: SymbolSpec) {
var classSpec = new readts.ClassSpec(spec);
this.getRef(spec.symbol, { class: classSpec });
// Interfaces have no value type.
if(spec.type) {
for(var signature of spec.type.getConstructSignatures()) {
classSpec.addConstructor(this.parseSignature(signature));
}
}
var memberTbl = spec.symbol.members;
for(let key of this.getKeys(memberTbl)) {
const spec = this.parseSymbol(memberTbl.get(key));
if(!spec) continue;
if(spec.declaration) {
if(ts.getCombinedModifierFlags(spec.declaration) & ts.ModifierFlags.Private) continue;
}
const symbolFlags = spec.symbol.getFlags();
if(symbolFlags & ts.SymbolFlags.Method) {
classSpec.addMethod(this.parseFunction(spec));
} else if(symbolFlags & ts.SymbolFlags.Property) {
classSpec.addProperty(this.parseIdentifier(spec, !!(symbolFlags & ts.SymbolFlags.Optional)));
} else if(ts.isIndexSignatureDeclaration(spec.declaration)) {
classSpec.index = this.parseIndex(spec);
}
}
const heritageClauses = (<ts.ClassLikeDeclarationBase>spec.declaration).heritageClauses;
if(heritageClauses) {
for(let heritageClause of heritageClauses) {
for(let type of heritageClause.types) {
const symbol = this.checker.getSymbolAtLocation(type.expression);
if(symbol && symbol.declarations.length) {
const ref = this.getRef(symbol);
if(ref.class) {
classSpec.addExtend(ref.class);
}
}
}
}
}
if(spec.symbol.getFlags() & ts.SymbolFlags.HasExports) {
var exportTbl = spec.symbol.exports;
for(let key of this.getKeys(exportTbl)) {
const symbol = exportTbl.get(key);
if(!(symbol.getFlags() & ts.SymbolFlags.ClassMember)) {
const spec = this.parseSymbol(exportTbl.get(key));
if(!spec) continue;
this.parseDeclaration(spec, classSpec.exports);
}
}
}
return(classSpec);
}
private parseFunction(spec: SymbolSpec) {
var funcSpec = new readts.FunctionSpec(spec);
for(var signature of spec.type.getCallSignatures()) {
funcSpec.addSignature(this.parseSignature(signature));
}
return(funcSpec);
}
private parseIndex(spec: SymbolSpec) {
var declaration = spec.declaration as ts.IndexSignatureDeclaration;
var parameter = declaration.parameters[0] as ts.ParameterDeclaration;
// ParameterDeclaration does have symbol, even though it is not on interfaces.
var singatureType = this.parseType(this.checker.getTypeOfSymbolAtLocation((<any>parameter).symbol, parameter.type));
var valueType = this.parseType(this.checker.getTypeAtLocation(declaration.type));
var indexSpec = new readts.IndexSpec(singatureType, valueType);
return(indexSpec);
}
/** Parse property, function / method parameter or variable. */
private parseIdentifier(spec: SymbolSpec, optional: boolean) {
var varSpec = new readts.IdentifierSpec(spec, this.parseType(spec.type), optional);
return(varSpec);
}
/** Parse function / method signature. */
private parseSignature(signature: ts.Signature) {
var pos: SourcePos;
var declaration = signature.getDeclaration();
if(declaration) pos = this.parsePos(declaration);
var signatureSpec = new readts.SignatureSpec(
pos,
this.parseType(signature.getReturnType()),
this.parseComment(signature)
);
for(var param of signature.parameters) {
var spec = this.parseSymbol(param);
if(spec) signatureSpec.addParam(this.parseIdentifier(spec, this.checker.isOptionalParameter(spec.declaration as ts.ParameterDeclaration)));
}
return(signatureSpec);
}
private getKeys<T>(map: ts.ReadonlyUnderscoreEscapedMap<T>): ts.__String[] {
const keys: ts.__String[] = [];
map.forEach((_, key) => keys.push(key));
return(keys);
}
private getOwnEmitOutputFilePath(sourceFile: ts.SourceFile, program: ts.Program, extension: string): string {
var getCanonicalFileName = (ts as any).createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames);
var host = {
getCanonicalFileName,
getCommonSourceDirectory: (program as any).getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
getCurrentDirectory: program.getCurrentDirectory,
};
var outPath = (ts as any).getOwnEmitOutputFilePath(sourceFile, host, extension);
return(path.resolve(program.getCurrentDirectory(), outPath));
}
private static isNodeExported(node: ts.Node) {
return(
!!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) ||
(node.parent && node.parent.kind == ts.SyntaxKind.SourceFile)
);
}
/** TypeScript services API object. */
private program: ts.Program;
/** TypeScript services type checker. */
private checker: ts.TypeChecker;
/** List of modules found while parsing. */
private moduleList: readts.ModuleSpec[];
private symbolTbl: { [name: string]: RefSpec[] };
}