forked from angular/angular
/
type_check_block.ts
2637 lines (2326 loc) · 106 KB
/
type_check_block.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
/**
* @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, BindingPipe, BindingType, BoundTarget, Call, createCssSelectorFromNode, CssSelector, DYNAMIC_TYPE, ImplicitReceiver, ParsedEventType, ParseSourceSpan, PropertyRead, PropertyWrite, SafeCall, SafePropertyRead, SchemaMetadata, SelectorMatcher, ThisReceiver, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstDeferredBlock, TmplAstDeferredBlockTriggers, TmplAstElement, TmplAstForLoopBlock, TmplAstHoverDeferredTrigger, TmplAstIcu, TmplAstIfBlock, TmplAstIfBlockBranch, TmplAstInteractionDeferredTrigger, TmplAstNode, TmplAstReference, TmplAstSwitchBlock, TmplAstSwitchBlockCase, TmplAstTemplate, TmplAstText, TmplAstTextAttribute, TmplAstVariable, TmplAstViewportDeferredTrigger, TransplantedType} from '@angular/compiler';
import ts from 'typescript';
import {Reference} from '../../imports';
import {BindingPropertyName, ClassPropertyName} from '../../metadata';
import {ClassDeclaration} from '../../reflection';
import {TemplateId, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata} from '../api';
import {addExpressionIdentifier, ExpressionIdentifier, markIgnoreDiagnostics} from './comments';
import {addParseSpanInfo, addTemplateId, wrapForDiagnostics, wrapForTypeChecker} from './diagnostics';
import {DomSchemaChecker} from './dom';
import {Environment} from './environment';
import {astToTypescript, NULL_AS_ANY} from './expression';
import {OutOfBandDiagnosticRecorder} from './oob';
import {ExpressionSemanticVisitor} from './template_semantics';
import {tsCallMethod, tsCastToAny, tsCreateElement, tsCreateTypeQueryForCoercedInput, tsCreateVariable, tsDeclareVariable} from './ts_util';
import {requiresInlineTypeCtor} from './type_constructor';
import {TypeParameterEmitter} from './type_parameter_emitter';
/**
* Controls how generics for the component context class will be handled during TCB generation.
*/
export enum TcbGenericContextBehavior {
/**
* References to generic parameter bounds will be emitted via the `TypeParameterEmitter`.
*
* The caller must verify that all parameter bounds are emittable in order to use this mode.
*/
UseEmitter,
/**
* Generic parameter declarations will be copied directly from the `ts.ClassDeclaration` of the
* component class.
*
* The caller must only use the generated TCB code in a context where such copies will still be
* valid, such as an inline type check block.
*/
CopyClassNodes,
/**
* Any generic parameters for the component context class will be set to `any`.
*
* Produces a less useful type, but is always safe to use.
*/
FallbackToAny,
}
/**
* Given a `ts.ClassDeclaration` for a component, and metadata regarding that component, compose a
* "type check block" function.
*
* When passed through TypeScript's TypeChecker, type errors that arise within the type check block
* function indicate issues in the template itself.
*
* As a side effect of generating a TCB for the component, `ts.Diagnostic`s may also be produced
* directly for issues within the template which are identified during generation. These issues are
* recorded in either the `domSchemaChecker` (which checks usage of DOM elements and bindings) as
* well as the `oobRecorder` (which records errors when the type-checking code generator is unable
* to sufficiently understand a template).
*
* @param env an `Environment` into which type-checking code will be generated.
* @param ref a `Reference` to the component class which should be type-checked.
* @param name a `ts.Identifier` to use for the generated `ts.FunctionDeclaration`.
* @param meta metadata about the component's template and the function being generated.
* @param domSchemaChecker used to check and record errors regarding improper usage of DOM elements
* and bindings.
* @param oobRecorder used to record errors regarding template elements which could not be correctly
* translated into types during TCB generation.
* @param genericContextBehavior controls how generic parameters (especially parameters with generic
* bounds) will be referenced from the generated TCB code.
*/
export function generateTypeCheckBlock(
env: Environment, ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, name: ts.Identifier,
meta: TypeCheckBlockMetadata, domSchemaChecker: DomSchemaChecker,
oobRecorder: OutOfBandDiagnosticRecorder,
genericContextBehavior: TcbGenericContextBehavior): ts.FunctionDeclaration {
const tcb = new Context(
env, domSchemaChecker, oobRecorder, meta.id, meta.boundTarget, meta.pipes, meta.schemas,
meta.isStandalone, meta.preserveWhitespaces);
const scope = Scope.forNodes(tcb, null, null, tcb.boundTarget.target.template!, /* guard */ null);
const ctxRawType = env.referenceType(ref);
if (!ts.isTypeReferenceNode(ctxRawType)) {
throw new Error(
`Expected TypeReferenceNode when referencing the ctx param for ${ref.debugName}`);
}
let typeParameters: ts.TypeParameterDeclaration[]|undefined = undefined;
let typeArguments: ts.TypeNode[]|undefined = undefined;
if (ref.node.typeParameters !== undefined) {
if (!env.config.useContextGenericType) {
genericContextBehavior = TcbGenericContextBehavior.FallbackToAny;
}
switch (genericContextBehavior) {
case TcbGenericContextBehavior.UseEmitter:
// Guaranteed to emit type parameters since we checked that the class has them above.
typeParameters = new TypeParameterEmitter(ref.node.typeParameters, env.reflector)
.emit(typeRef => env.referenceType(typeRef))!;
typeArguments = typeParameters.map(param => ts.factory.createTypeReferenceNode(param.name));
break;
case TcbGenericContextBehavior.CopyClassNodes:
typeParameters = [...ref.node.typeParameters];
typeArguments = typeParameters.map(param => ts.factory.createTypeReferenceNode(param.name));
break;
case TcbGenericContextBehavior.FallbackToAny:
typeArguments = ref.node.typeParameters.map(
() => ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword));
break;
}
}
const paramList = [tcbThisParam(ctxRawType.typeName, typeArguments)];
const scopeStatements = scope.render();
const innerBody = ts.factory.createBlock([
...env.getPreludeStatements(),
...scopeStatements,
]);
// Wrap the body in an "if (true)" expression. This is unnecessary but has the effect of causing
// the `ts.Printer` to format the type-check block nicely.
const body = ts.factory.createBlock(
[ts.factory.createIfStatement(ts.factory.createTrue(), innerBody, undefined)]);
const fnDecl = ts.factory.createFunctionDeclaration(
/* modifiers */ undefined,
/* asteriskToken */ undefined,
/* name */ name,
/* typeParameters */ env.config.useContextGenericType ? typeParameters : undefined,
/* parameters */ paramList,
/* type */ undefined,
/* body */ body);
addTemplateId(fnDecl, meta.id);
return fnDecl;
}
/**
* A code generation operation that's involved in the construction of a Type Check Block.
*
* The generation of a TCB is non-linear. Bindings within a template may result in the need to
* construct certain types earlier than they otherwise would be constructed. That is, if the
* generation of a TCB for a template is broken down into specific operations (constructing a
* directive, extracting a variable from a let- operation, etc), then it's possible for operations
* earlier in the sequence to depend on operations which occur later in the sequence.
*
* `TcbOp` abstracts the different types of operations which are required to convert a template into
* a TCB. This allows for two phases of processing for the template, where 1) a linear sequence of
* `TcbOp`s is generated, and then 2) these operations are executed, not necessarily in linear
* order.
*
* Each `TcbOp` may insert statements into the body of the TCB, and also optionally return a
* `ts.Expression` which can be used to reference the operation's result.
*/
abstract class TcbOp {
/**
* Set to true if this operation can be considered optional. Optional operations are only executed
* when depended upon by other operations, otherwise they are disregarded. This allows for less
* code to generate, parse and type-check, overall positively contributing to performance.
*/
abstract readonly optional: boolean;
abstract execute(): ts.Expression|null;
/**
* Replacement value or operation used while this `TcbOp` is executing (i.e. to resolve circular
* references during its execution).
*
* This is usually a `null!` expression (which asks TS to infer an appropriate type), but another
* `TcbOp` can be returned in cases where additional code generation is necessary to deal with
* circular references.
*/
circularFallback(): TcbOp|ts.Expression {
return INFER_TYPE_FOR_CIRCULAR_OP_EXPR;
}
}
/**
* A `TcbOp` which creates an expression for a native DOM element (or web component) from a
* `TmplAstElement`.
*
* Executing this operation returns a reference to the element variable.
*/
class TcbElementOp extends TcbOp {
constructor(private tcb: Context, private scope: Scope, private element: TmplAstElement) {
super();
}
override get optional() {
// The statement generated by this operation is only used for type-inference of the DOM
// element's type and won't report diagnostics by itself, so the operation is marked as optional
// to avoid generating statements for DOM elements that are never referenced.
return true;
}
override execute(): ts.Identifier {
const id = this.tcb.allocateId();
// Add the declaration of the element using document.createElement.
const initializer = tsCreateElement(this.element.name);
addParseSpanInfo(initializer, this.element.startSourceSpan || this.element.sourceSpan);
this.scope.addStatement(tsCreateVariable(id, initializer));
return id;
}
}
/**
* A `TcbOp` which creates an expression for particular let- `TmplAstVariable` on a
* `TmplAstTemplate`'s context.
*
* Executing this operation returns a reference to the variable variable (lol).
*/
class TcbTemplateVariableOp extends TcbOp {
constructor(
private tcb: Context, private scope: Scope, private template: TmplAstTemplate,
private variable: TmplAstVariable) {
super();
}
override get optional() {
return false;
}
override execute(): ts.Identifier {
// Look for a context variable for the template.
const ctx = this.scope.resolve(this.template);
// Allocate an identifier for the TmplAstVariable, and initialize it to a read of the variable
// on the template context.
const id = this.tcb.allocateId();
const initializer = ts.factory.createPropertyAccessExpression(
/* expression */ ctx,
/* name */ this.variable.value || '$implicit');
addParseSpanInfo(id, this.variable.keySpan);
// Declare the variable, and return its identifier.
let variable: ts.VariableStatement;
if (this.variable.valueSpan !== undefined) {
addParseSpanInfo(initializer, this.variable.valueSpan);
variable = tsCreateVariable(id, wrapForTypeChecker(initializer));
} else {
variable = tsCreateVariable(id, initializer);
}
addParseSpanInfo(variable.declarationList.declarations[0], this.variable.sourceSpan);
this.scope.addStatement(variable);
return id;
}
}
/**
* A `TcbOp` which generates a variable for a `TmplAstTemplate`'s context.
*
* Executing this operation returns a reference to the template's context variable.
*/
class TcbTemplateContextOp extends TcbOp {
constructor(private tcb: Context, private scope: Scope) {
super();
}
// The declaration of the context variable is only needed when the context is actually referenced.
override readonly optional = true;
override execute(): ts.Identifier {
// Allocate a template ctx variable and declare it with an 'any' type. The type of this variable
// may be narrowed as a result of template guard conditions.
const ctx = this.tcb.allocateId();
const type = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);
this.scope.addStatement(tsDeclareVariable(ctx, type));
return ctx;
}
}
/**
* A `TcbOp` which descends into a `TmplAstTemplate`'s children and generates type-checking code for
* them.
*
* This operation wraps the children's type-checking code in an `if` block, which may include one
* or more type guard conditions that narrow types within the template body.
*/
class TcbTemplateBodyOp extends TcbOp {
constructor(private tcb: Context, private scope: Scope, private template: TmplAstTemplate) {
super();
}
override get optional() {
return false;
}
override execute(): null {
// An `if` will be constructed, within which the template's children will be type checked. The
// `if` is used for two reasons: it creates a new syntactic scope, isolating variables declared
// in the template's TCB from the outer context, and it allows any directives on the templates
// to perform type narrowing of either expressions or the template's context.
//
// The guard is the `if` block's condition. It's usually set to `true` but directives that exist
// on the template can trigger extra guard expressions that serve to narrow types within the
// `if`. `guard` is calculated by starting with `true` and adding other conditions as needed.
// Collect these into `guards` by processing the directives.
const directiveGuards: ts.Expression[] = [];
const directives = this.tcb.boundTarget.getDirectivesOfNode(this.template);
if (directives !== null) {
for (const dir of directives) {
const dirInstId = this.scope.resolve(this.template, dir);
const dirId =
this.tcb.env.reference(dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>);
// There are two kinds of guards. Template guards (ngTemplateGuards) allow type narrowing of
// the expression passed to an @Input of the directive. Scan the directive to see if it has
// any template guards, and generate them if needed.
dir.ngTemplateGuards.forEach(guard => {
// For each template guard function on the directive, look for a binding to that input.
const boundInput = this.template.inputs.find(i => i.name === guard.inputName) ||
this.template.templateAttrs.find(
(i: TmplAstTextAttribute|TmplAstBoundAttribute): i is TmplAstBoundAttribute =>
i instanceof TmplAstBoundAttribute && i.name === guard.inputName);
if (boundInput !== undefined) {
// If there is such a binding, generate an expression for it.
const expr = tcbExpression(boundInput.value, this.tcb, this.scope);
// The expression has already been checked in the type constructor invocation, so
// it should be ignored when used within a template guard.
markIgnoreDiagnostics(expr);
if (guard.type === 'binding') {
// Use the binding expression itself as guard.
directiveGuards.push(expr);
} else {
// Call the guard function on the directive with the directive instance and that
// expression.
const guardInvoke = tsCallMethod(dirId, `ngTemplateGuard_${guard.inputName}`, [
dirInstId,
expr,
]);
addParseSpanInfo(guardInvoke, boundInput.value.sourceSpan);
directiveGuards.push(guardInvoke);
}
}
});
// The second kind of guard is a template context guard. This guard narrows the template
// rendering context variable `ctx`.
if (dir.hasNgTemplateContextGuard) {
if (this.tcb.env.config.applyTemplateContextGuards) {
const ctx = this.scope.resolve(this.template);
const guardInvoke = tsCallMethod(dirId, 'ngTemplateContextGuard', [dirInstId, ctx]);
addParseSpanInfo(guardInvoke, this.template.sourceSpan);
directiveGuards.push(guardInvoke);
} else if (
this.template.variables.length > 0 &&
this.tcb.env.config.suggestionsForSuboptimalTypeInference) {
// The compiler could have inferred a better type for the variables in this template,
// but was prevented from doing so by the type-checking configuration. Issue a warning
// diagnostic.
this.tcb.oobRecorder.suboptimalTypeInference(this.tcb.id, this.template.variables);
}
}
}
}
// By default the guard is simply `true`.
let guard: ts.Expression|null = null;
// If there are any guards from directives, use them instead.
if (directiveGuards.length > 0) {
// Pop the first value and use it as the initializer to reduce(). This way, a single guard
// will be used on its own, but two or more will be combined into binary AND expressions.
guard = directiveGuards.reduce(
(expr, dirGuard) => ts.factory.createBinaryExpression(
expr, ts.SyntaxKind.AmpersandAmpersandToken, dirGuard),
directiveGuards.pop()!);
}
// Create a new Scope for the template. This constructs the list of operations for the template
// children, as well as tracks bindings within the template.
const tmplScope =
Scope.forNodes(this.tcb, this.scope, this.template, this.template.children, guard);
// Render the template's `Scope` into its statements.
const statements = tmplScope.render();
if (statements.length === 0) {
// As an optimization, don't generate the scope's block if it has no statements. This is
// beneficial for templates that contain for example `<span *ngIf="first"></span>`, in which
// case there's no need to render the `NgIf` guard expression. This seems like a minor
// improvement, however it reduces the number of flow-node antecedents that TypeScript needs
// to keep into account for such cases, resulting in an overall reduction of
// type-checking time.
return null;
}
let tmplBlock: ts.Statement = ts.factory.createBlock(statements);
if (guard !== null) {
// The scope has a guard that needs to be applied, so wrap the template block into an `if`
// statement containing the guard expression.
tmplBlock =
ts.factory.createIfStatement(/* expression */ guard, /* thenStatement */ tmplBlock);
}
this.scope.addStatement(tmplBlock);
return null;
}
}
/**
* A `TcbOp` which renders an Angular expression (e.g. `{{foo() && bar.baz}}`).
*
* Executing this operation returns nothing.
*/
class TcbExpressionOp extends TcbOp {
constructor(private tcb: Context, private scope: Scope, private expression: AST) {
super();
}
override get optional() {
return false;
}
override execute(): null {
const expr = tcbExpression(this.expression, this.tcb, this.scope);
this.scope.addStatement(ts.factory.createExpressionStatement(expr));
return null;
}
}
/**
* A `TcbOp` which constructs an instance of a directive. For generic directives, generic
* parameters are set to `any` type.
*/
abstract class TcbDirectiveTypeOpBase extends TcbOp {
constructor(
protected tcb: Context, protected scope: Scope,
protected node: TmplAstTemplate|TmplAstElement, protected dir: TypeCheckableDirectiveMeta) {
super();
}
override get optional() {
// The statement generated by this operation is only used to declare the directive's type and
// won't report diagnostics by itself, so the operation is marked as optional to avoid
// generating declarations for directives that don't have any inputs/outputs.
return true;
}
override execute(): ts.Identifier {
const dirRef = this.dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>;
const rawType = this.tcb.env.referenceType(this.dir.ref);
let type: ts.TypeNode;
if (this.dir.isGeneric === false || dirRef.node.typeParameters === undefined) {
type = rawType;
} else {
if (!ts.isTypeReferenceNode(rawType)) {
throw new Error(
`Expected TypeReferenceNode when referencing the type for ${this.dir.ref.debugName}`);
}
const typeArguments = dirRef.node.typeParameters.map(
() => ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword));
type = ts.factory.createTypeReferenceNode(rawType.typeName, typeArguments);
}
const id = this.tcb.allocateId();
addExpressionIdentifier(type, ExpressionIdentifier.DIRECTIVE);
addParseSpanInfo(type, this.node.startSourceSpan || this.node.sourceSpan);
this.scope.addStatement(tsDeclareVariable(id, type));
return id;
}
}
/**
* A `TcbOp` which constructs an instance of a non-generic directive _without_ setting any of its
* inputs. Inputs are later set in the `TcbDirectiveInputsOp`. Type checking was found to be
* faster when done in this way as opposed to `TcbDirectiveCtorOp` which is only necessary when the
* directive is generic.
*
* Executing this operation returns a reference to the directive instance variable with its inferred
* type.
*/
class TcbNonGenericDirectiveTypeOp extends TcbDirectiveTypeOpBase {
/**
* Creates a variable declaration for this op's directive of the argument type. Returns the id of
* the newly created variable.
*/
override execute(): ts.Identifier {
const dirRef = this.dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>;
if (this.dir.isGeneric) {
throw new Error(`Assertion Error: expected ${dirRef.debugName} not to be generic.`);
}
return super.execute();
}
}
/**
* A `TcbOp` which constructs an instance of a generic directive with its generic parameters set
* to `any` type. This op is like `TcbDirectiveTypeOp`, except that generic parameters are set to
* `any` type. This is used for situations where we want to avoid inlining.
*
* Executing this operation returns a reference to the directive instance variable with its generic
* type parameters set to `any`.
*/
class TcbGenericDirectiveTypeWithAnyParamsOp extends TcbDirectiveTypeOpBase {
override execute(): ts.Identifier {
const dirRef = this.dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>;
if (dirRef.node.typeParameters === undefined) {
throw new Error(`Assertion Error: expected typeParameters when creating a declaration for ${
dirRef.debugName}`);
}
return super.execute();
}
}
/**
* A `TcbOp` which creates a variable for a local ref in a template.
* The initializer for the variable is the variable expression for the directive, template, or
* element the ref refers to. When the reference is used in the template, those TCB statements will
* access this variable as well. For example:
* ```
* var _t1 = document.createElement('div');
* var _t2 = _t1;
* _t2.value
* ```
* This operation supports more fluent lookups for the `TemplateTypeChecker` when getting a symbol
* for a reference. In most cases, this isn't essential; that is, the information for the symbol
* could be gathered without this operation using the `BoundTarget`. However, for the case of
* ng-template references, we will need this reference variable to not only provide a location in
* the shim file, but also to narrow the variable to the correct `TemplateRef<T>` type rather than
* `TemplateRef<any>` (this work is still TODO).
*
* Executing this operation returns a reference to the directive instance variable with its inferred
* type.
*/
class TcbReferenceOp extends TcbOp {
constructor(
private readonly tcb: Context, private readonly scope: Scope,
private readonly node: TmplAstReference,
private readonly host: TmplAstElement|TmplAstTemplate,
private readonly target: TypeCheckableDirectiveMeta|TmplAstTemplate|TmplAstElement) {
super();
}
// The statement generated by this operation is only used to for the Type Checker
// so it can map a reference variable in the template directly to a node in the TCB.
override readonly optional = true;
override execute(): ts.Identifier {
const id = this.tcb.allocateId();
let initializer: ts.Expression =
this.target instanceof TmplAstTemplate || this.target instanceof TmplAstElement ?
this.scope.resolve(this.target) :
this.scope.resolve(this.host, this.target);
// The reference is either to an element, an <ng-template> node, or to a directive on an
// element or template.
if ((this.target instanceof TmplAstElement && !this.tcb.env.config.checkTypeOfDomReferences) ||
!this.tcb.env.config.checkTypeOfNonDomReferences) {
// References to DOM nodes are pinned to 'any' when `checkTypeOfDomReferences` is `false`.
// References to `TemplateRef`s and directives are pinned to 'any' when
// `checkTypeOfNonDomReferences` is `false`.
initializer = ts.factory.createAsExpression(
initializer, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword));
} else if (this.target instanceof TmplAstTemplate) {
// Direct references to an <ng-template> node simply require a value of type
// `TemplateRef<any>`. To get this, an expression of the form
// `(_t1 as any as TemplateRef<any>)` is constructed.
initializer = ts.factory.createAsExpression(
initializer, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword));
initializer = ts.factory.createAsExpression(
initializer,
this.tcb.env.referenceExternalType('@angular/core', 'TemplateRef', [DYNAMIC_TYPE]));
initializer = ts.factory.createParenthesizedExpression(initializer);
}
addParseSpanInfo(initializer, this.node.sourceSpan);
addParseSpanInfo(id, this.node.keySpan);
this.scope.addStatement(tsCreateVariable(id, initializer));
return id;
}
}
/**
* A `TcbOp` which is used when the target of a reference is missing. This operation generates a
* variable of type any for usages of the invalid reference to resolve to. The invalid reference
* itself is recorded out-of-band.
*/
class TcbInvalidReferenceOp extends TcbOp {
constructor(private readonly tcb: Context, private readonly scope: Scope) {
super();
}
// The declaration of a missing reference is only needed when the reference is resolved.
override readonly optional = true;
override execute(): ts.Identifier {
const id = this.tcb.allocateId();
this.scope.addStatement(tsCreateVariable(id, NULL_AS_ANY));
return id;
}
}
/**
* A `TcbOp` which constructs an instance of a directive with types inferred from its inputs. The
* inputs themselves are not checked here; checking of inputs is achieved in `TcbDirectiveInputsOp`.
* Any errors reported in this statement are ignored, as the type constructor call is only present
* for type-inference.
*
* When a Directive is generic, it is required that the TCB generates the instance using this method
* in order to infer the type information correctly.
*
* Executing this operation returns a reference to the directive instance variable with its inferred
* type.
*/
class TcbDirectiveCtorOp extends TcbOp {
constructor(
private tcb: Context, private scope: Scope, private node: TmplAstTemplate|TmplAstElement,
private dir: TypeCheckableDirectiveMeta) {
super();
}
override get optional() {
// The statement generated by this operation is only used to infer the directive's type and
// won't report diagnostics by itself, so the operation is marked as optional.
return true;
}
override execute(): ts.Identifier {
const id = this.tcb.allocateId();
addExpressionIdentifier(id, ExpressionIdentifier.DIRECTIVE);
addParseSpanInfo(id, this.node.startSourceSpan || this.node.sourceSpan);
const genericInputs = new Map<string, TcbDirectiveInput>();
const boundAttrs = getBoundAttributes(this.dir, this.node);
for (const attr of boundAttrs) {
// Skip text attributes if configured to do so.
if (!this.tcb.env.config.checkTypeOfAttributes &&
attr.attribute instanceof TmplAstTextAttribute) {
continue;
}
for (const {fieldName} of attr.inputs) {
// Skip the field if an attribute has already been bound to it; we can't have a duplicate
// key in the type constructor call.
if (genericInputs.has(fieldName)) {
continue;
}
const expression = translateInput(attr.attribute, this.tcb, this.scope);
genericInputs.set(
fieldName,
{type: 'binding', field: fieldName, expression, sourceSpan: attr.attribute.sourceSpan});
}
}
// Add unset directive inputs for each of the remaining unset fields.
for (const {classPropertyName} of this.dir.inputs) {
if (!genericInputs.has(classPropertyName)) {
genericInputs.set(classPropertyName, {type: 'unset', field: classPropertyName});
}
}
// Call the type constructor of the directive to infer a type, and assign the directive
// instance.
const typeCtor = tcbCallTypeCtor(this.dir, this.tcb, Array.from(genericInputs.values()));
markIgnoreDiagnostics(typeCtor);
this.scope.addStatement(tsCreateVariable(id, typeCtor));
return id;
}
override circularFallback(): TcbOp {
return new TcbDirectiveCtorCircularFallbackOp(this.tcb, this.scope, this.node, this.dir);
}
}
/**
* A `TcbOp` which generates code to check input bindings on an element that correspond with the
* members of a directive.
*
* Executing this operation returns nothing.
*/
class TcbDirectiveInputsOp extends TcbOp {
constructor(
private tcb: Context, private scope: Scope, private node: TmplAstTemplate|TmplAstElement,
private dir: TypeCheckableDirectiveMeta) {
super();
}
override get optional() {
return false;
}
override execute(): null {
let dirId: ts.Expression|null = null;
// TODO(joost): report duplicate properties
const boundAttrs = getBoundAttributes(this.dir, this.node);
const seenRequiredInputs = new Set<ClassPropertyName>();
for (const attr of boundAttrs) {
// For bound inputs, the property is assigned the binding expression.
const expr = widenBinding(translateInput(attr.attribute, this.tcb, this.scope), this.tcb);
let assignment: ts.Expression = wrapForDiagnostics(expr);
for (const {fieldName, required, transformType} of attr.inputs) {
let target: ts.LeftHandSideExpression;
if (required) {
seenRequiredInputs.add(fieldName);
}
if (this.dir.coercedInputFields.has(fieldName)) {
let type: ts.TypeNode;
if (transformType !== null) {
type = this.tcb.env.referenceTransplantedType(new TransplantedType(transformType));
} else {
// The input has a coercion declaration which should be used instead of assigning the
// expression into the input field directly. To achieve this, a variable is declared
// with a type of `typeof Directive.ngAcceptInputType_fieldName` which is then used as
// target of the assignment.
const dirTypeRef: ts.TypeNode = this.tcb.env.referenceType(this.dir.ref);
if (!ts.isTypeReferenceNode(dirTypeRef)) {
throw new Error(
`Expected TypeReferenceNode from reference to ${this.dir.ref.debugName}`);
}
type = tsCreateTypeQueryForCoercedInput(dirTypeRef.typeName, fieldName);
}
const id = this.tcb.allocateId();
this.scope.addStatement(tsDeclareVariable(id, type));
target = id;
} else if (this.dir.undeclaredInputFields.has(fieldName)) {
// If no coercion declaration is present nor is the field declared (i.e. the input is
// declared in a `@Directive` or `@Component` decorator's `inputs` property) there is no
// assignment target available, so this field is skipped.
continue;
} else if (
!this.tcb.env.config.honorAccessModifiersForInputBindings &&
this.dir.restrictedInputFields.has(fieldName)) {
// If strict checking of access modifiers is disabled and the field is restricted
// (i.e. private/protected/readonly), generate an assignment into a temporary variable
// that has the type of the field. This achieves type-checking but circumvents the access
// modifiers.
if (dirId === null) {
dirId = this.scope.resolve(this.node, this.dir);
}
const id = this.tcb.allocateId();
const dirTypeRef = this.tcb.env.referenceType(this.dir.ref);
if (!ts.isTypeReferenceNode(dirTypeRef)) {
throw new Error(
`Expected TypeReferenceNode from reference to ${this.dir.ref.debugName}`);
}
const type = ts.factory.createIndexedAccessTypeNode(
ts.factory.createTypeQueryNode(dirId as ts.Identifier),
ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(fieldName)));
const temp = tsDeclareVariable(id, type);
this.scope.addStatement(temp);
target = id;
} else {
if (dirId === null) {
dirId = this.scope.resolve(this.node, this.dir);
}
// To get errors assign directly to the fields on the instance, using property access
// when possible. String literal fields may not be valid JS identifiers so we use
// literal element access instead for those cases.
target = this.dir.stringLiteralInputFields.has(fieldName) ?
ts.factory.createElementAccessExpression(
dirId, ts.factory.createStringLiteral(fieldName)) :
ts.factory.createPropertyAccessExpression(
dirId, ts.factory.createIdentifier(fieldName));
}
if (attr.attribute.keySpan !== undefined) {
addParseSpanInfo(target, attr.attribute.keySpan);
}
// Finally the assignment is extended by assigning it into the target expression.
assignment =
ts.factory.createBinaryExpression(target, ts.SyntaxKind.EqualsToken, assignment);
}
addParseSpanInfo(assignment, attr.attribute.sourceSpan);
// Ignore diagnostics for text attributes if configured to do so.
if (!this.tcb.env.config.checkTypeOfAttributes &&
attr.attribute instanceof TmplAstTextAttribute) {
markIgnoreDiagnostics(assignment);
}
this.scope.addStatement(ts.factory.createExpressionStatement(assignment));
}
this.checkRequiredInputs(seenRequiredInputs);
return null;
}
private checkRequiredInputs(seenRequiredInputs: Set<ClassPropertyName>): void {
const missing: BindingPropertyName[] = [];
for (const input of this.dir.inputs) {
if (input.required && !seenRequiredInputs.has(input.classPropertyName)) {
missing.push(input.bindingPropertyName);
}
}
if (missing.length > 0) {
this.tcb.oobRecorder.missingRequiredInputs(
this.tcb.id, this.node, this.dir.name, this.dir.isComponent, missing);
}
}
}
/**
* A `TcbOp` which is used to generate a fallback expression if the inference of a directive type
* via `TcbDirectiveCtorOp` requires a reference to its own type. This can happen using a template
* reference:
*
* ```html
* <some-cmp #ref [prop]="ref.foo"></some-cmp>
* ```
*
* In this case, `TcbDirectiveCtorCircularFallbackOp` will add a second inference of the directive
* type to the type-check block, this time calling the directive's type constructor without any
* input expressions. This infers the widest possible supertype for the directive, which is used to
* resolve any recursive references required to infer the real type.
*/
class TcbDirectiveCtorCircularFallbackOp extends TcbOp {
constructor(
private tcb: Context, private scope: Scope, private node: TmplAstTemplate|TmplAstElement,
private dir: TypeCheckableDirectiveMeta) {
super();
}
override get optional() {
return false;
}
override execute(): ts.Identifier {
const id = this.tcb.allocateId();
const typeCtor = this.tcb.env.typeCtorFor(this.dir);
const circularPlaceholder = ts.factory.createCallExpression(
typeCtor, /* typeArguments */ undefined,
[ts.factory.createNonNullExpression(ts.factory.createNull())]);
this.scope.addStatement(tsCreateVariable(id, circularPlaceholder));
return id;
}
}
/**
* A `TcbOp` which feeds elements and unclaimed properties to the `DomSchemaChecker`.
*
* The DOM schema is not checked via TCB code generation. Instead, the `DomSchemaChecker` ingests
* elements and property bindings and accumulates synthetic `ts.Diagnostic`s out-of-band. These are
* later merged with the diagnostics generated from the TCB.
*
* For convenience, the TCB iteration of the template is used to drive the `DomSchemaChecker` via
* the `TcbDomSchemaCheckerOp`.
*/
class TcbDomSchemaCheckerOp extends TcbOp {
constructor(
private tcb: Context, private element: TmplAstElement, private checkElement: boolean,
private claimedInputs: Set<string>) {
super();
}
override get optional() {
return false;
}
override execute(): ts.Expression|null {
if (this.checkElement) {
this.tcb.domSchemaChecker.checkElement(
this.tcb.id, this.element, this.tcb.schemas, this.tcb.hostIsStandalone);
}
// TODO(alxhub): this could be more efficient.
for (const binding of this.element.inputs) {
if (binding.type === BindingType.Property && this.claimedInputs.has(binding.name)) {
// Skip this binding as it was claimed by a directive.
continue;
}
if (binding.type === BindingType.Property) {
if (binding.name !== 'style' && binding.name !== 'class') {
// A direct binding to a property.
const propertyName = ATTR_TO_PROP.get(binding.name) ?? binding.name;
this.tcb.domSchemaChecker.checkProperty(
this.tcb.id, this.element, propertyName, binding.sourceSpan, this.tcb.schemas,
this.tcb.hostIsStandalone);
}
}
}
return null;
}
}
/**
* A `TcbOp` that finds and flags control flow nodes that interfere with content projection.
*
* Context:
* `@if` and `@for` try to emulate the content projection behavior of `*ngIf` and `*ngFor`
* in order to reduce breakages when moving from one syntax to the other (see #52414), however the
* approach only works if there's only one element at the root of the control flow expression.
* This means that a stray sibling node (e.g. text) can prevent an element from being projected
* into the right slot. The purpose of the `TcbOp` is to find any places where a node at the root
* of a control flow expression *would have been projected* into a specific slot, if the control
* flow node didn't exist.
*/
class TcbControlFlowContentProjectionOp extends TcbOp {
constructor(
private tcb: Context, private element: TmplAstElement, private ngContentSelectors: string[],
private componentName: string) {
super();
}
override readonly optional = false;
override execute(): null {
const controlFlowToCheck = this.findPotentialControlFlowNodes();
if (controlFlowToCheck.length > 0) {
const matcher = new SelectorMatcher<string>();
for (const selector of this.ngContentSelectors) {
// `*` is a special selector for the catch-all slot.
if (selector !== '*') {
matcher.addSelectables(CssSelector.parse(selector), selector);
}
}
for (const root of controlFlowToCheck) {
for (const child of root.children) {
if (child instanceof TmplAstElement || child instanceof TmplAstTemplate) {
matcher.match(createCssSelectorFromNode(child), (_, originalSelector) => {
this.tcb.oobRecorder.controlFlowPreventingContentProjection(
this.tcb.id, child, this.componentName, originalSelector, root,
this.tcb.hostPreserveWhitespaces);
});
}
}
}
}
return null;
}
private findPotentialControlFlowNodes() {
const result: Array<TmplAstIfBlockBranch|TmplAstForLoopBlock> = [];
for (const child of this.element.children) {
let eligibleNode: TmplAstForLoopBlock|TmplAstIfBlockBranch|null = null;
// Only `@for` blocks and the first branch of `@if` blocks participate in content projection.
if (child instanceof TmplAstForLoopBlock) {
eligibleNode = child;
} else if (child instanceof TmplAstIfBlock) {
eligibleNode = child.branches[0]; // @if blocks are guaranteed to have at least one branch.
}
// Skip nodes with less than two children since it's impossible
// for them to run into the issue that we're checking for.
if (eligibleNode === null || eligibleNode.children.length < 2) {
continue;
}
// Count the number of root nodes while skipping empty text where relevant.
const rootNodeCount = eligibleNode.children.reduce((count, node) => {
// Normally `preserveWhitspaces` would have been accounted for during parsing, however
// in `ngtsc/annotations/component/src/resources.ts#parseExtractedTemplate` we enable
// `preserveWhitespaces` to preserve the accuracy of source maps diagnostics. This means
// that we have to account for it here since the presence of text nodes affects the
// content projection behavior.
if (!(node instanceof TmplAstText) || this.tcb.hostPreserveWhitespaces ||
node.value.trim().length > 0) {
count++;
}
return count;
}, 0);
// Content projection can only be affected if there is more than one root node.
if (rootNodeCount > 1) {
result.push(eligibleNode);
}
}
return result;
}
}