/
indexer.ts
2828 lines (2636 loc) · 106 KB
/
indexer.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 The Kythe Authors. All rights reserved.
*
* 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 'source-map-support/register';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import {EdgeKind, FactName, JSONEdge, JSONFact, JSONMarkedSource, makeOrdinalEdge, MarkedSourceKind, NodeKind, OrdinalEdge, Subkind, VName} from './kythe';
import * as utf8 from './utf8';
import {CompilationUnit, Context, IndexerHost, IndexingOptions, Plugin, TSNamespace} from './plugin_api';
const LANGUAGE = 'typescript';
enum RefType {
READ,
WRITE,
READ_WRITE
}
/**
* toArray converts an Iterator to an array of its values.
* It's necessary when running in ES5 environments where for-of loops
* don't iterate through Iterators.
*/
function toArray<T>(it: Iterator<T>): T[] {
const array: T[] = [];
for (let next = it.next(); !next.done; next = it.next()) {
array.push(next.value);
}
return array;
}
/**
* stripExtension strips the .d.ts, .ts or .tsx extension from a path.
* It's used to map a file path to the module name.
*/
function stripExtension(path: string): string {
return path.replace(/\.(d\.)?tsx?$/, '');
}
/**
* Determines if a node is a variable-like declaration.
*
* TODO(https://github.com/microsoft/TypeScript/issues/33115): Replace this with
* a native `ts.isHasExpressionInitializer` if TypeScript ever adds it.
*/
function hasExpressionInitializer(node: ts.Node):
node is ts.HasExpressionInitializer {
return ts.isVariableDeclaration(node) || ts.isParameter(node) ||
ts.isBindingElement(node) || ts.isPropertySignature(node) ||
ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node) ||
ts.isEnumMember(node);
}
/**
* Determines if a node is a static member of a class.
*/
function isStaticMember(node: ts.Node, klass: ts.Declaration): boolean {
return ts.isPropertyDeclaration(node) && node.parent === klass &&
((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Static) > 0);
}
function todo(sourceRoot: string, node: ts.Node, message: string) {
const sourceFile = node.getSourceFile();
const file = path.relative(sourceRoot, sourceFile.fileName);
const {line, character} =
ts.getLineAndCharacterOfPosition(sourceFile, node.getStart());
console.warn(`TODO: ${file}:${line}:${character}: ${message}`);
}
/**
* Convert VName to a string that can be used as key in Maps.
*/
function vnameToString(vname: VName): string {
return `(${vname.corpus},${vname.language},${vname.path},${vname.root},${
vname.signature})`;
}
type NamespaceAndContext = string&{__brand: 'nsctx'};
/**
* A SymbolVNameStore stores a mapping of symbols to the (many) VNames it may
* have. Each TypeScript symbol can be be of a different TypeScript namespace
* and be declared in a unique context, leading to a total (`TSNamespace` *
* `Context`) number of possible VNames for the symbol.
*
* TSNamespace + Context
* ----------- -------
* TYPE Any
* ts.Symbol -> VALUE Getter -> VName
* NAMESPACE Setter
* ...
*
* The `Any` context makes no guarantee of symbol declaration disambiguation.
* As a result, unless explicitly set for a given symbol and namespace, the
* VName of an `Any` context is lazily set to the VName of an arbitrary context.
*/
class SymbolVNameStore {
private readonly store =
new Map<ts.Symbol, Map<NamespaceAndContext, Readonly<VName>>>();
/**
* Serializes a namespace and context as a string to lookup in the store.
*
* Each instance of a JavaScript object is unique, so using one as a key fails
* because a new object would be generated every time the store is queried.
*/
private serialize(ns: TSNamespace, context: Context): NamespaceAndContext {
return `${ns}${context}` as NamespaceAndContext;
}
/** Get a symbol VName for a given namespace and context, if it exists. */
get(symbol: ts.Symbol, ns: TSNamespace, context: Context): VName|undefined {
if (this.store.has(symbol)) {
const nsCtx = this.serialize(ns, context);
return this.store.get(symbol)!.get(nsCtx);
}
return undefined;
}
/**
* Set a symbol VName for a given namespace and context. Throws if a VName
* already exists.
*/
set(symbol: ts.Symbol, ns: TSNamespace, context: Context, vname: VName) {
let vnameMap = this.store.get(symbol);
const nsCtx = this.serialize(ns, context);
if (vnameMap) {
if (vnameMap.has(nsCtx)) {
throw new Error(`VName already set with signature ${
vnameMap.get(nsCtx)!.signature}`);
}
vnameMap.set(nsCtx, vname);
} else {
this.store.set(symbol, new Map([[nsCtx, vname]]));
}
// Set the symbol VName for the given namespace and `Any` context, if it has
// not already been set.
const nsAny = this.serialize(ns, Context.Any);
vnameMap = this.store.get(symbol)!;
if (!vnameMap.has(nsAny)) {
vnameMap.set(nsAny, vname);
}
}
}
/**
* StandardIndexerContext provides the standard definition of information about
* a TypeScript program and common methods used by the TypeScript indexer and
* its plugins. See the IndexerContext interface definition for more details.
*/
class StandardIndexerContext implements IndexerHost {
private offsetTables = new Map<string, utf8.OffsetTable>();
/** A shorter name for the rootDir in the CompilerOptions. */
private sourceRoot: string;
/**
* rootDirs is the list of rootDirs in the compiler options, sorted
* longest first. See this.moduleName().
*/
private rootDirs: string[];
/** symbolNames is a store of ts.Symbols to their assigned VNames. */
private symbolNames = new SymbolVNameStore();
/**
* anonId increments for each anonymous block, to give them unique
* signatures.
*/
private anonId = 0;
/**
* anonNames maps nodes to the anonymous names assigned to them.
*/
private anonNames = new Map<ts.Node, string>();
private typeChecker: ts.TypeChecker;
constructor(
public readonly program: ts.Program,
public readonly compilationUnit: CompilationUnit,
public readonly options: IndexingOptions,
) {
this.sourceRoot = this.program.getCompilerOptions().rootDir || process.cwd();
let rootDirs = this.program.getCompilerOptions().rootDirs || [this.sourceRoot];
rootDirs = rootDirs.map(d => d + '/');
rootDirs.sort((a, b) => b.length - a.length);
this.rootDirs = rootDirs;
this.typeChecker = this.program.getTypeChecker();
}
getOffsetTable(path: string): Readonly<utf8.OffsetTable> {
let table = this.offsetTables.get(path);
if (!table) {
const buf = (this.options.readFile || fs.readFileSync)(path);
table = new utf8.OffsetTable(buf);
this.offsetTables.set(path, table);
}
return table;
}
getSymbolAtLocation(node: ts.Node): ts.Symbol|undefined {
// Practically any interesting node has a Symbol: variables, classes, functions.
// Both named and anonymous have Symbols. We tie Symbols to Vnames so its
// important to get Symbol object for as many nodes as possible. Unfortunately
// Typescript doesn't provide good API for extracting Symbol from Nodes.
// It is supported well for named nodes, probably logic being that if you can't
// refer to a node then no need to have Symbol. But for Kythe we need to handle
// anonymous nodes as well. So we do hacks here.
// See similar bugs that haven't been resolved properly:
// https://github.com/microsoft/TypeScript/issues/26511
//
// Open FR: https://github.com/microsoft/TypeScript/issues/55433
let sym = this.typeChecker.getSymbolAtLocation(node);
if (sym) return sym;
// Check if it's named node.
if ('name' in node) {
sym = this.typeChecker.getSymbolAtLocation((node as ts.NamedDeclaration).name!);
if (sym) return sym;
}
// Sad hack. Nodes have symbol property but it's not exposed in the API.
// We could create our own Symbol instance to avoid depending on non-public API.
// But it's not clear whether it will be less maintainance.
return (node as any).symbol;
}
getSymbolAtLocationFollowingAliases(node: ts.Node): ts.Symbol|undefined {
let sym = this.getSymbolAtLocation(node);
while (sym && (sym.flags & ts.SymbolFlags.Alias) > 0) {
// a hack to prevent following aliases in cases like:
// import * as fooNamespace from './foo';
// here fooNamespace is an alias for the 'foo' module.
// We don't want to follow it so that users can easier usages
// of fooNamespace in the file.
const decl = sym.declarations?.[0];
if (decl && ts.isNamespaceImport(decl)) {
break;
}
sym = this.typeChecker.getAliasedSymbol(sym);
}
return sym;
}
/**
* anonName assigns a freshly generated name to a Node.
* It's used to give stable names to e.g. anonymous objects.
*/
anonName(node: ts.Node): string {
let name = this.anonNames.get(node);
if (!name) {
name = `anon${this.anonId++}`;
this.anonNames.set(node, name);
}
return name;
}
/**
* scopedSignature computes a scoped name for a ts.Node.
* E.g. if you have a function `foo` containing a block containing a variable
* `bar`, it might return a VName like
* signature: "foo.block0.bar""
* path: <appropriate path to module>
*/
scopedSignature(startNode: ts.Node): VName {
let moduleName: string|undefined;
const parts: string[] = [];
// Traverse the containing blocks upward, gathering names from nodes that
// introduce scopes.
for (let node: ts.Node|undefined = startNode,
lastNode: ts.Node|undefined = undefined;
node != null; lastNode = node, node = node.parent) {
// Nodes that are rvalues of a named initialization should not introduce a
// new scope. For instance, in `const a = class A {}`, `A` should
// contribute nothing to the scoped signature.
if (node.parent && hasExpressionInitializer(node.parent) &&
node.parent.name.kind === ts.SyntaxKind.Identifier) {
continue;
}
switch (node.kind) {
case ts.SyntaxKind.ExportAssignment:
const exportDecl = node as ts.ExportAssignment;
if (!exportDecl.isExportEquals) {
// It's an "export default" statement.
// This is semantically equivalent to exporting a variable
// named 'default'.
parts.push('default');
} else {
parts.push('export=');
}
break;
case ts.SyntaxKind.ArrowFunction:
// Arrow functions are anonymous, so generate a unique id.
parts.push(`arrow${this.anonId++}`);
break;
case ts.SyntaxKind.FunctionExpression:
// Function expressions look like
// (function() {})
// which have no name but introduce an anonymous scope.
parts.push(`func${this.anonId++}`);
break;
case ts.SyntaxKind.Block:
// Blocks need their own scopes for contained variable declarations.
if (node.parent &&
(node.parent.kind === ts.SyntaxKind.FunctionDeclaration ||
node.parent.kind === ts.SyntaxKind.MethodDeclaration ||
node.parent.kind === ts.SyntaxKind.Constructor ||
node.parent.kind === ts.SyntaxKind.ForStatement ||
node.parent.kind === ts.SyntaxKind.ForInStatement ||
node.parent.kind === ts.SyntaxKind.ForOfStatement)) {
// A block that's an immediate child of the above node kinds
// already has a scoped name generated by that parent.
// (It would be fine to not handle this specially and just fall
// through to the below code, but avoiding it here makes the names
// simpler.)
continue;
}
parts.push(`block${this.anonId++}`);
break;
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.ForInStatement:
case ts.SyntaxKind.ForOfStatement:
// Introduce a naming scope for all variables declared within the
// statement, so that the two 'x's declared here get different names:
// for (const x in y) { ... }
// for (const x in y) { ... }
parts.push(`for${this.anonId++}`);
break;
case ts.SyntaxKind.BindingElement:
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.ClassExpression:
case ts.SyntaxKind.EnumDeclaration:
case ts.SyntaxKind.EnumMember:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.ImportEqualsDeclaration:
case ts.SyntaxKind.ImportSpecifier:
case ts.SyntaxKind.ExportSpecifier:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.NamespaceImport:
case ts.SyntaxKind.ObjectLiteralExpression:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.PropertyAccessExpression:
case ts.SyntaxKind.PropertyAssignment:
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.TypeAliasDeclaration:
case ts.SyntaxKind.TypeParameter:
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.ShorthandPropertyAssignment:
const decl = node as ts.NamedDeclaration;
if (decl.name) {
switch (decl.name.kind) {
case ts.SyntaxKind.Identifier:
case ts.SyntaxKind.PrivateIdentifier:
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NumericLiteral:
case ts.SyntaxKind.ComputedPropertyName:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
let part;
if (ts.isComputedPropertyName(decl.name)) {
const sym = this.getSymbolAtLocationFollowingAliases(decl.name);
part = sym ? sym.name : this.anonName(decl.name);
} else {
part = decl.name.text;
}
// Wrap literals in quotes, so that characters used in other
// signatures do not interfere with the signature created by a
// literal. For instance, a literal
// obj.prop
// may interefere with the signature of `prop` on an object
// `obj`. The literal receives a signature
// "obj.prop"
// to avoid this.
if (ts.isStringLiteral(decl.name)) {
part = `"${part}"`;
}
// Instance members of a class are scoped to the type of the
// class.
if (ts.isClassDeclaration(decl) && lastNode !== undefined &&
ts.isClassElement(lastNode) &&
!isStaticMember(lastNode, decl) &&
// special case constructor. We want it to no have
// #type modifier as constructor will have the same name
// as class.
!ts.isConstructorDeclaration(startNode)) {
part += '#type';
}
// Getters and setters semantically refer to the same entities
// but are declared differently, so they are differentiated.
if (ts.isGetAccessor(decl)) {
part += ':getter';
} else if (ts.isSetAccessor(decl)) {
part += ':setter';
}
parts.push(part);
break;
default:
// Skip adding an anonymous scope for variables declared in an
// array or object binding pattern like `const [a] = [0]`.
break;
}
} else {
parts.push(this.anonName(node));
}
break;
case ts.SyntaxKind.Constructor:
// Class members declared with a shorthand in the constructor should
// be scoped to the class, not the constructor.
if (!ts.isParameterPropertyDeclaration(startNode, startNode.parent) &&
startNode !== node) {
parts.push('constructor');
}
break;
case ts.SyntaxKind.ImportClause:
// An import clause can have one of two forms:
// import foo from './bar';
// import {foo as far} from './bar';
// In the first case the clause has a name "foo". In this case add the
// name of the clause to the signature.
// In the second case the clause has no explicit name. This
// contributes nothing to the signature without risk of naming
// conflicts because TS imports are essentially file-global lvalues.
const importClause = node as ts.ImportClause;
if (importClause.name) {
parts.push(importClause.name.text);
}
break;
case ts.SyntaxKind.ModuleDeclaration:
const modDecl = node as ts.ModuleDeclaration;
if (modDecl.name.kind === ts.SyntaxKind.StringLiteral) {
// Syntax like:
// declare module 'foo/bar' {}
// This is the syntax for defining symbols in another, named
// module.
moduleName = (modDecl.name as ts.StringLiteral).text;
} else if (modDecl.name.kind === ts.SyntaxKind.Identifier) {
// Syntax like:
// declare module foo {}
// without quotes is just an obsolete way of saying 'namespace'.
parts.push((modDecl.name as ts.Identifier).text);
}
break;
case ts.SyntaxKind.SourceFile:
// moduleName can already be set if the target was contained within
// a "declare module 'foo/bar'" block (see the handling of
// ModuleDeclaration). Otherwise, the module name is derived from the
// name of the current file.
if (!moduleName) {
moduleName = this.moduleName((node as ts.SourceFile).fileName);
}
break;
case ts.SyntaxKind.JsxElement:
case ts.SyntaxKind.JsxSelfClosingElement:
case ts.SyntaxKind.JsxAttribute:
// Given a unique anonymous name to all JSX nodes. This prevents
// conflicts in cases where attributes would otherwise have the same
// name, like `src` in
// <img src={a} />
// <img src={b} />
parts.push(`jsx${this.anonId++}`);
break;
default:
// Most nodes are children of other nodes that do not introduce a
// new namespace, e.g. "return x;", so ignore all other parents
// by default.
// TODO: namespace {}, etc.
// If the node is actually some subtype that has a 'name' attribute
// and it's not empty it's likely this function should have handled
// it. Dynamically probe for this case and warn if we missed one.
if ((node as any).name != null) {
todo(
this.sourceRoot, node,
`scopedSignature: ${ts.SyntaxKind[node.kind]} ` +
`has unused 'name' property`);
}
}
}
// The names were gathered from bottom to top, so reverse before joining.
const signature = parts.reverse().join('.');
return Object.assign(
this.pathToVName(moduleName!), {signature, language: LANGUAGE});
}
/**
* getSymbolName computes the VName of a ts.Symbol. A Context can be
* optionally specified to help disambiguate nodes with multiple declarations.
* See the documentation of Context for more information.
*/
getSymbolName(
sym: ts.Symbol, ns: TSNamespace, context: Context = Context.Any): VName
|undefined {
const stored = this.symbolNames.get(sym, ns, context);
if (stored) return stored;
if (!sym.declarations || sym.declarations.length < 1) {
return undefined;
}
let declarations = sym.declarations;
// Disambiguate symbols with multiple declarations using a context.
if (sym.declarations.length > 1) {
switch (context) {
case Context.Getter:
declarations = declarations.filter(ts.isGetAccessor);
break;
case Context.Setter:
declarations = declarations.filter(ts.isSetAccessor);
break;
default:
break;
}
}
const decl = declarations[0];
const vname = this.scopedSignature(decl);
// The signature of a value is undecorated.
// The signature of a type has the #type suffix.
// The signature of a namespace has the #namespace suffix.
if (ns === TSNamespace.TYPE) {
vname.signature += '#type';
} else if (ns === TSNamespace.NAMESPACE) {
vname.signature += '#namespace';
} else if (ns === TSNamespace.TYPE_MIGRATION) {
vname.signature += '#mtype';
}
// Cache the VName for future lookups.
this.symbolNames.set(sym, ns, context, vname);
return vname;
}
/**
* moduleName returns the ES6 module name of a path to a source file.
* E.g. foo/bar.ts and foo/bar.d.ts both have the same module name,
* 'foo/bar', and rootDirs (like bazel-bin/) are eliminated.
* See README.md for a discussion of this.
*/
moduleName(sourcePath: string): string {
// Compute sourcePath as relative to one of the rootDirs.
// This canonicalizes e.g. bazel-bin/foo to just foo.
// Note that this.rootDirs is sorted longest first, so we'll use the
// longest match.
for (const rootDir of this.rootDirs) {
if (sourcePath.startsWith(rootDir)) {
sourcePath = path.relative(rootDir, sourcePath);
break;
}
}
return stripExtension(sourcePath);
}
/**
* pathToVName returns the VName for a given file path.
*
* This function is used for 2 distinct cases that should be ideally separated
* in 2 different functions. `path` can be one of two:
* 1. Full path like 'bazel-out/genfiles/path/to/file.ts'.
* This path is used to build VNames for files and anchors.
* 2. Module name like 'path/to/file'.
* This path is used to build VNames for semantic nodes.
*
* Only for full paths `pathVnames` contains an entry. For short paths (module
* names) this function will defaults to calculating vname based on path
* and compilation unit.
*/
pathToVName(path: string): VName {
const vname = this.compilationUnit.fileVNames.get(path);
return {
signature: '',
language: '',
corpus: vname && vname.corpus ? vname.corpus :
this.compilationUnit.rootVName.corpus,
root: vname && vname.corpus ? vname.root : this.compilationUnit.rootVName.root,
path: vname && vname.path ? vname.path : path,
};
}
}
const RE_FIRST_NON_WS = /\S|$/;
const RE_NEWLINE = /\r?\n/;
const MAX_MS_TEXT_LENGTH = 1_000;
/**
* Formats a MarkedSource text component by
* - stripping the text to its first MAX_MS_TEXT_LENGTH characters
* - trimming the text
* - stripping the leading whitespace of each line in multi-line string by the
* shortest non-zero whitespace length. For example,
* [
* 1,
* 2,
* ]
* becomes
* [
* 1,
* 2,
* ]
*/
function fmtMarkedSource(s: string) {
if (s.search(RE_FIRST_NON_WS) === s.length) {
// String is all whitespace, keep as-is
return s;
}
let isChopped = false;
if (s.length > MAX_MS_TEXT_LENGTH) {
// Trim left first to pick up more chars before chopping the string
s = s.trimLeft();
s = s.substring(0, MAX_MS_TEXT_LENGTH);
isChopped = true;
}
s = s.replace(/\t/g, ' '); // normalize tabs for display
const lines = s.split(RE_NEWLINE);
let shortestLeading = lines[lines.length - 1].search(RE_FIRST_NON_WS);
for (let i = 1; i < lines.length - 1; ++i) {
shortestLeading =
Math.min(shortestLeading, lines[i].search(RE_FIRST_NON_WS));
}
for (let i = 1; i < lines.length; ++i) {
lines[i] = lines[i].substring(shortestLeading);
}
s = lines.join('\n');
if (isChopped) {
s += '...';
}
return s;
}
function isNonNullableArray<T>(arr: Array<T>): arr is Array<NonNullable<T>> {
return arr.findIndex(el => el === undefined || el === null) === -1;
}
/** Visitor manages the indexing process for a single TypeScript SourceFile. */
class Visitor {
/** kFile is the VName for the 'file' node representing the source file. */
kFile: VName;
/** A shorter name for the rootDir in the CompilerOptions. */
sourceRoot: string;
typeChecker: ts.TypeChecker;
/** influencers is a stack of influencer VNames. */
private readonly influencers: Set<VName>[] = [];
/** Cached anchor nodes. Signature is used as key. */
private readonly anchors = new Map<string, VName>();
constructor(
private readonly host: IndexerHost,
private file: ts.SourceFile,
) {
this.sourceRoot =
this.host.program.getCompilerOptions().rootDir || process.cwd();
this.typeChecker = this.host.program.getTypeChecker();
this.kFile = this.newFileVName(file.fileName);
}
/**
* newFileVName returns a new VName for the given file path.
*/
newFileVName(path: string): VName {
return this.host.pathToVName(path);
}
/**
* newVName returns a new VName with a given signature and path.
*/
newVName(signature: string, path: string): VName {
return Object.assign(
this.newFileVName(path), {signature: signature, language: LANGUAGE});
}
/** newAnchor emits a new anchor entry that covers a TypeScript node. */
newAnchor(node: ts.Node, start = node.getStart(), end = node.end, tag = ''):
VName {
const signature = `@${tag}${start}:${end}`;
const cachedName = this.anchors.get(signature);
if (cachedName != null) return cachedName;
const name =
Object.assign({...this.kFile}, {signature, language: LANGUAGE});
this.emitNode(name, NodeKind.ANCHOR);
const offsetTable = this.host.getOffsetTable(node.getSourceFile().fileName);
this.emitFact(
name, FactName.LOC_START, offsetTable.lookupUtf8(start).toString());
this.emitFact(
name, FactName.LOC_END, offsetTable.lookupUtf8(end).toString());
this.anchors.set(signature, name);
return name;
}
/** emitNode emits a new node entry, declaring the kind of a VName. */
emitNode(source: VName, kind: NodeKind) {
this.emitFact(source, FactName.NODE_KIND, kind);
}
/** emitSubkind emits a new fact entry, declaring the subkind of a VName. */
emitSubkind(source: VName, subkind: Subkind) {
this.emitFact(source, FactName.SUBKIND, subkind);
}
/** emitFact emits a new fact entry, tying an attribute to a VName. */
emitFact(source: VName, name: FactName, value: string|Uint8Array) {
this.host.options.emit({
source,
fact_name: name,
fact_value: Buffer.from(value).toString('base64'),
});
}
/** emitEdge emits a new edge entry, relating two VNames. */
emitEdge(source: VName, kind: EdgeKind|OrdinalEdge, target: VName) {
this.host.options.emit({
source,
edge_kind: kind,
target,
fact_name: '/',
});
}
/** forAllInfluencers executes fn for each influencer in the active set. */
forAllInfluencers(fn: (influencer: VName) => void) {
if (this.influencers.length != 0) {
this.influencers[this.influencers.length - 1].forEach(fn);
}
}
/** addInfluencer adds influencer to the active set. */
addInfluencer(influencer: VName) {
if (this.influencers.length != 0) {
this.influencers[this.influencers.length - 1].add(influencer);
}
}
/** popInfluencers pops the active influencer set. */
popInfluencers() {
if (this.influencers.length != 0) {
this.influencers.pop();
}
}
/** pushInfluencers pushes a new active influencer set. */
pushInfluencers() {
this.influencers.push(new Set<VName>());
}
visitTypeParameters(
parent: VName|undefined,
params: ReadonlyArray<ts.TypeParameterDeclaration>) {
for (var ordinal = 0; ordinal < params.length; ++ordinal) {
const param = params[ordinal];
const sym = this.host.getSymbolAtLocationFollowingAliases(param.name);
if (!sym) {
todo(
this.sourceRoot, param,
`type param ${param.getText()} has no symbol`);
return;
}
const kTVar = this.host.getSymbolName(sym, TSNamespace.TYPE_MIGRATION);
if (kTVar && parent) {
this.emitNode(kTVar, NodeKind.TVAR);
this.emitEdge(
this.newAnchor(
param.name, param.name.getStart(), param.name.end, 'M'),
EdgeKind.DEFINES_BINDING, kTVar);
this.emitEdge(parent, makeOrdinalEdge(EdgeKind.TPARAM, ordinal), kTVar);
// ...<T extends A>
if (param.constraint) {
var superType = this.visitType(param.constraint);
if (superType)
this.emitEdge(kTVar, EdgeKind.BOUNDED_UPPER, superType);
}
// ...<T = A>
if (param.default) this.visitType(param.default);
}
}
}
/**
* Adds influence edges for return statements.
*/
visitReturnStatement(node: ts.ReturnStatement) {
this.pushInfluencers();
ts.forEachChild(node, n => {
this.visit(n);
});
const containingFunction = this.getContainingFunctionNode(node);
if (!ts.isSourceFile(containingFunction)) {
const containingVName =
this.getSymbolAndVNameForFunctionDeclaration(containingFunction)
.vname;
if (containingVName) {
this.forAllInfluencers(influencer => {
this.emitEdge(influencer, EdgeKind.INFLUENCES, containingVName);
});
}
// Handle case like
// "return {name: 'Alice'};"
// where return type of the function is a named type, e.g. Person.
// This will connect 'name' property of the object literal to the
// Person.name property.
if (node.expression && ts.isObjectLiteralExpression(node.expression)) {
this.connectObjectLiteralToType(
node.expression, containingFunction.type);
}
}
this.popInfluencers();
}
getCallAnchor(callee:any) {
if (!this.host.options.emitRefCallOverIdentifier) {
return undefined;
}
for (;;) {
if (ts.isIdentifier(callee)) {
return this.newAnchor(callee);
}
if (ts.isPropertyAccessExpression(callee)) {
callee = callee.name;
continue;
}
if (ts.isNewExpression(callee)) {
callee = callee.expression;
continue;
}
return undefined;
}
}
/**
* Emits `ref/call` edges required for call graph:
* https://kythe.io/docs/schema/callgraph.html
*/
visitCallOrNewExpression(node: ts.CallExpression|ts.NewExpression) {
ts.forEachChild(node, n => {
this.visit(n);
});
// Special case dynamic imports as they are represendted as CallExpressions.
// We don't want to emit ref/call as we don't have anything to point it at:
// there is no import() function
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
this.visitDynamicImportCall(node);
return;
}
// Handle case of immediately-invoked functions like:
// (() => do stuff... )();
let expression: ts.Node = node.expression;
while (ts.isParenthesizedExpression(expression)) {
expression = expression.expression;
}
const symbol = this.host.getSymbolAtLocationFollowingAliases(expression);
if (!symbol) {
return;
}
const name = this.host.getSymbolName(symbol, TSNamespace.VALUE);
if (!name) {
return;
}
const callAnchor = this.getCallAnchor(node.expression) ?? this.newAnchor(node);
this.emitEdge(callAnchor, EdgeKind.REF_CALL, name);
// Each call should have a childof edge to its containing function
// scope.
const containingFunction = this.getContainingFunctionNode(node);
let containingVName: VName|undefined;
if (ts.isSourceFile(containingFunction)) {
containingVName = this.getSyntheticFileInitVName();
} else {
containingVName =
this.getSymbolAndVNameForFunctionDeclaration(containingFunction)
.vname;
}
if (containingVName) {
this.emitEdge(callAnchor, EdgeKind.CHILD_OF, containingVName);
}
// Handle function/constructor calls like `doSomething({name: 'Alice'})`
// where type of the argument is, for example, an interface Person. This
// will add ref from object literal 'name' property to Person.name field.
if (node.arguments != null) {
const signature = this.typeChecker.getResolvedSignature(node);
if (signature == null) return;
for (let i = 0; i < node.arguments.length; i++) {
const argument = node.arguments[i];
// get parameter of the function/constructor signature.
const signParameter = signature.parameters[i]?.valueDeclaration;
if (ts.isObjectLiteralExpression(argument) && signParameter &&
ts.isParameter(signParameter)) {
this.connectObjectLiteralToType(argument, signParameter.type);
}
}
}
}
/**
* visitHeritage visits the X found in an 'extends X' or 'implements X'.
*
* These are subtle in an interesting way. When you have
* interface X extends Y {}
* that is referring to the *type* Y (because interfaces are types, not
* values). But it's also legal to write
* class X extends (class Z { ... }) {}
* where the thing in the extends clause is itself an expression, and the
* existing logic for visiting a class expression already handles modelling
* the class as both a type and a value.
*
* The full set of possible combinations is:
* - class extends => value
* - interface extends => type
* - class implements => type
* - interface implements => illegal
*/
visitHeritage(
classOrInterface: VName|undefined,
heritageClauses: ReadonlyArray<ts.HeritageClause>) {
for (const heritage of heritageClauses) {
if (heritage.token === ts.SyntaxKind.ExtendsKeyword && heritage.parent &&
heritage.parent.kind !== ts.SyntaxKind.InterfaceDeclaration) {
this.visit(heritage);
} else {
this.visitType(heritage);
}
// Add extends edges.
if (classOrInterface == null) {
// classOrInterface is null for anonymous classes.
// But anonymous classes can implement and extends other
// classes and interfaces. So currently this edge
// is missing. Once we have nodes for anonymous classes -
// we can add this missing edges.
continue;
}
for (const baseType of heritage.types) {
const type = this.typeChecker.getTypeAtLocation(baseType);
if (!type || !type.symbol) {
continue;
}
const vname = this.host.getSymbolName(type.symbol, TSNamespace.TYPE);
if (vname) {
this.emitEdge(classOrInterface, EdgeKind.EXTENDS, vname);
}
}
}
}
visitInterfaceDeclaration(decl: ts.InterfaceDeclaration) {
const sym = this.host.getSymbolAtLocationFollowingAliases(decl.name);
if (!sym) {
todo(
this.sourceRoot, decl.name,
`interface ${decl.name.getText()} has no symbol`);
return;
}
const kType = this.host.getSymbolName(sym, TSNamespace.TYPE);
if (kType) {
this.emitNode(kType, NodeKind.INTERFACE);
this.emitEdge(this.newAnchor(decl.name), EdgeKind.DEFINES_BINDING, kType);
this.visitJSDoc(decl, kType);
this.emitMarkedSourceForClasslikeDeclaration(decl, kType);
}
if (decl.typeParameters)
this.visitTypeParameters(kType, decl.typeParameters);
if (decl.heritageClauses) this.visitHeritage(kType, decl.heritageClauses);
for (const member of decl.members) {
this.visit(member);
}
}
visitTypeAliasDeclaration(decl: ts.TypeAliasDeclaration) {
const sym = this.host.getSymbolAtLocationFollowingAliases(decl.name);
if (!sym) {
todo(
this.sourceRoot, decl.name,
`type alias ${decl.name.getText()} has no symbol`);
return;