@angular/compiler 17.0.0-next.2 → 17.0.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @license Angular v17.0.0-next.2
2
+ * @license Angular v17.0.0-next.4
3
3
  * (c) 2010-2022 Google LLC. https://angular.io/
4
4
  * License: MIT
5
5
  */
@@ -480,179 +480,6 @@ var core = /*#__PURE__*/Object.freeze({
480
480
  parseSelectorToR3Selector: parseSelectorToR3Selector
481
481
  });
482
482
 
483
- /**
484
- * Represents a big integer using a buffer of its individual digits, with the least significant
485
- * digit stored at the beginning of the array (little endian).
486
- *
487
- * For performance reasons, each instance is mutable. The addition operation can be done in-place
488
- * to reduce memory pressure of allocation for the digits array.
489
- */
490
- class BigInteger {
491
- static zero() {
492
- return new BigInteger([0]);
493
- }
494
- static one() {
495
- return new BigInteger([1]);
496
- }
497
- /**
498
- * Creates a big integer using its individual digits in little endian storage.
499
- */
500
- constructor(digits) {
501
- this.digits = digits;
502
- }
503
- /**
504
- * Creates a clone of this instance.
505
- */
506
- clone() {
507
- return new BigInteger(this.digits.slice());
508
- }
509
- /**
510
- * Returns a new big integer with the sum of `this` and `other` as its value. This does not mutate
511
- * `this` but instead returns a new instance, unlike `addToSelf`.
512
- */
513
- add(other) {
514
- const result = this.clone();
515
- result.addToSelf(other);
516
- return result;
517
- }
518
- /**
519
- * Adds `other` to the instance itself, thereby mutating its value.
520
- */
521
- addToSelf(other) {
522
- const maxNrOfDigits = Math.max(this.digits.length, other.digits.length);
523
- let carry = 0;
524
- for (let i = 0; i < maxNrOfDigits; i++) {
525
- let digitSum = carry;
526
- if (i < this.digits.length) {
527
- digitSum += this.digits[i];
528
- }
529
- if (i < other.digits.length) {
530
- digitSum += other.digits[i];
531
- }
532
- if (digitSum >= 10) {
533
- this.digits[i] = digitSum - 10;
534
- carry = 1;
535
- }
536
- else {
537
- this.digits[i] = digitSum;
538
- carry = 0;
539
- }
540
- }
541
- // Apply a remaining carry if needed.
542
- if (carry > 0) {
543
- this.digits[maxNrOfDigits] = 1;
544
- }
545
- }
546
- /**
547
- * Builds the decimal string representation of the big integer. As this is stored in
548
- * little endian, the digits are concatenated in reverse order.
549
- */
550
- toString() {
551
- let res = '';
552
- for (let i = this.digits.length - 1; i >= 0; i--) {
553
- res += this.digits[i];
554
- }
555
- return res;
556
- }
557
- }
558
- /**
559
- * Represents a big integer which is optimized for multiplication operations, as its power-of-twos
560
- * are memoized. See `multiplyBy()` for details on the multiplication algorithm.
561
- */
562
- class BigIntForMultiplication {
563
- constructor(value) {
564
- this.powerOfTwos = [value];
565
- }
566
- /**
567
- * Returns the big integer itself.
568
- */
569
- getValue() {
570
- return this.powerOfTwos[0];
571
- }
572
- /**
573
- * Computes the value for `num * b`, where `num` is a JS number and `b` is a big integer. The
574
- * value for `b` is represented by a storage model that is optimized for this computation.
575
- *
576
- * This operation is implemented in N(log2(num)) by continuous halving of the number, where the
577
- * least-significant bit (LSB) is tested in each iteration. If the bit is set, the bit's index is
578
- * used as exponent into the power-of-two multiplication of `b`.
579
- *
580
- * As an example, consider the multiplication num=42, b=1337. In binary 42 is 0b00101010 and the
581
- * algorithm unrolls into the following iterations:
582
- *
583
- * Iteration | num | LSB | b * 2^iter | Add? | product
584
- * -----------|------------|------|------------|------|--------
585
- * 0 | 0b00101010 | 0 | 1337 | No | 0
586
- * 1 | 0b00010101 | 1 | 2674 | Yes | 2674
587
- * 2 | 0b00001010 | 0 | 5348 | No | 2674
588
- * 3 | 0b00000101 | 1 | 10696 | Yes | 13370
589
- * 4 | 0b00000010 | 0 | 21392 | No | 13370
590
- * 5 | 0b00000001 | 1 | 42784 | Yes | 56154
591
- * 6 | 0b00000000 | 0 | 85568 | No | 56154
592
- *
593
- * The computed product of 56154 is indeed the correct result.
594
- *
595
- * The `BigIntForMultiplication` representation for a big integer provides memoized access to the
596
- * power-of-two values to reduce the workload in computing those values.
597
- */
598
- multiplyBy(num) {
599
- const product = BigInteger.zero();
600
- this.multiplyByAndAddTo(num, product);
601
- return product;
602
- }
603
- /**
604
- * See `multiplyBy()` for details. This function allows for the computed product to be added
605
- * directly to the provided result big integer.
606
- */
607
- multiplyByAndAddTo(num, result) {
608
- for (let exponent = 0; num !== 0; num = num >>> 1, exponent++) {
609
- if (num & 1) {
610
- const value = this.getMultipliedByPowerOfTwo(exponent);
611
- result.addToSelf(value);
612
- }
613
- }
614
- }
615
- /**
616
- * Computes and memoizes the big integer value for `this.number * 2^exponent`.
617
- */
618
- getMultipliedByPowerOfTwo(exponent) {
619
- // Compute the powers up until the requested exponent, where each value is computed from its
620
- // predecessor. This is simple as `this.number * 2^(exponent - 1)` only has to be doubled (i.e.
621
- // added to itself) to reach `this.number * 2^exponent`.
622
- for (let i = this.powerOfTwos.length; i <= exponent; i++) {
623
- const previousPower = this.powerOfTwos[i - 1];
624
- this.powerOfTwos[i] = previousPower.add(previousPower);
625
- }
626
- return this.powerOfTwos[exponent];
627
- }
628
- }
629
- /**
630
- * Represents an exponentiation operation for the provided base, of which exponents are computed and
631
- * memoized. The results are represented by a `BigIntForMultiplication` which is tailored for
632
- * multiplication operations by memoizing the power-of-twos. This effectively results in a matrix
633
- * representation that is lazily computed upon request.
634
- */
635
- class BigIntExponentiation {
636
- constructor(base) {
637
- this.base = base;
638
- this.exponents = [new BigIntForMultiplication(BigInteger.one())];
639
- }
640
- /**
641
- * Compute the value for `this.base^exponent`, resulting in a big integer that is optimized for
642
- * further multiplication operations.
643
- */
644
- toThePowerOf(exponent) {
645
- // Compute the results up until the requested exponent, where every value is computed from its
646
- // predecessor. This is because `this.base^(exponent - 1)` only has to be multiplied by `base`
647
- // to reach `this.base^exponent`.
648
- for (let i = this.exponents.length; i <= exponent; i++) {
649
- const value = this.exponents[i - 1].multiplyBy(this.base);
650
- this.exponents[i] = new BigIntForMultiplication(value);
651
- }
652
- return this.exponents[exponent];
653
- }
654
- }
655
-
656
483
  /**
657
484
  * A lazily created TextEncoder instance for converting strings into UTF-8 bytes
658
485
  */
@@ -815,17 +642,18 @@ function fingerprint(str) {
815
642
  hi = hi ^ 0x130f9bef;
816
643
  lo = lo ^ -0x6b5f56d8;
817
644
  }
818
- return [hi, lo];
645
+ return (BigInt.asUintN(32, BigInt(hi)) << BigInt(32)) | BigInt.asUintN(32, BigInt(lo));
819
646
  }
820
647
  function computeMsgId(msg, meaning = '') {
821
648
  let msgFingerprint = fingerprint(msg);
822
649
  if (meaning) {
823
- const meaningFingerprint = fingerprint(meaning);
824
- msgFingerprint = add64(rol64(msgFingerprint, 1), meaningFingerprint);
650
+ // Rotate the 64-bit message fingerprint one bit to the left and then add the meaning
651
+ // fingerprint.
652
+ msgFingerprint = BigInt.asUintN(64, msgFingerprint << BigInt(1)) |
653
+ ((msgFingerprint >> BigInt(63)) & BigInt(1));
654
+ msgFingerprint += fingerprint(meaning);
825
655
  }
826
- const hi = msgFingerprint[0];
827
- const lo = msgFingerprint[1];
828
- return wordsToDecimalString(hi & 0x7fffffff, lo);
656
+ return BigInt.asUintN(63, msgFingerprint).toString();
829
657
  }
830
658
  function hash32(view, length, c) {
831
659
  let a = 0x9e3779b9, b = 0x9e3779b9;
@@ -931,26 +759,10 @@ function add32to64(a, b) {
931
759
  const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
932
760
  return [high >>> 16, (high << 16) | (low & 0xffff)];
933
761
  }
934
- function add64(a, b) {
935
- const ah = a[0], al = a[1];
936
- const bh = b[0], bl = b[1];
937
- const result = add32to64(al, bl);
938
- const carry = result[0];
939
- const l = result[1];
940
- const h = add32(add32(ah, bh), carry);
941
- return [h, l];
942
- }
943
762
  // Rotate a 32b number left `count` position
944
763
  function rol32(a, count) {
945
764
  return (a << count) | (a >>> (32 - count));
946
765
  }
947
- // Rotate a 64b number left `count` position
948
- function rol64(num, count) {
949
- const hi = num[0], lo = num[1];
950
- const h = (hi << count) | (lo >>> (32 - count));
951
- const l = (lo << count) | (hi >>> (32 - count));
952
- return [h, l];
953
- }
954
766
  function bytesToWords32(bytes, endian) {
955
767
  const size = (bytes.length + 3) >>> 2;
956
768
  const words32 = [];
@@ -976,31 +788,6 @@ function wordAt(bytes, index, endian) {
976
788
  }
977
789
  return word;
978
790
  }
979
- /**
980
- * Create a shared exponentiation pool for base-256 computations. This shared pool provides memoized
981
- * power-of-256 results with memoized power-of-two computations for efficient multiplication.
982
- *
983
- * For our purposes, this can be safely stored as a global without memory concerns. The reason is
984
- * that we encode two words, so only need the 0th (for the low word) and 4th (for the high word)
985
- * exponent.
986
- */
987
- const base256 = new BigIntExponentiation(256);
988
- /**
989
- * Represents two 32-bit words as a single decimal number. This requires a big integer storage
990
- * model as JS numbers are not accurate enough to represent the 64-bit number.
991
- *
992
- * Based on https://www.danvk.org/hex2dec.html
993
- */
994
- function wordsToDecimalString(hi, lo) {
995
- // Encode the four bytes in lo in the lower digits of the decimal number.
996
- // Note: the multiplication results in lo itself but represented by a big integer using its
997
- // decimal digits.
998
- const decimal = base256.toThePowerOf(0).multiplyBy(lo);
999
- // Encode the four bytes in hi above the four lo bytes. lo is a maximum of (2^8)^4, which is why
1000
- // this multiplication factor is applied.
1001
- base256.toThePowerOf(4).multiplyByAndAddTo(hi, decimal);
1002
- return decimal.toString();
1003
- }
1004
791
 
1005
792
  //// Types
1006
793
  var TypeModifier;
@@ -1677,8 +1464,8 @@ class FunctionExpr extends Expression {
1677
1464
  this.name = name;
1678
1465
  }
1679
1466
  isEquivalent(e) {
1680
- return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
1681
- areAllEquivalent(this.statements, e.statements);
1467
+ return (e instanceof FunctionExpr || e instanceof DeclareFunctionStmt) &&
1468
+ areAllEquivalent(this.params, e.params) && areAllEquivalent(this.statements, e.statements);
1682
1469
  }
1683
1470
  isConstant() {
1684
1471
  return false;
@@ -1724,6 +1511,9 @@ class ArrowFunctionExpr extends Expression {
1724
1511
  // TODO: Should we deep clone statements?
1725
1512
  return new ArrowFunctionExpr(this.params.map(p => p.clone()), Array.isArray(this.body) ? this.body : this.body.clone(), this.type, this.sourceSpan);
1726
1513
  }
1514
+ toDeclStmt(name, modifiers) {
1515
+ return new DeclareVarStmt(name, this, INFERRED_TYPE, modifiers, this.sourceSpan);
1516
+ }
1727
1517
  }
1728
1518
  class UnaryOperatorExpr extends Expression {
1729
1519
  constructor(operator, expr, type, sourceSpan, parens = true) {
@@ -2515,13 +2305,32 @@ class ConstantPool {
2515
2305
  }))));
2516
2306
  }
2517
2307
  }
2308
+ getSharedFunctionReference(fn, prefix) {
2309
+ const isArrow = fn instanceof ArrowFunctionExpr;
2310
+ for (const current of this.statements) {
2311
+ // Arrow functions are saved as variables so we check if the
2312
+ // value of the variable is the same as the arrow function.
2313
+ if (isArrow && current instanceof DeclareVarStmt && current.value?.isEquivalent(fn)) {
2314
+ return variable(current.name);
2315
+ }
2316
+ // Function declarations are saved as function statements
2317
+ // so we compare them directly to the passed-in function.
2318
+ if (!isArrow && current instanceof DeclareFunctionStmt && fn.isEquivalent(current)) {
2319
+ return variable(current.name);
2320
+ }
2321
+ }
2322
+ // Otherwise declare the function.
2323
+ const name = this.uniqueName(prefix);
2324
+ this.statements.push(fn.toDeclStmt(name, StmtModifier.Final));
2325
+ return variable(name);
2326
+ }
2518
2327
  _getLiteralFactory(key, values, resultMap) {
2519
2328
  let literalFactory = this.literalFactories.get(key);
2520
2329
  const literalFactoryArguments = values.filter((e => !e.isConstant()));
2521
2330
  if (!literalFactory) {
2522
2331
  const resultExpressions = values.map((e, index) => e.isConstant() ? this.getConstLiteral(e, true) : variable(`a${index}`));
2523
2332
  const parameters = resultExpressions.filter(isVariable).map(e => new FnParam(e.name, DYNAMIC_TYPE));
2524
- const pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
2333
+ const pureFunctionDeclaration = arrowFn(parameters, resultMap(resultExpressions), INFERRED_TYPE);
2525
2334
  const name = this.freshName();
2526
2335
  this.statements.push(variable(name)
2527
2336
  .set(pureFunctionDeclaration)
@@ -2678,6 +2487,7 @@ class Identifiers {
2678
2487
  static { this.repeaterCreate = { name: 'ɵɵrepeaterCreate', moduleName: CORE }; }
2679
2488
  static { this.repeaterTrackByIndex = { name: 'ɵɵrepeaterTrackByIndex', moduleName: CORE }; }
2680
2489
  static { this.repeaterTrackByIdentity = { name: 'ɵɵrepeaterTrackByIdentity', moduleName: CORE }; }
2490
+ static { this.componentInstance = { name: 'ɵɵcomponentInstance', moduleName: CORE }; }
2681
2491
  static { this.text = { name: 'ɵɵtext', moduleName: CORE }; }
2682
2492
  static { this.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE }; }
2683
2493
  static { this.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE }; }
@@ -5780,13 +5590,13 @@ let policy;
5780
5590
  */
5781
5591
  function getPolicy() {
5782
5592
  if (policy === undefined) {
5593
+ const trustedTypes = _global['trustedTypes'];
5783
5594
  policy = null;
5784
- if (_global.trustedTypes) {
5595
+ if (trustedTypes) {
5785
5596
  try {
5786
- policy =
5787
- _global.trustedTypes.createPolicy('angular#unsafe-jit', {
5788
- createScript: (s) => s,
5789
- });
5597
+ policy = trustedTypes.createPolicy('angular#unsafe-jit', {
5598
+ createScript: (s) => s,
5599
+ });
5790
5600
  }
5791
5601
  catch {
5792
5602
  // trustedTypes.createPolicy throws if called with a name that is
@@ -5816,7 +5626,7 @@ function trustedScriptFromString(script) {
5816
5626
  * vulnerabilities.
5817
5627
  */
5818
5628
  function newTrustedFunctionForJIT(...args) {
5819
- if (!_global.trustedTypes) {
5629
+ if (!_global['trustedTypes']) {
5820
5630
  // In environments that don't support Trusted Types, fall back to the most
5821
5631
  // straightforward implementation:
5822
5632
  return new Function(...args);
@@ -7051,6 +6861,26 @@ function convertPropertyBinding(localResolver, implicitReceiver, expressionWitho
7051
6861
  }
7052
6862
  return new ConvertPropertyBindingResult(stmts, outputExpr);
7053
6863
  }
6864
+ /** Converts an AST to a pure function that may have access to the component scope. */
6865
+ function convertPureComponentScopeFunction(ast, localResolver, implicitReceiver, bindingId) {
6866
+ const converted = convertPropertyBindingBuiltins({
6867
+ createLiteralArrayConverter: () => args => literalArr(args),
6868
+ createLiteralMapConverter: keys => values => literalMap(keys.map((key, index) => {
6869
+ return ({
6870
+ key: key.key,
6871
+ value: values[index],
6872
+ quoted: key.quoted,
6873
+ });
6874
+ })),
6875
+ createPipeConverter: () => {
6876
+ throw new Error('Illegal State: Pipes are not allowed in this context');
6877
+ }
6878
+ }, ast);
6879
+ const visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, false);
6880
+ const statements = [];
6881
+ flattenStatements(converted.visit(visitor, _Mode.Statement), statements);
6882
+ return statements;
6883
+ }
7054
6884
  /**
7055
6885
  * Given some expression, such as a binding or interpolation expression, and a context expression to
7056
6886
  * look values up on, visit each facet of the given expression resolving values from the context
@@ -10921,6 +10751,7 @@ function phaseAlignPipeVariadicVarOffset(job) {
10921
10751
  expr.varOffset = expr.args.varOffset;
10922
10752
  // Put the PureFunction vars following the PipeBindingVariadic vars.
10923
10753
  expr.args.varOffset = expr.varOffset + varsUsedByIrExpression(expr);
10754
+ return undefined;
10924
10755
  });
10925
10756
  }
10926
10757
  }
@@ -18014,7 +17845,7 @@ class _TreeBuilder {
18014
17845
  // This is unlikely to happen, but we have an assertion just in case.
18015
17846
  if (parent instanceof BlockGroup) {
18016
17847
  this.errors.push(TreeError.create(null, startSpan, 'Text cannot be placed directly inside of a block group.'));
18017
- return null;
17848
+ return;
18018
17849
  }
18019
17850
  if (parent != null && parent.children.length === 0 &&
18020
17851
  this.getTagDefinition(parent.name).ignoreFirstLf) {
@@ -19267,6 +19098,7 @@ function mergeNextContextsInOps(ops) {
19267
19098
  tryToMerge = false;
19268
19099
  break;
19269
19100
  }
19101
+ return;
19270
19102
  });
19271
19103
  }
19272
19104
  }
@@ -23083,7 +22915,12 @@ function validateSwitchBlock(ast) {
23083
22915
  const [primaryBlock, ...secondaryBlocks] = ast.blocks;
23084
22916
  const errors = [];
23085
22917
  let hasDefault = false;
23086
- if (primaryBlock.children.length > 0) {
22918
+ const hasPrimary = primaryBlock.children.length > 0 && primaryBlock.children.some(child => {
22919
+ // The main block might have empty text nodes if `preserveWhitespaces` is enabled.
22920
+ // Allow them since they might be used for code formatting.
22921
+ return !(child instanceof Text) || child.value.trim().length > 0;
22922
+ });
22923
+ if (hasPrimary) {
23087
22924
  errors.push(new ParseError(primaryBlock.sourceSpan, 'Switch block can only contain "case" and "default" blocks'));
23088
22925
  }
23089
22926
  if (primaryBlock.parameters.length !== 1) {
@@ -24383,9 +24220,10 @@ function createComponentDefConsts() {
24383
24220
  };
24384
24221
  }
24385
24222
  class TemplateData {
24386
- constructor(name, index, visitor) {
24223
+ constructor(name, index, scope, visitor) {
24387
24224
  this.name = name;
24388
24225
  this.index = index;
24226
+ this.scope = scope;
24389
24227
  this.visitor = visitor;
24390
24228
  }
24391
24229
  getConstCount() {
@@ -25059,7 +24897,7 @@ class TemplateDefinitionBuilder {
25059
24897
  this._ngContentReservedSlots.push(...visitor._ngContentReservedSlots);
25060
24898
  }
25061
24899
  });
25062
- return new TemplateData(name, index, visitor);
24900
+ return new TemplateData(name, index, visitor._bindingScope, visitor);
25063
24901
  }
25064
24902
  createEmbeddedTemplateFn(tagName, children, contextNameSuffix, sourceSpan, variables = [], attrsExprs, references, i18n) {
25065
24903
  const data = this.prepareEmbeddedTemplateFn(children, contextNameSuffix, variables, i18n);
@@ -25345,8 +25183,8 @@ class TemplateDefinitionBuilder {
25345
25183
  const dependencyExp = [];
25346
25184
  for (const deferredDep of deferredDeps) {
25347
25185
  if (deferredDep.isDeferrable) {
25348
- // Callback function, e.g. `function(m) { return m.MyCmp; }`.
25349
- const innerFn = fn([new FnParam('m', DYNAMIC_TYPE)], [new ReturnStatement(variable('m').prop(deferredDep.symbolName))]);
25186
+ // Callback function, e.g. `m () => m.MyCmp;`.
25187
+ const innerFn = arrowFn([new FnParam('m', DYNAMIC_TYPE)], variable('m').prop(deferredDep.symbolName));
25350
25188
  // Dynamic import, e.g. `import('./a').then(...)`.
25351
25189
  const importExpr = (new DynamicImportExpr(deferredDep.importPath)).prop('then').callFn([innerFn]);
25352
25190
  dependencyExp.push(importExpr);
@@ -25356,8 +25194,8 @@ class TemplateDefinitionBuilder {
25356
25194
  dependencyExp.push(deferredDep.type);
25357
25195
  }
25358
25196
  }
25359
- const depsFnExpr = fn([], [new ReturnStatement(literalArr(dependencyExp))], INFERRED_TYPE, null, name);
25360
- this.constantPool.statements.push(depsFnExpr.toDeclStmt(name));
25197
+ const depsFnExpr = arrowFn([], literalArr(dependencyExp));
25198
+ this.constantPool.statements.push(depsFnExpr.toDeclStmt(name, StmtModifier.Final));
25361
25199
  return variable(name);
25362
25200
  }
25363
25201
  createDeferTriggerInstructions(deferredIndex, triggers, prefetch) {
@@ -25406,14 +25244,18 @@ class TemplateDefinitionBuilder {
25406
25244
  // Allocate one slot for the repeater metadata. The slots for the primary and empty block
25407
25245
  // are implicitly inferred by the runtime to index + 1 and index + 2.
25408
25246
  const blockIndex = this.allocateDataSlot();
25409
- const templateVariables = this.createForLoopVariables(block);
25410
- const primaryData = this.prepareEmbeddedTemplateFn(block.children, '_For', templateVariables);
25247
+ const primaryData = this.prepareEmbeddedTemplateFn(block.children, '_For', [
25248
+ new Variable(block.itemName, '$implicit', block.sourceSpan, block.sourceSpan),
25249
+ new Variable(getLoopLocalName(block, '$index'), '$index', block.sourceSpan, block.sourceSpan),
25250
+ new Variable(getLoopLocalName(block, '$count'), '$count', block.sourceSpan, block.sourceSpan),
25251
+ ]);
25411
25252
  const emptyData = block.empty === null ?
25412
25253
  null :
25413
25254
  this.prepareEmbeddedTemplateFn(block.empty.children, '_ForEmpty');
25414
- const trackByFn = this.createTrackByFunction(block);
25255
+ const { expression: trackByExpression, usesComponentInstance: trackByUsesComponentInstance } = this.createTrackByFunction(block);
25415
25256
  const value = block.expression.visit(this._valueConverter);
25416
25257
  this.allocateBindingSlots(value);
25258
+ this.registerComputedLoopVariables(block, primaryData.scope);
25417
25259
  // `repeaterCreate(0, ...)`
25418
25260
  this.creationInstruction(block.sourceSpan, Identifiers.repeaterCreate, () => {
25419
25261
  const params = [
@@ -25421,53 +25263,100 @@ class TemplateDefinitionBuilder {
25421
25263
  variable(primaryData.name),
25422
25264
  literal(primaryData.getConstCount()),
25423
25265
  literal(primaryData.getVarCount()),
25424
- trackByFn,
25266
+ trackByExpression,
25425
25267
  ];
25426
25268
  if (emptyData !== null) {
25427
- params.push(variable(emptyData.name), literal(emptyData.getConstCount()), literal(emptyData.getVarCount()));
25269
+ params.push(literal(trackByUsesComponentInstance), variable(emptyData.name), literal(emptyData.getConstCount()), literal(emptyData.getVarCount()));
25270
+ }
25271
+ else if (trackByUsesComponentInstance) {
25272
+ // If the tracking function doesn't use the component instance, we can omit the flag.
25273
+ params.push(literal(trackByUsesComponentInstance));
25428
25274
  }
25429
25275
  return params;
25430
25276
  });
25431
25277
  // `repeater(0, iterable)`
25432
25278
  this.updateInstruction(block.sourceSpan, Identifiers.repeater, () => [literal(blockIndex), this.convertPropertyBinding(value)]);
25433
25279
  }
25434
- createForLoopVariables(block) {
25280
+ registerComputedLoopVariables(block, bindingScope) {
25435
25281
  const indexLocalName = getLoopLocalName(block, '$index');
25436
25282
  const countLocalName = getLoopLocalName(block, '$count');
25437
- this._bindingScope.set(this.level, getLoopLocalName(block, '$odd'), scope => scope.get(indexLocalName).modulo(literal(2)).notIdentical(literal(0)));
25438
- this._bindingScope.set(this.level, getLoopLocalName(block, '$even'), scope => scope.get(indexLocalName).modulo(literal(2)).identical(literal(0)));
25439
- this._bindingScope.set(this.level, getLoopLocalName(block, '$first'), scope => scope.get(indexLocalName).identical(literal(0)));
25440
- this._bindingScope.set(this.level, getLoopLocalName(block, '$last'), scope => scope.get(indexLocalName).identical(scope.get(countLocalName).minus(literal(1))));
25441
- return [
25442
- new Variable(block.itemName, '$implicit', block.sourceSpan, block.sourceSpan),
25443
- new Variable(indexLocalName, '$index', block.sourceSpan, block.sourceSpan),
25444
- new Variable(countLocalName, '$count', block.sourceSpan, block.sourceSpan),
25445
- ];
25283
+ const level = bindingScope.bindingLevel;
25284
+ bindingScope.set(level, getLoopLocalName(block, '$odd'), scope => scope.get(indexLocalName).modulo(literal(2)).notIdentical(literal(0)));
25285
+ bindingScope.set(level, getLoopLocalName(block, '$even'), scope => scope.get(indexLocalName).modulo(literal(2)).identical(literal(0)));
25286
+ bindingScope.set(level, getLoopLocalName(block, '$first'), scope => scope.get(indexLocalName).identical(literal(0)));
25287
+ bindingScope.set(level, getLoopLocalName(block, '$last'), scope => scope.get(indexLocalName).identical(scope.get(countLocalName).minus(literal(1))));
25446
25288
  }
25447
- createTrackByFunction(block) {
25289
+ optimizeTrackByFunction(block) {
25448
25290
  const ast = block.trackBy.ast;
25449
25291
  // Top-level access of `$index` uses the built in `repeaterTrackByIndex`.
25450
25292
  if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver &&
25451
25293
  ast.name === getLoopLocalName(block, '$index')) {
25452
- return importExpr(Identifiers.repeaterTrackByIndex);
25294
+ return { expression: importExpr(Identifiers.repeaterTrackByIndex), usesComponentInstance: false };
25453
25295
  }
25454
25296
  // Top-level access of the item uses the built in `repeaterTrackByIdentity`.
25455
25297
  if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver &&
25456
25298
  ast.name === block.itemName) {
25457
- return importExpr(Identifiers.repeaterTrackByIdentity);
25299
+ return { expression: importExpr(Identifiers.repeaterTrackByIdentity), usesComponentInstance: false };
25300
+ }
25301
+ // Top-level calls in the form of `fn($index, item)` can be passed in directly.
25302
+ if (ast instanceof Call && ast.receiver instanceof PropertyRead &&
25303
+ ast.receiver.receiver instanceof ImplicitReceiver && ast.args.length === 2) {
25304
+ const firstIsIndex = ast.args[0] instanceof PropertyRead &&
25305
+ ast.args[0].receiver instanceof ImplicitReceiver &&
25306
+ ast.args[0].name === getLoopLocalName(block, '$index');
25307
+ const secondIsItem = ast.args[1] instanceof PropertyRead &&
25308
+ ast.args[1].receiver instanceof ImplicitReceiver && ast.args[1].name === block.itemName;
25309
+ if (firstIsIndex && secondIsItem) {
25310
+ // If we're in the top-level component, we can access directly through `ctx`,
25311
+ // otherwise we have to get a hold of the component through `componentInstance()`.
25312
+ const receiver = this.level === 0 ? variable(CONTEXT_NAME) :
25313
+ new ExternalExpr(Identifiers.componentInstance).callFn([]);
25314
+ return { expression: receiver.prop(ast.receiver.name), usesComponentInstance: false };
25315
+ }
25458
25316
  }
25459
- // Otherwise transpile to an inline arrow function.
25460
- if (ast instanceof PropertyRead && ast.receiver instanceof PropertyRead &&
25461
- ast.receiver.receiver instanceof ImplicitReceiver && ast.receiver.name === block.itemName) {
25462
- // TODO(crisbeto): support references outside the function scope.
25463
- const params = [getLoopLocalName(block, '$index'), block.itemName];
25464
- const scope = this._bindingScope.nestedScope(this.level + 1, new Set(params));
25465
- const binding = convertPropertyBinding(scope, variable(CONTEXT_NAME), block.trackBy, 'trackBy');
25466
- return arrowFn(params.map(param => new FnParam(param)), binding.currValExpr);
25317
+ return null;
25318
+ }
25319
+ createTrackByFunction(block) {
25320
+ const optimizedFn = this.optimizeTrackByFunction(block);
25321
+ // If the tracking function can be optimized, we don't need any further processing.
25322
+ if (optimizedFn !== null) {
25323
+ return optimizedFn;
25324
+ }
25325
+ // Referencing these requires access to the context which the tracking function
25326
+ // might not have. `$index` is special because of backwards compatibility.
25327
+ const bannedGlobals = new Set([
25328
+ getLoopLocalName(block, '$count'), getLoopLocalName(block, '$first'),
25329
+ getLoopLocalName(block, '$last'), getLoopLocalName(block, '$even'),
25330
+ getLoopLocalName(block, '$odd')
25331
+ ]);
25332
+ const scope = new TrackByBindingScope(this._bindingScope, {
25333
+ // Alias `$index` and the item name to `$index` and `$item` respectively.
25334
+ // This allows us to reuse pure functions that may have different item names,
25335
+ // but are otherwise identical.
25336
+ [getLoopLocalName(block, '$index')]: '$index',
25337
+ [block.itemName]: '$item',
25338
+ }, bannedGlobals);
25339
+ const params = [new FnParam('$index'), new FnParam('$item')];
25340
+ const stmts = convertPureComponentScopeFunction(block.trackBy.ast, scope, variable(CONTEXT_NAME), 'track');
25341
+ const usesComponentInstance = scope.getComponentAccessCount() > 0;
25342
+ let fn$1;
25343
+ if (!usesComponentInstance && stmts.length === 1 && stmts[0] instanceof ExpressionStatement) {
25344
+ fn$1 = arrowFn(params, stmts[0].expr);
25345
+ }
25346
+ else {
25347
+ // The last statement is returned implicitly.
25348
+ if (stmts.length > 0) {
25349
+ const lastStatement = stmts[stmts.length - 1];
25350
+ if (lastStatement instanceof ExpressionStatement) {
25351
+ stmts[stmts.length - 1] = new ReturnStatement(lastStatement.expr);
25352
+ }
25353
+ }
25354
+ fn$1 = fn(params, stmts);
25467
25355
  }
25468
- // TODO(crisbeto): this is a temporary restriction to land the initial implementation of the
25469
- // `for` blocks. A follow-up PR will introduce more flexibility to the `trackBy` expression.
25470
- throw new Error('Unsupported track expression');
25356
+ return {
25357
+ expression: this.constantPool.getSharedFunctionReference(fn$1, '_forTrack'),
25358
+ usesComponentInstance,
25359
+ };
25471
25360
  }
25472
25361
  getConstCount() {
25473
25362
  return this._dataIndex;
@@ -25939,6 +25828,10 @@ class BindingScope {
25939
25828
  // local var we used to store the component context, e.g. const $comp$ = x();
25940
25829
  return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
25941
25830
  }
25831
+ /** Checks whether a variable exists locally on the current scope. */
25832
+ hasLocal(name) {
25833
+ return this.map.has(name);
25834
+ }
25942
25835
  /**
25943
25836
  * Create a local variable for later reference.
25944
25837
  *
@@ -26098,6 +25991,45 @@ class BindingScope {
26098
25991
  this.usesRestoredViewContext = true;
26099
25992
  }
26100
25993
  }
25994
+ /** Binding scope of a `track` function inside a `for` loop block. */
25995
+ class TrackByBindingScope extends BindingScope {
25996
+ constructor(parentScope, globalAliases, bannedGlobals) {
25997
+ super(parentScope.bindingLevel + 1, parentScope);
25998
+ this.globalAliases = globalAliases;
25999
+ this.bannedGlobals = bannedGlobals;
26000
+ this.componentAccessCount = 0;
26001
+ }
26002
+ get(name) {
26003
+ let current = this.parent;
26004
+ // Verify that the expression isn't trying to access a variable from a parent scope.
26005
+ while (current) {
26006
+ if (current.hasLocal(name)) {
26007
+ this.forbiddenAccessError(name);
26008
+ }
26009
+ current = current.parent;
26010
+ }
26011
+ // If the variable is one of the banned globals, we have to throw.
26012
+ if (this.bannedGlobals.has(name)) {
26013
+ this.forbiddenAccessError(name);
26014
+ }
26015
+ // Intercept any aliased globals.
26016
+ if (this.globalAliases[name]) {
26017
+ return variable(this.globalAliases[name]);
26018
+ }
26019
+ // When the component scope is accessed, we redirect it through `this`.
26020
+ this.componentAccessCount++;
26021
+ return variable('this').prop(name);
26022
+ }
26023
+ /** Gets the number of times the host component has been accessed through the scope. */
26024
+ getComponentAccessCount() {
26025
+ return this.componentAccessCount;
26026
+ }
26027
+ forbiddenAccessError(propertyName) {
26028
+ // TODO(crisbeto): this should be done through template type checking once it is available.
26029
+ throw new Error(`Accessing ${propertyName} inside of a track expression is not allowed. ` +
26030
+ `Tracking expressions can only access the item, $index and properties on the containing component.`);
26031
+ }
26032
+ }
26101
26033
  /**
26102
26034
  * Creates a `CssSelector` given a tag name and a map of attributes
26103
26035
  */
@@ -26824,11 +26756,11 @@ function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindin
26824
26756
  // actually already handle these special attributes internally. Therefore, we just drop them
26825
26757
  // into the attributes map.
26826
26758
  if (hostBindingsMetadata.specialAttributes.styleAttr) {
26827
- hostBindingsMetadata.attributes.style =
26759
+ hostBindingsMetadata.attributes['style'] =
26828
26760
  literal(hostBindingsMetadata.specialAttributes.styleAttr);
26829
26761
  }
26830
26762
  if (hostBindingsMetadata.specialAttributes.classAttr) {
26831
- hostBindingsMetadata.attributes.class =
26763
+ hostBindingsMetadata.attributes['class'] =
26832
26764
  literal(hostBindingsMetadata.specialAttributes.classAttr);
26833
26765
  }
26834
26766
  const hostJob = ingestHostBinding({
@@ -27803,7 +27735,7 @@ function publishFacade(global) {
27803
27735
  * @description
27804
27736
  * Entry point for all public APIs of the compiler package.
27805
27737
  */
27806
- const VERSION = new Version('17.0.0-next.2');
27738
+ const VERSION = new Version('17.0.0-next.4');
27807
27739
 
27808
27740
  class CompilerConfig {
27809
27741
  constructor({ defaultEncapsulation = ViewEncapsulation.Emulated, useJit = true, missingTranslation = null, preserveWhitespaces, strictInjectionParameters } = {}) {
@@ -29961,7 +29893,7 @@ const MINIMUM_PARTIAL_LINKER_VERSION$6 = '12.0.0';
29961
29893
  function compileDeclareClassMetadata(metadata) {
29962
29894
  const definitionMap = new DefinitionMap();
29963
29895
  definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$6));
29964
- definitionMap.set('version', literal('17.0.0-next.2'));
29896
+ definitionMap.set('version', literal('17.0.0-next.4'));
29965
29897
  definitionMap.set('ngImport', importExpr(Identifiers.core));
29966
29898
  definitionMap.set('type', metadata.type);
29967
29899
  definitionMap.set('decorators', metadata.decorators);
@@ -30069,7 +30001,7 @@ function createDirectiveDefinitionMap(meta) {
30069
30001
  // in 16.1 is actually used.
30070
30002
  const minVersion = hasTransformFunctions ? MINIMUM_PARTIAL_LINKER_VERSION$5 : '14.0.0';
30071
30003
  definitionMap.set('minVersion', literal(minVersion));
30072
- definitionMap.set('version', literal('17.0.0-next.2'));
30004
+ definitionMap.set('version', literal('17.0.0-next.4'));
30073
30005
  // e.g. `type: MyDirective`
30074
30006
  definitionMap.set('type', meta.type.value);
30075
30007
  if (meta.isStandalone) {
@@ -30300,7 +30232,7 @@ const MINIMUM_PARTIAL_LINKER_VERSION$4 = '12.0.0';
30300
30232
  function compileDeclareFactoryFunction(meta) {
30301
30233
  const definitionMap = new DefinitionMap();
30302
30234
  definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$4));
30303
- definitionMap.set('version', literal('17.0.0-next.2'));
30235
+ definitionMap.set('version', literal('17.0.0-next.4'));
30304
30236
  definitionMap.set('ngImport', importExpr(Identifiers.core));
30305
30237
  definitionMap.set('type', meta.type.value);
30306
30238
  definitionMap.set('deps', compileDependencies(meta.deps));
@@ -30335,7 +30267,7 @@ function compileDeclareInjectableFromMetadata(meta) {
30335
30267
  function createInjectableDefinitionMap(meta) {
30336
30268
  const definitionMap = new DefinitionMap();
30337
30269
  definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$3));
30338
- definitionMap.set('version', literal('17.0.0-next.2'));
30270
+ definitionMap.set('version', literal('17.0.0-next.4'));
30339
30271
  definitionMap.set('ngImport', importExpr(Identifiers.core));
30340
30272
  definitionMap.set('type', meta.type.value);
30341
30273
  // Only generate providedIn property if it has a non-null value
@@ -30386,7 +30318,7 @@ function compileDeclareInjectorFromMetadata(meta) {
30386
30318
  function createInjectorDefinitionMap(meta) {
30387
30319
  const definitionMap = new DefinitionMap();
30388
30320
  definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$2));
30389
- definitionMap.set('version', literal('17.0.0-next.2'));
30321
+ definitionMap.set('version', literal('17.0.0-next.4'));
30390
30322
  definitionMap.set('ngImport', importExpr(Identifiers.core));
30391
30323
  definitionMap.set('type', meta.type.value);
30392
30324
  definitionMap.set('providers', meta.providers);
@@ -30419,7 +30351,7 @@ function createNgModuleDefinitionMap(meta) {
30419
30351
  throw new Error('Invalid path! Local compilation mode should not get into the partial compilation path');
30420
30352
  }
30421
30353
  definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$1));
30422
- definitionMap.set('version', literal('17.0.0-next.2'));
30354
+ definitionMap.set('version', literal('17.0.0-next.4'));
30423
30355
  definitionMap.set('ngImport', importExpr(Identifiers.core));
30424
30356
  definitionMap.set('type', meta.type.value);
30425
30357
  // We only generate the keys in the metadata if the arrays contain values.
@@ -30470,7 +30402,7 @@ function compileDeclarePipeFromMetadata(meta) {
30470
30402
  function createPipeDefinitionMap(meta) {
30471
30403
  const definitionMap = new DefinitionMap();
30472
30404
  definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION));
30473
- definitionMap.set('version', literal('17.0.0-next.2'));
30405
+ definitionMap.set('version', literal('17.0.0-next.4'));
30474
30406
  definitionMap.set('ngImport', importExpr(Identifiers.core));
30475
30407
  // e.g. `type: MyPipe`
30476
30408
  definitionMap.set('type', meta.type.value);