-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
template_symbol_builder.ts
717 lines (628 loc) · 26.9 KB
/
template_symbol_builder.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AST, ASTWithSource, BindingPipe, ParseSourceSpan, PropertyRead, PropertyWrite, R3Identifiers, SafePropertyRead, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstElement, TmplAstNode, TmplAstReference, TmplAstTemplate, TmplAstTextAttribute, TmplAstVariable} from '@angular/compiler';
import ts from 'typescript';
import {AbsoluteFsPath} from '../../file_system';
import {Reference} from '../../imports';
import {HostDirectiveMeta} from '../../metadata';
import {ClassDeclaration} from '../../reflection';
import {ComponentScopeKind, ComponentScopeReader} from '../../scope';
import {isAssignment, isSymbolWithValueDeclaration} from '../../util/src/typescript';
import {BindingSymbol, DirectiveSymbol, DomBindingSymbol, ElementSymbol, ExpressionSymbol, InputBindingSymbol, OutputBindingSymbol, PipeSymbol, ReferenceSymbol, Symbol, SymbolKind, TcbLocation, TemplateSymbol, TsNodeSymbolInfo, TypeCheckableDirectiveMeta, VariableSymbol} from '../api';
import {ExpressionIdentifier, findAllMatchingNodes, findFirstMatchingNode, hasExpressionIdentifier} from './comments';
import {TemplateData} from './context';
import {isAccessExpression} from './ts_util';
/**
* Generates and caches `Symbol`s for various template structures for a given component.
*
* The `SymbolBuilder` internally caches the `Symbol`s it creates, and must be destroyed and
* replaced if the component's template changes.
*/
export class SymbolBuilder {
private symbolCache = new Map<AST|TmplAstNode, Symbol|null>();
constructor(
private readonly tcbPath: AbsoluteFsPath,
private readonly tcbIsShim: boolean,
private readonly typeCheckBlock: ts.Node,
private readonly templateData: TemplateData,
private readonly componentScopeReader: ComponentScopeReader,
// The `ts.TypeChecker` depends on the current type-checking program, and so must be requested
// on-demand instead of cached.
private readonly getTypeChecker: () => ts.TypeChecker,
) {}
getSymbol(node: TmplAstTemplate|TmplAstElement): TemplateSymbol|ElementSymbol|null;
getSymbol(node: TmplAstReference|TmplAstVariable): ReferenceSymbol|VariableSymbol|null;
getSymbol(node: AST|TmplAstNode): Symbol|null;
getSymbol(node: AST|TmplAstNode): Symbol|null {
if (this.symbolCache.has(node)) {
return this.symbolCache.get(node)!;
}
let symbol: Symbol|null = null;
if (node instanceof TmplAstBoundAttribute || node instanceof TmplAstTextAttribute) {
// TODO(atscott): input and output bindings only return the first directive match but should
// return a list of bindings for all of them.
symbol = this.getSymbolOfInputBinding(node);
} else if (node instanceof TmplAstBoundEvent) {
symbol = this.getSymbolOfBoundEvent(node);
} else if (node instanceof TmplAstElement) {
symbol = this.getSymbolOfElement(node);
} else if (node instanceof TmplAstTemplate) {
symbol = this.getSymbolOfAstTemplate(node);
} else if (node instanceof TmplAstVariable) {
symbol = this.getSymbolOfVariable(node);
} else if (node instanceof TmplAstReference) {
symbol = this.getSymbolOfReference(node);
} else if (node instanceof BindingPipe) {
symbol = this.getSymbolOfPipe(node);
} else if (node instanceof AST) {
symbol = this.getSymbolOfTemplateExpression(node);
} else {
// TODO(atscott): TmplAstContent, TmplAstIcu
}
this.symbolCache.set(node, symbol);
return symbol;
}
private getSymbolOfAstTemplate(template: TmplAstTemplate): TemplateSymbol|null {
const directives = this.getDirectivesOfNode(template);
return {kind: SymbolKind.Template, directives, templateNode: template};
}
private getSymbolOfElement(element: TmplAstElement): ElementSymbol|null {
const elementSourceSpan = element.startSourceSpan ?? element.sourceSpan;
const node = findFirstMatchingNode(
this.typeCheckBlock, {withSpan: elementSourceSpan, filter: ts.isVariableDeclaration});
if (node === null) {
return null;
}
const symbolFromDeclaration = this.getSymbolOfTsNode(node);
if (symbolFromDeclaration === null || symbolFromDeclaration.tsSymbol === null) {
return null;
}
const directives = this.getDirectivesOfNode(element);
// All statements in the TCB are `Expression`s that optionally include more information.
// An `ElementSymbol` uses the information returned for the variable declaration expression,
// adds the directives for the element, and updates the `kind` to be `SymbolKind.Element`.
return {
...symbolFromDeclaration,
kind: SymbolKind.Element,
directives,
templateNode: element,
};
}
private getDirectivesOfNode(element: TmplAstElement|TmplAstTemplate): DirectiveSymbol[] {
const elementSourceSpan = element.startSourceSpan ?? element.sourceSpan;
const tcbSourceFile = this.typeCheckBlock.getSourceFile();
// directives could be either:
// - var _t1: TestDir /*T:D*/ = null! as TestDir;
// - var _t1 /*T:D*/ = _ctor1({});
const isDirectiveDeclaration = (node: ts.Node): node is ts.TypeNode|ts.Identifier =>
(ts.isTypeNode(node) || ts.isIdentifier(node)) && ts.isVariableDeclaration(node.parent) &&
hasExpressionIdentifier(tcbSourceFile, node, ExpressionIdentifier.DIRECTIVE);
const nodes = findAllMatchingNodes(
this.typeCheckBlock, {withSpan: elementSourceSpan, filter: isDirectiveDeclaration});
const symbols: DirectiveSymbol[] = [];
for (const node of nodes) {
const symbol = this.getSymbolOfTsNode(node.parent);
if (symbol === null || !isSymbolWithValueDeclaration(symbol.tsSymbol) ||
!ts.isClassDeclaration(symbol.tsSymbol.valueDeclaration)) {
continue;
}
const meta = this.getDirectiveMeta(element, symbol.tsSymbol.valueDeclaration);
if (meta !== null && meta.selector !== null) {
const ref = new Reference<ClassDeclaration>(symbol.tsSymbol.valueDeclaration as any);
if (meta.hostDirectives !== null) {
this.addHostDirectiveSymbols(element, meta.hostDirectives, symbols);
}
const directiveSymbol: DirectiveSymbol = {
...symbol,
ref,
tsSymbol: symbol.tsSymbol,
selector: meta.selector,
isComponent: meta.isComponent,
ngModule: this.getDirectiveModule(symbol.tsSymbol.valueDeclaration),
kind: SymbolKind.Directive,
isStructural: meta.isStructural,
isInScope: true,
isHostDirective: false,
};
symbols.push(directiveSymbol);
}
}
return symbols;
}
private addHostDirectiveSymbols(
host: TmplAstTemplate|TmplAstElement, hostDirectives: HostDirectiveMeta[],
symbols: DirectiveSymbol[]): void {
for (const current of hostDirectives) {
if (!ts.isClassDeclaration(current.directive.node)) {
continue;
}
const symbol = this.getSymbolOfTsNode(current.directive.node);
const meta = this.getDirectiveMeta(host, current.directive.node);
if (meta !== null && symbol !== null && isSymbolWithValueDeclaration(symbol.tsSymbol)) {
if (meta.hostDirectives !== null) {
this.addHostDirectiveSymbols(host, meta.hostDirectives, symbols);
}
const directiveSymbol: DirectiveSymbol = {
...symbol,
isHostDirective: true,
ref: current.directive,
tsSymbol: symbol.tsSymbol,
exposedInputs: current.inputs,
exposedOutputs: current.outputs,
selector: meta.selector,
isComponent: meta.isComponent,
ngModule: this.getDirectiveModule(current.directive.node),
kind: SymbolKind.Directive,
isStructural: meta.isStructural,
isInScope: true,
};
symbols.push(directiveSymbol);
}
}
}
private getDirectiveMeta(
host: TmplAstTemplate|TmplAstElement,
directiveDeclaration: ts.Declaration): TypeCheckableDirectiveMeta|null {
let directives = this.templateData.boundTarget.getDirectivesOfNode(host);
// `getDirectivesOfNode` will not return the directives intended for an element
// on a microsyntax template, for example `<div *ngFor="let user of users;" dir>`,
// the `dir` will be skipped, but it's needed in language service.
const firstChild = host.children[0];
if (firstChild instanceof TmplAstElement) {
const isMicrosyntaxTemplate = host instanceof TmplAstTemplate &&
sourceSpanEqual(firstChild.sourceSpan, host.sourceSpan);
if (isMicrosyntaxTemplate) {
const firstChildDirectives = this.templateData.boundTarget.getDirectivesOfNode(firstChild);
if (firstChildDirectives !== null && directives !== null) {
directives = directives.concat(firstChildDirectives);
} else {
directives = directives ?? firstChildDirectives;
}
}
}
if (directives === null) {
return null;
}
return directives.find(m => m.ref.node === directiveDeclaration) ?? null;
}
private getDirectiveModule(declaration: ts.ClassDeclaration): ClassDeclaration|null {
const scope = this.componentScopeReader.getScopeForComponent(declaration as ClassDeclaration);
if (scope === null || scope.kind !== ComponentScopeKind.NgModule) {
return null;
}
return scope.ngModule;
}
private getSymbolOfBoundEvent(eventBinding: TmplAstBoundEvent): OutputBindingSymbol|null {
const consumer = this.templateData.boundTarget.getConsumerOfBinding(eventBinding);
if (consumer === null) {
return null;
}
// Outputs in the TCB look like one of the two:
// * _t1["outputField"].subscribe(handler);
// * _t1.addEventListener(handler);
// Even with strict null checks disabled, we still produce the access as a separate statement
// so that it can be found here.
let expectedAccess: string;
if (consumer instanceof TmplAstTemplate || consumer instanceof TmplAstElement) {
expectedAccess = 'addEventListener';
} else {
const bindingPropertyNames = consumer.outputs.getByBindingPropertyName(eventBinding.name);
if (bindingPropertyNames === null || bindingPropertyNames.length === 0) {
return null;
}
// Note that we only get the expectedAccess text from a single consumer of the binding. If
// there are multiple consumers (not supported in the `boundTarget` API) and one of them has
// an alias, it will not get matched here.
expectedAccess = bindingPropertyNames[0].classPropertyName;
}
function filter(n: ts.Node): n is ts.PropertyAccessExpression|ts.ElementAccessExpression {
if (!isAccessExpression(n)) {
return false;
}
if (ts.isPropertyAccessExpression(n)) {
return n.name.getText() === expectedAccess;
} else {
return ts.isStringLiteral(n.argumentExpression) &&
n.argumentExpression.text === expectedAccess;
}
}
const outputFieldAccesses =
findAllMatchingNodes(this.typeCheckBlock, {withSpan: eventBinding.keySpan, filter});
const bindings: BindingSymbol[] = [];
for (const outputFieldAccess of outputFieldAccesses) {
if (consumer instanceof TmplAstTemplate || consumer instanceof TmplAstElement) {
if (!ts.isPropertyAccessExpression(outputFieldAccess)) {
continue;
}
const addEventListener = outputFieldAccess.name;
const tsSymbol = this.getTypeChecker().getSymbolAtLocation(addEventListener);
const tsType = this.getTypeChecker().getTypeAtLocation(addEventListener);
const positionInFile = this.getTcbPositionForNode(addEventListener);
const target = this.getSymbol(consumer);
if (target === null || tsSymbol === undefined) {
continue;
}
bindings.push({
kind: SymbolKind.Binding,
tsSymbol,
tsType,
target,
tcbLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile,
},
});
} else {
if (!ts.isElementAccessExpression(outputFieldAccess)) {
continue;
}
const tsSymbol =
this.getTypeChecker().getSymbolAtLocation(outputFieldAccess.argumentExpression);
if (tsSymbol === undefined) {
continue;
}
const target = this.getDirectiveSymbolForAccessExpression(outputFieldAccess, consumer);
if (target === null) {
continue;
}
const positionInFile = this.getTcbPositionForNode(outputFieldAccess);
const tsType = this.getTypeChecker().getTypeAtLocation(outputFieldAccess);
bindings.push({
kind: SymbolKind.Binding,
tsSymbol,
tsType,
target,
tcbLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile,
},
});
}
}
if (bindings.length === 0) {
return null;
}
return {kind: SymbolKind.Output, bindings};
}
private getSymbolOfInputBinding(binding: TmplAstBoundAttribute|
TmplAstTextAttribute): InputBindingSymbol|DomBindingSymbol|null {
const consumer = this.templateData.boundTarget.getConsumerOfBinding(binding);
if (consumer === null) {
return null;
}
if (consumer instanceof TmplAstElement || consumer instanceof TmplAstTemplate) {
const host = this.getSymbol(consumer);
return host !== null ? {kind: SymbolKind.DomBinding, host} : null;
}
const nodes = findAllMatchingNodes(
this.typeCheckBlock, {withSpan: binding.sourceSpan, filter: isAssignment});
const bindings: BindingSymbol[] = [];
for (const node of nodes) {
if (!isAccessExpression(node.left)) {
continue;
}
const signalInputAssignment = unwrapSignalInputWriteTAccessor(node.left);
let symbolInfo: TsNodeSymbolInfo|null = null;
// Signal inputs need special treatment because they are generated with an extra keyed
// access. E.g. `_t1.prop[WriteT_ACCESSOR_SYMBOL]`. Observations:
// - The keyed access for the write type needs to be resolved for the "input type".
// - The definition symbol of the input should be the input class member, and not the
// internal write accessor. Symbol should resolve `_t1.prop`.
if (signalInputAssignment !== null) {
const fieldSymbol = this.getSymbolOfTsNode(signalInputAssignment.fieldExpr);
const typeSymbol = this.getSymbolOfTsNode(signalInputAssignment.typeExpr);
symbolInfo = fieldSymbol === null || typeSymbol === null ? null : {
tcbLocation: fieldSymbol.tcbLocation,
tsSymbol: fieldSymbol.tsSymbol,
tsType: typeSymbol.tsType,
};
} else {
symbolInfo = this.getSymbolOfTsNode(node.left);
}
if (symbolInfo === null || symbolInfo.tsSymbol === null) {
continue;
}
const target = this.getDirectiveSymbolForAccessExpression(
signalInputAssignment?.fieldExpr ?? node.left, consumer);
if (target === null) {
continue;
}
bindings.push({
...symbolInfo,
tsSymbol: symbolInfo.tsSymbol,
kind: SymbolKind.Binding,
target,
});
}
if (bindings.length === 0) {
return null;
}
return {kind: SymbolKind.Input, bindings};
}
private getDirectiveSymbolForAccessExpression(
fieldAccessExpr: ts.ElementAccessExpression|ts.PropertyAccessExpression,
{isComponent, selector, isStructural}: TypeCheckableDirectiveMeta): DirectiveSymbol|null {
// In all cases, `_t1["index"]` or `_t1.index`, `node.expression` is _t1.
const tsSymbol = this.getTypeChecker().getSymbolAtLocation(fieldAccessExpr.expression);
if (tsSymbol?.declarations === undefined || tsSymbol.declarations.length === 0 ||
selector === null) {
return null;
}
const [declaration] = tsSymbol.declarations;
if (!ts.isVariableDeclaration(declaration) ||
!hasExpressionIdentifier(
// The expression identifier could be on the type (for regular directives) or the name
// (for generic directives and the ctor op).
declaration.getSourceFile(), declaration.type ?? declaration.name,
ExpressionIdentifier.DIRECTIVE)) {
return null;
}
const symbol = this.getSymbolOfTsNode(declaration);
if (symbol === null || !isSymbolWithValueDeclaration(symbol.tsSymbol) ||
!ts.isClassDeclaration(symbol.tsSymbol.valueDeclaration)) {
return null;
}
const ref: Reference<ClassDeclaration> = new Reference(symbol.tsSymbol.valueDeclaration as any);
const ngModule = this.getDirectiveModule(symbol.tsSymbol.valueDeclaration);
return {
ref,
kind: SymbolKind.Directive,
tsSymbol: symbol.tsSymbol,
tsType: symbol.tsType,
tcbLocation: symbol.tcbLocation,
isComponent,
isStructural,
selector,
ngModule,
isHostDirective: false,
isInScope: true, // TODO: this should always be in scope in this context, right?
};
}
private getSymbolOfVariable(variable: TmplAstVariable): VariableSymbol|null {
const node = findFirstMatchingNode(
this.typeCheckBlock, {withSpan: variable.sourceSpan, filter: ts.isVariableDeclaration});
if (node === null) {
return null;
}
let nodeValueSymbol: TsNodeSymbolInfo|null = null;
if (ts.isForOfStatement(node.parent.parent)) {
nodeValueSymbol = this.getSymbolOfTsNode(node);
} else if (node.initializer !== undefined) {
nodeValueSymbol = this.getSymbolOfTsNode(node.initializer);
}
if (nodeValueSymbol === null) {
return null;
}
return {
tsType: nodeValueSymbol.tsType,
tsSymbol: nodeValueSymbol.tsSymbol,
initializerLocation: nodeValueSymbol.tcbLocation,
kind: SymbolKind.Variable,
declaration: variable,
localVarLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: this.getTcbPositionForNode(node.name),
}
};
}
private getSymbolOfReference(ref: TmplAstReference): ReferenceSymbol|null {
const target = this.templateData.boundTarget.getReferenceTarget(ref);
// Find the node for the reference declaration, i.e. `var _t2 = _t1;`
let node = findFirstMatchingNode(
this.typeCheckBlock, {withSpan: ref.sourceSpan, filter: ts.isVariableDeclaration});
if (node === null || target === null || node.initializer === undefined) {
return null;
}
// Get the original declaration for the references variable, with the exception of template refs
// which are of the form var _t3 = (_t2 as any as i2.TemplateRef<any>)
// TODO(atscott): Consider adding an `ExpressionIdentifier` to tag variable declaration
// initializers as invalid for symbol retrieval.
const originalDeclaration = ts.isParenthesizedExpression(node.initializer) &&
ts.isAsExpression(node.initializer.expression) ?
this.getTypeChecker().getSymbolAtLocation(node.name) :
this.getTypeChecker().getSymbolAtLocation(node.initializer);
if (originalDeclaration === undefined || originalDeclaration.valueDeclaration === undefined) {
return null;
}
const symbol = this.getSymbolOfTsNode(originalDeclaration.valueDeclaration);
if (symbol === null || symbol.tsSymbol === null) {
return null;
}
const referenceVarTcbLocation: TcbLocation = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: this.getTcbPositionForNode(node),
};
if (target instanceof TmplAstTemplate || target instanceof TmplAstElement) {
return {
kind: SymbolKind.Reference,
tsSymbol: symbol.tsSymbol,
tsType: symbol.tsType,
target,
declaration: ref,
targetLocation: symbol.tcbLocation,
referenceVarLocation: referenceVarTcbLocation,
};
} else {
if (!ts.isClassDeclaration(target.directive.ref.node)) {
return null;
}
return {
kind: SymbolKind.Reference,
tsSymbol: symbol.tsSymbol,
tsType: symbol.tsType,
declaration: ref,
target: target.directive.ref.node,
targetLocation: symbol.tcbLocation,
referenceVarLocation: referenceVarTcbLocation,
};
}
}
private getSymbolOfPipe(expression: BindingPipe): PipeSymbol|null {
const methodAccess = findFirstMatchingNode(
this.typeCheckBlock,
{withSpan: expression.nameSpan, filter: ts.isPropertyAccessExpression});
if (methodAccess === null) {
return null;
}
const pipeVariableNode = methodAccess.expression;
const pipeDeclaration = this.getTypeChecker().getSymbolAtLocation(pipeVariableNode);
if (pipeDeclaration === undefined || pipeDeclaration.valueDeclaration === undefined) {
return null;
}
const pipeInstance = this.getSymbolOfTsNode(pipeDeclaration.valueDeclaration);
// The instance should never be null, nor should the symbol lack a value declaration. This
// is because the node used to look for the `pipeInstance` symbol info is a value
// declaration of another symbol (i.e. the `pipeDeclaration` symbol).
if (pipeInstance === null || !isSymbolWithValueDeclaration(pipeInstance.tsSymbol)) {
return null;
}
const symbolInfo = this.getSymbolOfTsNode(methodAccess);
if (symbolInfo === null) {
return null;
}
return {
kind: SymbolKind.Pipe,
...symbolInfo,
classSymbol: {
...pipeInstance,
tsSymbol: pipeInstance.tsSymbol,
},
};
}
private getSymbolOfTemplateExpression(expression: AST): VariableSymbol|ReferenceSymbol
|ExpressionSymbol|null {
if (expression instanceof ASTWithSource) {
expression = expression.ast;
}
const expressionTarget = this.templateData.boundTarget.getExpressionTarget(expression);
if (expressionTarget !== null) {
return this.getSymbol(expressionTarget);
}
let withSpan = expression.sourceSpan;
// The `name` part of a `PropertyWrite` and a non-safe `Call` does not have its own
// AST so there is no way to retrieve a `Symbol` for just the `name` via a specific node.
if (expression instanceof PropertyWrite) {
withSpan = expression.nameSpan;
}
let node: ts.Node|null = null;
// Property reads in templates usually map to a `PropertyAccessExpression`
// (e.g. `ctx.foo`) so try looking for one first.
if (expression instanceof PropertyRead) {
node = findFirstMatchingNode(
this.typeCheckBlock, {withSpan, filter: ts.isPropertyAccessExpression});
}
// Otherwise fall back to searching for any AST node.
if (node === null) {
node = findFirstMatchingNode(this.typeCheckBlock, {withSpan, filter: anyNodeFilter});
}
if (node === null) {
return null;
}
while (ts.isParenthesizedExpression(node)) {
node = node.expression;
}
// - If we have safe property read ("a?.b") we want to get the Symbol for b, the `whenTrue`
// expression.
// - If our expression is a pipe binding ("a | test:b:c"), we want the Symbol for the
// `transform` on the pipe.
// - Otherwise, we retrieve the symbol for the node itself with no special considerations
if (expression instanceof SafePropertyRead && ts.isConditionalExpression(node)) {
const whenTrueSymbol = this.getSymbolOfTsNode(node.whenTrue);
if (whenTrueSymbol === null) {
return null;
}
return {
...whenTrueSymbol,
kind: SymbolKind.Expression,
// Rather than using the type of only the `whenTrue` part of the expression, we should
// still get the type of the whole conditional expression to include `|undefined`.
tsType: this.getTypeChecker().getTypeAtLocation(node)
};
} else {
const symbolInfo = this.getSymbolOfTsNode(node);
return symbolInfo === null ? null : {...symbolInfo, kind: SymbolKind.Expression};
}
}
private getSymbolOfTsNode(node: ts.Node): TsNodeSymbolInfo|null {
while (ts.isParenthesizedExpression(node)) {
node = node.expression;
}
let tsSymbol: ts.Symbol|undefined;
if (ts.isPropertyAccessExpression(node)) {
tsSymbol = this.getTypeChecker().getSymbolAtLocation(node.name);
} else {
tsSymbol = this.getTypeChecker().getSymbolAtLocation(node);
}
const positionInFile = this.getTcbPositionForNode(node);
const type = this.getTypeChecker().getTypeAtLocation(node);
return {
// If we could not find a symbol, fall back to the symbol on the type for the node.
// Some nodes won't have a "symbol at location" but will have a symbol for the type.
// Examples of this would be literals and `document.createElement('div')`.
tsSymbol: tsSymbol ?? type.symbol ?? null,
tsType: type,
tcbLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile,
},
};
}
private getTcbPositionForNode(node: ts.Node): number {
if (ts.isTypeReferenceNode(node)) {
return this.getTcbPositionForNode(node.typeName);
} else if (ts.isQualifiedName(node)) {
return node.right.getStart();
} else if (ts.isPropertyAccessExpression(node)) {
return node.name.getStart();
} else if (ts.isElementAccessExpression(node)) {
return node.argumentExpression.getStart();
} else {
return node.getStart();
}
}
}
/** Filter predicate function that matches any AST node. */
function anyNodeFilter(n: ts.Node): n is ts.Node {
return true;
}
function sourceSpanEqual(a: ParseSourceSpan, b: ParseSourceSpan) {
return a.start.offset === b.start.offset && a.end.offset === b.end.offset;
}
function unwrapSignalInputWriteTAccessor(expr: ts.LeftHandSideExpression): (null|{
fieldExpr: ts.ElementAccessExpression | ts.PropertyAccessExpression,
typeExpr: ts.ElementAccessExpression
}) {
// e.g. `_t2.inputA[i2.ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]`
// 1. Assert that we are dealing with an element access expression.
// 2. Assert that we are dealing with a signal brand symbol access in the argument expression.
if (!ts.isElementAccessExpression(expr) ||
!ts.isPropertyAccessExpression(expr.argumentExpression)) {
return null;
}
// Assert that the property access in the element access is a simple identifier and
// refers to `ɵINPUT_SIGNAL_BRAND_WRITE_TYPE`.
if (!ts.isIdentifier(expr.argumentExpression.name) ||
expr.argumentExpression.name.text !== R3Identifiers.InputSignalBrandWriteType.name) {
return null;
}
// Assert that the `_t2.inputA` is actually either a keyed element access, or
// property access expression. This is checked for type safety and to catch unexpected cases.
if (!ts.isPropertyAccessExpression(expr.expression) &&
!ts.isElementAccessExpression(expr.expression)) {
throw new Error('Unexpected expression for signal input write type.');
}
return {
fieldExpr: expr.expression,
typeExpr: expr,
};
}