forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
r3_view_compiler.ts
1332 lines (1147 loc) · 52 KB
/
r3_view_compiler.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 Inc. 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 {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeSummary, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata, CompileTypeSummary, flatten, identifierName, rendererTypeName, sanitizeIdentifier, tokenReference, viewClassName} from '../compile_metadata';
import {CompileReflector} from '../compile_reflector';
import {BindingForm, BuiltinConverter, BuiltinFunctionCall, ConvertPropertyBindingResult, EventHandlerVars, LocalResolver, convertActionBinding, convertPropertyBinding, convertPropertyBindingBuiltins} from '../compiler_util/expression_converter';
import {ConstantPool, DefinitionKind} from '../constant_pool';
import {InjectFlags} from '../core';
import {AST, AstMemoryEfficientTransformer, AstTransformer, BindingPipe, FunctionCall, ImplicitReceiver, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, ParseSpan, PropertyRead} from '../expression_parser/ast';
import {Identifiers} from '../identifiers';
import {LifecycleHooks} from '../lifecycle_reflector';
import * as o from '../output/output_ast';
import {ParseSourceSpan, typeSourceSpan} from '../parse_util';
import {CssSelector} from '../selector';
import {BindingParser} from '../template_parser/binding_parser';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, PropertyBindingType, ProviderAst, QueryMatch, RecursiveTemplateAstVisitor, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '../template_parser/template_ast';
import {OutputContext, error} from '../util';
import {Identifiers as R3} from './r3_identifiers';
import {BUILD_OPTIMIZER_COLOCATE, OutputMode} from './r3_types';
/** Name of the context parameter passed into a template function */
const CONTEXT_NAME = 'ctx';
/** Name of the RenderFlag passed into a template function */
const RENDER_FLAGS = 'rf';
/** Name of the temporary to use during data binding */
const TEMPORARY_NAME = '_t';
/** The prefix reference variables */
const REFERENCE_PREFIX = '_r';
/** The name of the implicit context reference */
const IMPLICIT_REFERENCE = '$implicit';
/** Name of the i18n attributes **/
const I18N_ATTR = 'i18n';
const I18N_ATTR_PREFIX = 'i18n-';
/** I18n separators for metadata **/
const MEANING_SEPARATOR = '|';
const ID_SEPARATOR = '@@';
export function compileDirective(
outputCtx: OutputContext, directive: CompileDirectiveMetadata, reflector: CompileReflector,
bindingParser: BindingParser, mode: OutputMode) {
const definitionMapValues: {key: string, quoted: boolean, value: o.Expression}[] = [];
const field = (key: string, value: o.Expression | null) => {
if (value) {
definitionMapValues.push({key, value, quoted: false});
}
};
// e.g. 'type: MyDirective`
field('type', outputCtx.importExpr(directive.type.reference));
// e.g. `selectors: [['', 'someDir', '']]`
field('selectors', createDirectiveSelector(directive.selector !));
// e.g. `factory: () => new MyApp(injectElementRef())`
field('factory', createFactory(directive.type, outputCtx, reflector, directive.queries));
// e.g. `hostBindings: (dirIndex, elIndex) => { ... }
field('hostBindings', createHostBindingsFunction(directive, outputCtx, bindingParser));
// e.g. `attributes: ['role', 'listbox']`
field('attributes', createHostAttributesArray(directive, outputCtx));
// e.g 'inputs: {a: 'a'}`
field('inputs', conditionallyCreateMapObjectLiteral(directive.inputs, outputCtx));
// e.g 'outputs: {a: 'a'}`
field('outputs', conditionallyCreateMapObjectLiteral(directive.outputs, outputCtx));
const className = identifierName(directive.type) !;
className || error(`Cannot resolver the name of ${directive.type}`);
const definitionField = outputCtx.constantPool.propertyNameOf(DefinitionKind.Directive);
const definitionFunction =
o.importExpr(R3.defineDirective).callFn([o.literalMap(definitionMapValues)]);
if (mode === OutputMode.PartialClass) {
// Create the partial class to be merged with the actual class.
outputCtx.statements.push(new o.ClassStmt(
/* name */ className,
/* parent */ null,
/* fields */[new o.ClassField(
/* name */ definitionField,
/* type */ o.INFERRED_TYPE,
/* modifiers */[o.StmtModifier.Static],
/* initializer */ definitionFunction)],
/* getters */[],
/* constructorMethod */ new o.ClassMethod(null, [], []),
/* methods */[]));
} else {
// Create back-patch definition.
const classReference = outputCtx.importExpr(directive.type.reference);
// Create the back-patch statement
outputCtx.statements.push(new o.CommentStmt(BUILD_OPTIMIZER_COLOCATE));
outputCtx.statements.push(
classReference.prop(definitionField).set(definitionFunction).toStmt());
}
}
export function compileComponent(
outputCtx: OutputContext, component: CompileDirectiveMetadata,
pipeSummaries: CompilePipeSummary[], template: TemplateAst[], reflector: CompileReflector,
bindingParser: BindingParser, mode: OutputMode) {
const definitionMapValues: {key: string, quoted: boolean, value: o.Expression}[] = [];
// Pipes and Directives found in the template
const pipes = new Set<any>();
const directives = new Set<any>();
const field = (key: string, value: o.Expression | null) => {
if (value) {
definitionMapValues.push({key, value, quoted: false});
}
};
// e.g. `type: MyApp`
field('type', outputCtx.importExpr(component.type.reference));
// e.g. `selectors: [['my-app']]`
field('selectors', createDirectiveSelector(component.selector !));
const selector = component.selector && CssSelector.parse(component.selector);
const firstSelector = selector && selector[0];
// e.g. `attr: ["class", ".my.app"]
// This is optional an only included if the first selector of a component specifies attributes.
if (firstSelector) {
const selectorAttributes = firstSelector.getAttrs();
if (selectorAttributes.length) {
field(
'attrs', outputCtx.constantPool.getConstLiteral(
o.literalArr(selectorAttributes.map(
value => value != null ? o.literal(value) : o.literal(undefined))),
/* forceShared */ true));
}
}
// e.g. `factory: function MyApp_Factory() { return new MyApp(injectElementRef()); }`
field('factory', createFactory(component.type, outputCtx, reflector, component.queries));
// e.g `hostBindings: function MyApp_HostBindings { ... }
field('hostBindings', createHostBindingsFunction(component, outputCtx, bindingParser));
// e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
const templateTypeName = component.type.reference.name;
const templateName = templateTypeName ? `${templateTypeName}_Template` : null;
const pipeMap =
new Map(pipeSummaries.map<[string, CompilePipeSummary]>(pipe => [pipe.name, pipe]));
const templateFunctionExpression =
new TemplateDefinitionBuilder(
outputCtx, outputCtx.constantPool, reflector, CONTEXT_NAME, BindingScope.ROOT_SCOPE, 0,
component.template !.ngContentSelectors, templateTypeName, templateName, pipeMap,
component.viewQueries, directives, pipes)
.buildTemplateFunction(template, []);
field('template', templateFunctionExpression);
// e.g. `directives: [MyDirective]`
if (directives.size) {
const expressions = Array.from(directives).map(d => outputCtx.importExpr(d));
field('directives', o.literalArr(expressions));
}
// e.g. `pipes: [MyPipe]`
if (pipes.size) {
const expressions = Array.from(pipes).map(p => outputCtx.importExpr(p));
field('pipes', o.literalArr(expressions));
}
// e.g `inputs: {a: 'a'}`
field('inputs', conditionallyCreateMapObjectLiteral(component.inputs, outputCtx));
// e.g 'outputs: {a: 'a'}`
field('outputs', conditionallyCreateMapObjectLiteral(component.outputs, outputCtx));
// e.g. `features: [NgOnChangesFeature(MyComponent)]`
const features: o.Expression[] = [];
if (component.type.lifecycleHooks.some(lifecycle => lifecycle == LifecycleHooks.OnChanges)) {
features.push(o.importExpr(R3.NgOnChangesFeature, null, null).callFn([outputCtx.importExpr(
component.type.reference)]));
}
if (features.length) {
field('features', o.literalArr(features));
}
const definitionField = outputCtx.constantPool.propertyNameOf(DefinitionKind.Component);
const definitionFunction =
o.importExpr(R3.defineComponent).callFn([o.literalMap(definitionMapValues)]);
if (mode === OutputMode.PartialClass) {
const className = identifierName(component.type) !;
className || error(`Cannot resolver the name of ${component.type}`);
// Create the partial class to be merged with the actual class.
outputCtx.statements.push(new o.ClassStmt(
/* name */ className,
/* parent */ null,
/* fields */[new o.ClassField(
/* name */ definitionField,
/* type */ o.INFERRED_TYPE,
/* modifiers */[o.StmtModifier.Static],
/* initializer */ definitionFunction)],
/* getters */[],
/* constructorMethod */ new o.ClassMethod(null, [], []),
/* methods */[]));
} else {
const classReference = outputCtx.importExpr(component.type.reference);
// Create the back-patch statement
outputCtx.statements.push(
new o.CommentStmt(BUILD_OPTIMIZER_COLOCATE),
classReference.prop(definitionField).set(definitionFunction).toStmt());
}
}
// TODO: Remove these when the things are fully supported
function unknown<T>(arg: o.Expression | o.Statement | TemplateAst): never {
throw new Error(
`Builder ${this.constructor.name} is unable to handle ${arg.constructor.name} yet`);
}
function unsupported(feature: string): never {
if (this) {
throw new Error(`Builder ${this.constructor.name} doesn't support ${feature} yet`);
}
throw new Error(`Feature ${feature} is not supported yet`);
}
const BINDING_INSTRUCTION_MAP: {[index: number]: o.ExternalReference | undefined} = {
[PropertyBindingType.Property]: R3.elementProperty,
[PropertyBindingType.Attribute]: R3.elementAttribute,
[PropertyBindingType.Class]: R3.elementClassNamed,
[PropertyBindingType.Style]: R3.elementStyleNamed
};
function interpolate(args: o.Expression[]): o.Expression {
args = args.slice(1); // Ignore the length prefix added for render2
switch (args.length) {
case 3:
return o.importExpr(R3.interpolation1).callFn(args);
case 5:
return o.importExpr(R3.interpolation2).callFn(args);
case 7:
return o.importExpr(R3.interpolation3).callFn(args);
case 9:
return o.importExpr(R3.interpolation4).callFn(args);
case 11:
return o.importExpr(R3.interpolation5).callFn(args);
case 13:
return o.importExpr(R3.interpolation6).callFn(args);
case 15:
return o.importExpr(R3.interpolation7).callFn(args);
case 17:
return o.importExpr(R3.interpolation8).callFn(args);
}
(args.length >= 19 && args.length % 2 == 1) ||
error(`Invalid interpolation argument length ${args.length}`);
return o.importExpr(R3.interpolationV).callFn([o.literalArr(args)]);
}
function pipeBinding(args: o.Expression[]): o.ExternalReference {
switch (args.length) {
case 0:
// The first parameter to pipeBind is always the value to be transformed followed
// by arg.length arguments so the total number of arguments to pipeBind are
// arg.length + 1.
return R3.pipeBind1;
case 1:
return R3.pipeBind2;
case 2:
return R3.pipeBind3;
default:
return R3.pipeBindV;
}
}
const pureFunctionIdentifiers = [
R3.pureFunction0, R3.pureFunction1, R3.pureFunction2, R3.pureFunction3, R3.pureFunction4,
R3.pureFunction5, R3.pureFunction6, R3.pureFunction7, R3.pureFunction8
];
function getLiteralFactory(
outputContext: OutputContext, literal: o.LiteralArrayExpr | o.LiteralMapExpr): o.Expression {
const {literalFactory, literalFactoryArguments} =
outputContext.constantPool.getLiteralFactory(literal);
literalFactoryArguments.length > 0 || error(`Expected arguments to a literal factory function`);
let pureFunctionIdent =
pureFunctionIdentifiers[literalFactoryArguments.length] || R3.pureFunctionV;
// Literal factories are pure functions that only need to be re-invoked when the parameters
// change.
return o.importExpr(pureFunctionIdent).callFn([literalFactory, ...literalFactoryArguments]);
}
function noop() {}
/**
* Function which is executed whenever a variable is referenced for the first time in a given
* scope.
*
* It is expected that the function creates the `const localName = expression`; statement.
*/
type DeclareLocalVarCallback = (lhsVar: o.ReadVarExpr, rhsExpression: o.Expression) => void;
class BindingScope implements LocalResolver {
/**
* Keeps a map from local variables to their expressions.
*
* This is used when one refers to variable such as: 'let abc = a.b.c`.
* - key to the map is the string literal `"abc"`.
* - value `lhs` is the left hand side which is an AST representing `abc`.
* - value `rhs` is the right hand side which is an AST representing `a.b.c`.
* - value `declared` is true if the `declareLocalVarCallback` has been called for this scope
* already.
*/
private map = new Map < string, {
lhs: o.ReadVarExpr;
rhs: o.Expression|undefined;
declared: boolean;
}
> ();
private referenceNameIndex = 0;
static ROOT_SCOPE = new BindingScope().set('$event', o.variable('$event'));
private constructor(
private parent: BindingScope|null = null,
private declareLocalVarCallback: DeclareLocalVarCallback = noop) {}
get(name: string): o.Expression|null {
let current: BindingScope|null = this;
while (current) {
let value = current.map.get(name);
if (value != null) {
if (current !== this) {
// make a local copy and reset the `declared` state.
value = {lhs: value.lhs, rhs: value.rhs, declared: false};
// Cache the value locally.
this.map.set(name, value);
}
if (value.rhs && !value.declared) {
// if it is first time we are referencing the variable in the scope
// than invoke the callback to insert variable declaration.
this.declareLocalVarCallback(value.lhs, value.rhs);
value.declared = true;
}
return value.lhs;
}
current = current.parent;
}
return null;
}
/**
* Create a local variable for later reference.
*
* @param name Name of the variable.
* @param lhs AST representing the left hand side of the `let lhs = rhs;`.
* @param rhs AST representing the right hand side of the `let lhs = rhs;`. The `rhs` can be
* `undefined` for variable that are ambient such as `$event` and which don't have `rhs`
* declaration.
*/
set(name: string, lhs: o.ReadVarExpr, rhs?: o.Expression): BindingScope {
!this.map.has(name) ||
error(`The name ${name} is already defined in scope to be ${this.map.get(name)}`);
this.map.set(name, {lhs: lhs, rhs: rhs, declared: false});
return this;
}
getLocal(name: string): (o.Expression|null) { return this.get(name); }
nestedScope(declareCallback: DeclareLocalVarCallback): BindingScope {
return new BindingScope(this, declareCallback);
}
freshReferenceName(): string {
let current: BindingScope = this;
// Find the top scope as it maintains the global reference count
while (current.parent) current = current.parent;
const ref = `${REFERENCE_PREFIX}${current.referenceNameIndex++}`;
return ref;
}
}
// Pasted from render3/interfaces/definition since it cannot be referenced directly
/**
* Flags passed into template functions to determine which blocks (i.e. creation, update)
* should be executed.
*
* Typically, a template runs both the creation block and the update block on initialization and
* subsequent runs only execute the update block. However, dynamically created views require that
* the creation block be executed separately from the update block (for backwards compat).
*/
export const enum RenderFlags {
/* Whether to run the creation block (e.g. create elements and directives) */
Create = 0b01,
/* Whether to run the update block (e.g. refresh bindings) */
Update = 0b10
}
class TemplateDefinitionBuilder implements TemplateAstVisitor, LocalResolver {
private _dataIndex = 0;
private _bindingContext = 0;
private _temporaryAllocated = false;
private _prefix: o.Statement[] = [];
private _creationMode: o.Statement[] = [];
private _variableMode: o.Statement[] = [];
private _bindingMode: o.Statement[] = [];
private _postfix: o.Statement[] = [];
private _contentProjections: Map<NgContentAst, NgContentInfo>;
private _projectionDefinitionIndex = 0;
private _valueConverter: ValueConverter;
private unsupported = unsupported;
private invalid = invalid;
private bindingScope: BindingScope;
// Whether we are inside a translatable element (`<p i18n>... somewhere here ... </p>)
private _inI18nSection: boolean = false;
private _i18nSectionIndex = -1;
// Maps of placeholder to node indexes for each of the i18n section
private _phToNodeIdxes: {[phName: string]: number[]}[] = [{}];
constructor(
private outputCtx: OutputContext, private constantPool: ConstantPool,
private reflector: CompileReflector, private contextParameter: string,
parentBindingScope: BindingScope, private level = 0, private ngContentSelectors: string[],
private contextName: string|null, private templateName: string|null,
private pipeMap: Map<string, CompilePipeSummary>, private viewQueries: CompileQueryMetadata[],
private directives: Set<any>, private pipes: Set<any>) {
this.bindingScope =
parentBindingScope.nestedScope((lhsVar: o.ReadVarExpr, expression: o.Expression) => {
this._bindingMode.push(
lhsVar.set(expression).toDeclStmt(o.INFERRED_TYPE, [o.StmtModifier.Final]));
});
this._valueConverter = new ValueConverter(
outputCtx, () => this.allocateDataSlot(), (name, localName, slot, value: o.ReadVarExpr) => {
this.bindingScope.set(localName, value);
const pipe = pipeMap.get(name) !;
pipe || error(`Could not find pipe ${name}`);
this.pipes.add(pipe.type.reference);
this._creationMode.push(
o.importExpr(R3.pipe).callFn([o.literal(slot), o.literal(name)]).toStmt());
});
}
buildTemplateFunction(nodes: TemplateAst[], variables: VariableAst[]): o.FunctionExpr {
// Create variable bindings
for (const variable of variables) {
const variableName = variable.name;
const expression =
o.variable(this.contextParameter).prop(variable.value || IMPLICIT_REFERENCE);
const scopedName = this.bindingScope.freshReferenceName();
// Add the reference to the local scope.
this.bindingScope.set(variableName, o.variable(variableName + scopedName), expression);
}
// Collect content projections
if (this.ngContentSelectors && this.ngContentSelectors.length > 0) {
const contentProjections = getContentProjection(nodes, this.ngContentSelectors);
this._contentProjections = contentProjections;
if (contentProjections.size > 0) {
const selectors: string[] = [];
Array.from(contentProjections.values()).forEach(info => {
if (info.selector) {
selectors[info.index - 1] = info.selector;
}
});
const projectionIndex = this._projectionDefinitionIndex = this.allocateDataSlot();
const parameters: o.Expression[] = [o.literal(projectionIndex)];
if (selectors.some(value => !value)) {
error(`content project information skipped an index`);
}
if (selectors.length > 1) {
const r3Selectors = selectors.map(s => parseSelectorToR3Selector(s));
// `projectionDef` needs both the parsed and raw value of the selectors
const parsed = this.outputCtx.constantPool.getConstLiteral(asLiteral(r3Selectors), true);
const unParsed = this.outputCtx.constantPool.getConstLiteral(asLiteral(selectors), true);
parameters.push(parsed, unParsed);
}
this.instruction(this._creationMode, null, R3.projectionDef, ...parameters);
}
}
// Define and update any view queries
for (let query of this.viewQueries) {
// e.g. r3.Q(0, somePredicate, true);
const querySlot = this.allocateDataSlot();
const predicate = getQueryPredicate(query, this.outputCtx);
const args = [
/* memoryIndex */ o.literal(querySlot, o.INFERRED_TYPE),
/* predicate */ predicate,
/* descend */ o.literal(query.descendants, o.INFERRED_TYPE)
];
if (query.read) {
args.push(this.outputCtx.importExpr(query.read.identifier !.reference));
}
this.instruction(this._creationMode, null, R3.query, ...args);
// (r3.qR(tmp = r3.ɵld(0)) && (ctx.someDir = tmp));
const temporary = this.temp();
const getQueryList = o.importExpr(R3.load).callFn([o.literal(querySlot)]);
const refresh = o.importExpr(R3.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = o.variable(CONTEXT_NAME)
.prop(query.propertyName)
.set(query.first ? temporary.prop('first') : temporary);
this._bindingMode.push(refresh.and(updateDirective).toStmt());
}
templateVisitAll(this, nodes);
const creationMode = this._creationMode.length > 0 ?
[o.ifStmt(
o.variable(RENDER_FLAGS).bitwiseAnd(o.literal(RenderFlags.Create), null, false),
this._creationMode)] :
[];
const updateMode = this._bindingMode.length > 0 ?
[o.ifStmt(
o.variable(RENDER_FLAGS).bitwiseAnd(o.literal(RenderFlags.Update), null, false),
this._bindingMode)] :
[];
// Generate maps of placeholder name to node indexes
// TODO(vicb): This is a WIP, not fully supported yet
for (const phToNodeIdx of this._phToNodeIdxes) {
if (Object.keys(phToNodeIdx).length > 0) {
const scopedName = this.bindingScope.freshReferenceName();
const phMap = o.variable(scopedName)
.set(mapToExpression(phToNodeIdx, true))
.toDeclStmt(o.INFERRED_TYPE, [o.StmtModifier.Final]);
this._prefix.push(phMap);
}
}
return o.fn(
[new o.FnParam(RENDER_FLAGS, o.NUMBER_TYPE), new o.FnParam(this.contextParameter, null)],
[
// Temporary variable declarations for query refresh (i.e. let _t: any;)
...this._prefix,
// Creating mode (i.e. if (rf & RenderFlags.Create) { ... })
...creationMode,
// Temporary variable declarations for local refs (i.e. const tmp = ld(1) as any)
...this._variableMode,
// Binding and refresh mode (i.e. if (rf & RenderFlags.Update) {...})
...updateMode,
// Nested templates (i.e. function CompTemplate() {})
...this._postfix
],
o.INFERRED_TYPE, null, this.templateName);
}
// LocalResolver
getLocal(name: string): o.Expression|null { return this.bindingScope.get(name); }
// TemplateAstVisitor
visitNgContent(ngContent: NgContentAst) {
const info = this._contentProjections.get(ngContent) !;
info ||
error(`Expected ${ngContent.sourceSpan} to be included in content projection collection`);
const slot = this.allocateDataSlot();
const parameters = [o.literal(slot), o.literal(this._projectionDefinitionIndex)];
if (info.index !== 0) {
parameters.push(o.literal(info.index));
}
this.instruction(this._creationMode, ngContent.sourceSpan, R3.projection, ...parameters);
}
// TemplateAstVisitor
visitElement(element: ElementAst) {
const elementIndex = this.allocateDataSlot();
const referenceDataSlots = new Map<string, number>();
const wasInI18nSection = this._inI18nSection;
const outputAttrs: {[name: string]: string} = {};
const attrI18nMetas: {[name: string]: string} = {};
let i18nMeta: string = '';
// Elements inside i18n sections are replaced with placeholders
// TODO(vicb): nested elements are a WIP in this phase
if (this._inI18nSection) {
const phName = element.name.toLowerCase();
if (!this._phToNodeIdxes[this._i18nSectionIndex][phName]) {
this._phToNodeIdxes[this._i18nSectionIndex][phName] = [];
}
this._phToNodeIdxes[this._i18nSectionIndex][phName].push(elementIndex);
}
// Handle i18n attributes
for (const attr of element.attrs) {
const name = attr.name;
const value = attr.value;
if (name === I18N_ATTR) {
if (this._inI18nSection) {
throw new Error(
`Could not mark an element as translatable inside of a translatable section`);
}
this._inI18nSection = true;
this._i18nSectionIndex++;
this._phToNodeIdxes[this._i18nSectionIndex] = {};
i18nMeta = value;
} else if (name.startsWith(I18N_ATTR_PREFIX)) {
attrI18nMetas[name.slice(I18N_ATTR_PREFIX.length)] = value;
} else {
outputAttrs[name] = value;
}
}
// Element creation mode
const parameters: o.Expression[] = [
o.literal(elementIndex),
o.literal(element.name),
];
element.directives.forEach(
directive => this.directives.add(directive.directive.type.reference));
// Add the attributes
const i18nMessages: o.Statement[] = [];
const attributes: o.Expression[] = [];
let hasI18nAttr = false;
Object.getOwnPropertyNames(outputAttrs).forEach(name => {
const value = outputAttrs[name];
attributes.push(o.literal(name));
if (attrI18nMetas.hasOwnProperty(name)) {
hasI18nAttr = true;
const meta = parseI18nMeta(attrI18nMetas[name]);
const variable = this.constantPool.getTranslation(value, meta);
attributes.push(variable);
} else {
attributes.push(o.literal(value));
}
});
let attrArg: o.Expression = o.TYPED_NULL_EXPR;
if (attributes.length > 0) {
attrArg = hasI18nAttr ? getLiteralFactory(this.outputCtx, o.literalArr(attributes)) :
this.constantPool.getConstLiteral(o.literalArr(attributes), true);
}
parameters.push(attrArg);
if (element.references && element.references.length > 0) {
const references =
flatten(element.references.map(reference => {
const slot = this.allocateDataSlot();
referenceDataSlots.set(reference.name, slot);
// Generate the update temporary.
const variableName = this.bindingScope.freshReferenceName();
this._variableMode.push(o.variable(variableName, o.INFERRED_TYPE)
.set(o.importExpr(R3.load).callFn([o.literal(slot)]))
.toDeclStmt(o.INFERRED_TYPE, [o.StmtModifier.Final]));
this.bindingScope.set(reference.name, o.variable(variableName));
return [reference.name, reference.originalValue];
})).map(value => o.literal(value));
parameters.push(
this.constantPool.getConstLiteral(o.literalArr(references), /* forceShared */ true));
} else {
parameters.push(o.TYPED_NULL_EXPR);
}
// Generate the instruction create element instruction
if (i18nMessages.length > 0) {
this._creationMode.push(...i18nMessages);
}
this.instruction(
this._creationMode, element.sourceSpan, R3.createElement, ...trimTrailingNulls(parameters));
const implicit = o.variable(CONTEXT_NAME);
// Generate Listeners (outputs)
element.outputs.forEach((outputAst: BoundEventAst) => {
const functionName = `${this.templateName}_${element.name}_${outputAst.name}_listener`;
const localVars: o.Statement[] = [];
const bindingScope =
this.bindingScope.nestedScope((lhsVar: o.ReadVarExpr, rhsExpression: o.Expression) => {
localVars.push(
lhsVar.set(rhsExpression).toDeclStmt(o.INFERRED_TYPE, [o.StmtModifier.Final]));
});
const bindingExpr = convertActionBinding(
bindingScope, o.variable(CONTEXT_NAME), outputAst.handler, 'b',
() => error('Unexpected interpolation'));
const handler = o.fn(
[new o.FnParam('$event', o.DYNAMIC_TYPE)], [...localVars, ...bindingExpr.render3Stmts],
o.INFERRED_TYPE, null, functionName);
this.instruction(
this._creationMode, outputAst.sourceSpan, R3.listener, o.literal(outputAst.name),
handler);
});
// Generate element input bindings
for (let input of element.inputs) {
if (input.isAnimation) {
this.unsupported('animations');
}
const convertedBinding = this.convertPropertyBinding(implicit, input.value);
const instruction = BINDING_INSTRUCTION_MAP[input.type];
if (instruction) {
// TODO(chuckj): runtime: security context?
this.instruction(
this._bindingMode, input.sourceSpan, instruction, o.literal(elementIndex),
o.literal(input.name), convertedBinding);
} else {
this.unsupported(`binding ${PropertyBindingType[input.type]}`);
}
}
// Generate directives input bindings
this._visitDirectives(element.directives, implicit, elementIndex);
// Traverse element child nodes
if (this._inI18nSection && element.children.length == 1 &&
element.children[0] instanceof TextAst) {
const text = element.children[0] as TextAst;
this.visitSingleI18nTextChild(text, i18nMeta);
} else {
templateVisitAll(this, element.children);
}
// Finish element construction mode.
this.instruction(
this._creationMode, element.endSourceSpan || element.sourceSpan, R3.elementEnd);
// Restore the state before exiting this node
this._inI18nSection = wasInI18nSection;
}
private _visitDirectives(directives: DirectiveAst[], implicit: o.Expression, nodeIndex: number) {
for (let directive of directives) {
// Creation mode
// e.g. D(0, TodoComponentDef.n(), TodoComponentDef);
const directiveType = directive.directive.type.reference;
const kind =
directive.directive.isComponent ? DefinitionKind.Component : DefinitionKind.Directive;
// Note: *do not cache* calls to this.directiveOf() as the constant pool needs to know if the
// node is referenced multiple times to know that it must generate the reference into a
// temporary.
// Bindings
for (const input of directive.inputs) {
const convertedBinding = this.convertPropertyBinding(implicit, input.value);
this.instruction(
this._bindingMode, directive.sourceSpan, R3.elementProperty, o.literal(nodeIndex),
o.literal(input.templateName), o.importExpr(R3.bind).callFn([convertedBinding]));
}
}
}
// TemplateAstVisitor
visitEmbeddedTemplate(template: EmbeddedTemplateAst) {
const templateIndex = this.allocateDataSlot();
const templateRef = this.reflector.resolveExternalReference(Identifiers.TemplateRef);
const templateDirective = template.directives.find(
directive => directive.directive.type.diDeps.some(
dependency =>
dependency.token != null && (tokenReference(dependency.token) == templateRef)));
const contextName =
this.contextName && templateDirective && templateDirective.directive.type.reference.name ?
`${this.contextName}_${templateDirective.directive.type.reference.name}` :
null;
const templateName =
contextName ? `${contextName}_Template_${templateIndex}` : `Template_${templateIndex}`;
const templateContext = `ctx${this.level}`;
const parameters: o.Expression[] = [o.variable(templateName), o.literal(null, o.INFERRED_TYPE)];
const attributeNames: o.Expression[] = [];
template.directives.forEach((directiveAst: DirectiveAst) => {
this.directives.add(directiveAst.directive.type.reference);
CssSelector.parse(directiveAst.directive.selector !).forEach(selector => {
selector.attrs.forEach((value) => {
// Convert '' (falsy) strings into `null`. This is needed because we want
// to communicate to runtime that these attributes are present for
// selector matching, but should not actually be added to the DOM.
// attributeNames.push(o.literal(value ? value : null));
// TODO(misko): make the above comment true, for now just write to DOM because
// the runtime selectors have not been updated.
attributeNames.push(o.literal(value));
});
});
});
if (attributeNames.length) {
parameters.push(
this.constantPool.getConstLiteral(o.literalArr(attributeNames), /* forcedShared */ true));
}
// e.g. C(1, C1Template)
this.instruction(
this._creationMode, template.sourceSpan, R3.containerCreate, o.literal(templateIndex),
...trimTrailingNulls(parameters));
// Generate directives
this._visitDirectives(template.directives, o.variable(CONTEXT_NAME), templateIndex);
// Create the template function
const templateVisitor = new TemplateDefinitionBuilder(
this.outputCtx, this.constantPool, this.reflector, templateContext, this.bindingScope,
this.level + 1, this.ngContentSelectors, contextName, templateName, this.pipeMap, [],
this.directives, this.pipes);
const templateFunctionExpr =
templateVisitor.buildTemplateFunction(template.children, template.variables);
this._postfix.push(templateFunctionExpr.toDeclStmt(templateName, null));
}
// These should be handled in the template or element directly.
readonly visitReference = invalid;
readonly visitVariable = invalid;
readonly visitEvent = invalid;
readonly visitElementProperty = invalid;
readonly visitAttr = invalid;
// TemplateAstVisitor
visitBoundText(text: BoundTextAst) {
const nodeIndex = this.allocateDataSlot();
// Creation mode
this.instruction(this._creationMode, text.sourceSpan, R3.text, o.literal(nodeIndex));
this.instruction(
this._bindingMode, text.sourceSpan, R3.textCreateBound, o.literal(nodeIndex),
this.convertPropertyBinding(o.variable(CONTEXT_NAME), text.value));
}
// TemplateAstVisitor
visitText(text: TextAst) {
// Text is defined in creation mode only.
this.instruction(
this._creationMode, text.sourceSpan, R3.text, o.literal(this.allocateDataSlot()),
o.literal(text.value));
}
// When the content of the element is a single text node the translation can be inlined:
//
// `<p i18n="desc|mean">some content</p>`
// compiles to
// ```
// /**
// * @desc desc
// * @meaning mean
// */
// const MSG_XYZ = goog.getMsg('some content');
// i0.ɵT(1, MSG_XYZ);
// ```
visitSingleI18nTextChild(text: TextAst, i18nMeta: string) {
const meta = parseI18nMeta(i18nMeta);
const variable = this.constantPool.getTranslation(text.value, meta);
this.instruction(
this._creationMode, text.sourceSpan, R3.text, o.literal(this.allocateDataSlot()), variable);
}
// These should be handled in the template or element directly
readonly visitDirective = invalid;
readonly visitDirectiveProperty = invalid;
private allocateDataSlot() { return this._dataIndex++; }
private bindingContext() { return `${this._bindingContext++}`; }
private instruction(
statements: o.Statement[], span: ParseSourceSpan|null, reference: o.ExternalReference,
...params: o.Expression[]) {
statements.push(o.importExpr(reference, null, span).callFn(params, span).toStmt());
}
private definitionOf(type: any, kind: DefinitionKind): o.Expression {
return this.constantPool.getDefinition(type, kind, this.outputCtx);
}
private temp(): o.ReadVarExpr {
if (!this._temporaryAllocated) {
this._prefix.push(new o.DeclareVarStmt(TEMPORARY_NAME, undefined, o.DYNAMIC_TYPE));
this._temporaryAllocated = true;
}
return o.variable(TEMPORARY_NAME);
}
private convertPropertyBinding(implicit: o.Expression, value: AST): o.Expression {
const pipesConvertedValue = value.visit(this._valueConverter);
const convertedPropertyBinding = convertPropertyBinding(
this, implicit, pipesConvertedValue, this.bindingContext(), BindingForm.TrySimple,
interpolate);
this._bindingMode.push(...convertedPropertyBinding.stmts);
return convertedPropertyBinding.currValExpr;
}
}
function getQueryPredicate(query: CompileQueryMetadata, outputCtx: OutputContext): o.Expression {
if (query.selectors.length > 1 || (query.selectors.length == 1 && query.selectors[0].value)) {
const selectors = query.selectors.map(value => value.value as string);
selectors.some(value => !value) && error('Found a type among the string selectors expected');
return outputCtx.constantPool.getConstLiteral(
o.literalArr(selectors.map(value => o.literal(value))));
}
if (query.selectors.length == 1) {
const first = query.selectors[0];
if (first.identifier) {
return outputCtx.importExpr(first.identifier.reference);
}
}
error('Unexpected query form');
return o.NULL_EXPR;
}
export function createFactory(
type: CompileTypeMetadata, outputCtx: OutputContext, reflector: CompileReflector,
queries: CompileQueryMetadata[]): o.Expression {
let args: o.Expression[] = [];
const elementRef = reflector.resolveExternalReference(Identifiers.ElementRef);
const templateRef = reflector.resolveExternalReference(Identifiers.TemplateRef);
const viewContainerRef = reflector.resolveExternalReference(Identifiers.ViewContainerRef);
for (let dependency of type.diDeps) {
const token = dependency.token;
if (token) {
const tokenRef = tokenReference(token);
if (tokenRef === elementRef) {
args.push(o.importExpr(R3.injectElementRef).callFn([]));
} else if (tokenRef === templateRef) {
args.push(o.importExpr(R3.injectTemplateRef).callFn([]));
} else if (tokenRef === viewContainerRef) {
args.push(o.importExpr(R3.injectViewContainerRef).callFn([]));
} else if (dependency.isAttribute) {
args.push(o.importExpr(R3.injectAttribute).callFn([o.literal(dependency.token !.value)]));
} else {
const tokenValue =
token.identifier != null ? outputCtx.importExpr(tokenRef) : o.literal(tokenRef);
const directiveInjectArgs = [tokenValue];
const flags = extractFlags(dependency);
if (flags != InjectFlags.Default) {
// Append flag information if other than default.
directiveInjectArgs.push(o.literal(flags));
}
args.push(o.importExpr(R3.directiveInject).callFn(directiveInjectArgs));
}
} else {
unsupported('dependency without a token');
}
}
const queryDefinitions: o.Expression[] = [];
for (let query of queries) {
const predicate = getQueryPredicate(query, outputCtx);
// e.g. r3.Q(null, somePredicate, false) or r3.Q(null, ['div'], false)
const parameters = [
/* memoryIndex */ o.literal(null, o.INFERRED_TYPE),
/* predicate */ predicate,
/* descend */ o.literal(query.descendants)
];
if (query.read) {
parameters.push(outputCtx.importExpr(query.read.identifier !.reference));
}
queryDefinitions.push(o.importExpr(R3.query).callFn(parameters));
}
const createInstance = new o.InstantiateExpr(outputCtx.importExpr(type.reference), args);
const result = queryDefinitions.length > 0 ? o.literalArr([createInstance, ...queryDefinitions]) :
createInstance;
return o.fn(
[], [new o.ReturnStatement(result)], o.INFERRED_TYPE, null,
type.reference.name ? `${type.reference.name}_Factory` : null);
}
function extractFlags(dependency: CompileDiDependencyMetadata): InjectFlags {
let flags = InjectFlags.Default;
if (dependency.isHost) {
flags |= InjectFlags.Host;
}
if (dependency.isOptional) {
flags |= InjectFlags.Optional;