From 13618ea551884682ec00dcd2aad305d3ec585fe9 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Wed, 16 Sep 2026 09:56:23 +0200 Subject: [PATCH] refactor(compiler): handle increment/decrement operators in template type checker Updates the template type checker to handle the `++` and `--` operators. --- .../typecheck/src/template_symbol_builder.ts | 28 ++++++--- .../src/template_semantics_checker.ts | 16 +++++ .../typecheck/test/type_check_block_spec.ts | 20 ++++++ ...ecker__get_symbol_of_template_node_spec.ts | 42 +++++++++++++ .../test/ngtsc/template_typecheck_spec.ts | 62 +++++++++++++++++++ packages/compiler/src/typecheck/expression.ts | 6 +- .../compiler/src/typecheck/ops/expression.ts | 35 ++++++++--- 7 files changed, 193 insertions(+), 16 deletions(-) diff --git a/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts b/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts index 113e34e6795..96246876fec 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts @@ -32,6 +32,8 @@ import { TmplAstTextAttribute, TmplAstVariable, TypeCheckingConfig, + Unary, + unwrapWriteTarget, } from '@angular/compiler'; import ts from 'typescript'; @@ -663,14 +665,26 @@ export class SymbolBuilder { let withSpan = expression.sourceSpan; + // Whether `withSpan` points at a property read, in which case the search below should look + // for a `PropertyAccessExpression` rather than settling for whichever node comes first. + let isPropertyRead = expression instanceof PropertyRead; + // The `name` part of a property write and `ASTWithName` do not have their own // AST so there is no way to retrieve a `Symbol` for just the `name` via a specific node. - if ( - expression instanceof Binary && - Binary.isAssignmentOperation(expression.operation) && - expression.left instanceof PropertyRead - ) { - withSpan = expression.left.nameSpan; + if (expression instanceof Binary && Binary.isAssignmentOperation(expression.operation)) { + const target = unwrapWriteTarget(expression.left); + if (target instanceof PropertyRead) { + withSpan = target.nameSpan; + isPropertyRead = true; + } + } else if (expression instanceof Unary && Unary.isUpdateOperation(expression.operator)) { + // The target of an update operator can be wrapped in parentheses or a non-null assertion + // (e.g. `(value)++` or `value!++`), neither of which affect what is being written to. + const target = unwrapWriteTarget(expression.expr); + if (target instanceof PropertyRead) { + withSpan = target.nameSpan; + isPropertyRead = true; + } } else if ( expression instanceof ASTWithName && !(expression instanceof SafePropertyRead) && @@ -683,7 +697,7 @@ export class SymbolBuilder { // Property reads in templates usually map to a `PropertyAccessExpression` // (e.g. `ctx.foo`) so try looking for one first. - if (expression instanceof PropertyRead || expression instanceof SafePropertyRead) { + if (isPropertyRead || expression instanceof SafePropertyRead) { node = findFirstMatchingNode(this.typeCheckBlock, { withSpan, filter: ts.isPropertyAccessExpression, diff --git a/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.ts b/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.ts index d880b807198..0971daf52d2 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.ts @@ -20,6 +20,8 @@ import { TmplAstRecursiveVisitor, TmplAstVariable, ThisReceiver, + Unary, + unwrapWriteTarget, } from '@angular/compiler'; import ts from 'typescript'; @@ -85,6 +87,20 @@ class ExpressionsSemanticsVisitor extends RecursiveAstVisitor { } } + override visitUnary(ast: Unary, context: TmplAstNode): void { + if (Unary.isUpdateOperation(ast.operator)) { + // The target of an update operator can be wrapped in parentheses or a non-null assertion + // (e.g. `(value)++` or `value!++`), neither of which affect what is being written to. + const target = unwrapWriteTarget(ast.expr); + + if (target instanceof PropertyRead) { + this.checkForIllegalWriteInEventBinding(target, context); + } + } + + super.visitUnary(ast, context); + } + override visitPropertyRead(ast: PropertyRead, context: TmplAstNode) { super.visitPropertyRead(ast, context); this.checkForIllegalWriteInTwoWayBinding(ast, context); diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts index da962528979..cc9bc45b910 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts @@ -117,6 +117,10 @@ describe('type check blocks', () => { expect(tcb('')).toContain('(((this).a)) &&= (((this).b));'); expect(tcb('')).toContain('(((this).a)) ||= (((this).b));'); expect(tcb('')).toContain('(((this).a)) ??= (((this).b));'); + expect(tcb('')).toContain('(((this).a)++)'); + expect(tcb('')).toContain('(((this).a)--)'); + expect(tcb('')).toContain('(++((this).a))'); + expect(tcb('')).toContain('(--((this).a))'); }); it('should handle exponentiation expressions', () => { @@ -126,6 +130,12 @@ describe('type check blocks', () => { expect(tcb('{{a ** b ** c}}')).toContain('((((this).a)) ** (((((this).b)) ** (((this).c)))))'); }); + it('should handle update expressions as operands of an exponentiation expression', () => { + expect(tcb('')).toContain('(((((this).a)++)) ** (2));'); + expect(tcb('')).toContain('(((++((this).a))) ** (2));'); + expect(tcb('')).toContain('((2) ** ((((this).a)--)));'); + }); + it('should handle "in" expressions', () => { expect(tcb(`{{'bar' in {bar: 'bar'} }}`)).toContain(`(("bar") in (({ "bar": "bar" })))`); expect(tcb(`{{!('bar' in {bar: 'bar'}) }}`)).toContain(`!((("bar") in (({ "bar": "bar" }))))`); @@ -2482,6 +2492,16 @@ describe('type check blocks', () => { '_t2.addEventListener("click", ($event): any => { (this).doStuff(_t1); });', ); }); + + it('should rewrite writes to let declarations with update operators', () => { + const result = tcb(` + @let value = 1; + + `); + + expect(result).toContain('const _t1 = (1);'); + expect(result).toContain('(_t1++)'); + }); }); describe('arrow functions', () => { diff --git a/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts b/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts index e33fcc315c7..d4144ed9554 100644 --- a/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts +++ b/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts @@ -1445,6 +1445,48 @@ runInEachFileSystem(() => { ).toEqual('any'); }); + it('should get a symbol for update expressions', () => { + const fileName = absoluteFrom('/main.ts'); + const {templateTypeChecker, program} = setup([ + { + fileName, + templates: { + 'Cmp': ` +
+
+
+
+ `, + }, + source: `export class Cmp { counter = 0; }`, + }, + ]); + const sf = getSourceFileOrError(program, fileName); + const cmp = getClass(sf, 'Cmp'); + const nodes = getAstElements(templateTypeChecker, cmp); + + // As with `PropertyWrite`, the symbol of an update expression is the symbol of the + // value being updated. The target may be wrapped in parentheses or a non-null + // assertion, neither of which changes what is being written to. + for (const node of nodes) { + const output = node.outputs[0]; + const symbol = templateTypeChecker.getSymbolOfNode(output.handler, cmp)!; + assertExpressionSymbol(symbol); + expect( + program + .getTypeChecker() + .symbolToString(templateTypeChecker.getTsSymbolOfSymbol(symbol)!), + ) + .withContext(`symbol for (${output.name})`) + .toEqual('counter'); + expect( + program.getTypeChecker().typeToString(templateTypeChecker.getTypeOfSymbol(symbol)!), + ) + .withContext(`type for (${output.name})`) + .toEqual('number'); + } + }); + it('should get a symbol for Call expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ diff --git a/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts b/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts index f44efc571fe..9fa161810c3 100644 --- a/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts +++ b/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts @@ -2256,6 +2256,44 @@ runInEachFileSystem(() => { expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); }); + it('should type check increment/decrement operations', () => { + env.write( + 'test.ts', + ` + import {Component} from '@angular/core'; + + @Component({template: ''}) + class TestCmp { + name = 'frodo'; + } + `, + ); + + const diags = env.driveDiagnostics(); + expect(diags.length).toBe(1); + expect(diags[0].messageText).toEqual( + `An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.`, + ); + }); + + it('should type check increment/decrement targets', () => { + env.write( + 'test.ts', + ` + import {Component} from '@angular/core'; + + @Component({template: ''}) + class TestCmp {} + `, + ); + + const diags = env.driveDiagnostics(); + expect(diags.length).toBe(1); + expect(diags[0].messageText).toEqual( + `Property 'doesNotExist' does not exist on type 'TestCmp'.`, + ); + }); + describe('microsyntax variables', () => { beforeEach(() => { // Use the same template for both tests @@ -8878,6 +8916,30 @@ suppress expect(diags[0].messageText).toBe(`Cannot assign to @let declaration 'value'.`); }); + it('should not allow a let declaration value to be changed through update operators', () => { + env.write( + 'test.ts', + ` + import {Component} from '@angular/core'; + + @Component({ + template: \` + @let value = 1; + + + \`, + }) + export class Main { + } + `, + ); + + const diags = env.driveDiagnostics(); + expect(diags.length).toBe(2); + expect(diags[0].messageText).toBe(`Cannot assign to @let declaration 'value'.`); + expect(diags[1].messageText).toBe(`Cannot assign to @let declaration 'value'.`); + }); + it('should not allow a let declaration value to be changed through a `this` access', () => { env.write( 'test.ts', diff --git a/packages/compiler/src/typecheck/expression.ts b/packages/compiler/src/typecheck/expression.ts index 0d63e9ebfee..c4fe4876f57 100644 --- a/packages/compiler/src/typecheck/expression.ts +++ b/packages/compiler/src/typecheck/expression.ts @@ -76,8 +76,10 @@ class TcbExprTranslator implements AstVisitor { } visitUnary(ast: Unary): TcbExpr { - const expr = this.translate(ast.expr); - const node = new TcbExpr(`${ast.operator}${expr.print()}`); + // Note that we don't need to guard against sequences like `+ +a` collapsing into `++a`, + // because `wrapForTypeChecker` always parenthesizes nested unary expressions. + const expr = this.translate(ast.expr).print(); + const node = new TcbExpr(ast.isPrefix ? `${ast.operator}${expr}` : `${expr}${ast.operator}`); return node.wrapForTypeChecker().addParseSpanInfo(ast.sourceSpan); } diff --git a/packages/compiler/src/typecheck/ops/expression.ts b/packages/compiler/src/typecheck/ops/expression.ts index a61db390b6a..7c0fe70985e 100644 --- a/packages/compiler/src/typecheck/ops/expression.ts +++ b/packages/compiler/src/typecheck/ops/expression.ts @@ -16,6 +16,8 @@ import { SafeCall, SafePropertyRead, ThisReceiver, + Unary, + unwrapWriteTarget, } from '../../expression_parser/ast'; import {LetDeclaration} from '../../render3/r3_ast'; import {Identifiers as R3Identifiers} from '../../render3/r3_identifiers'; @@ -138,20 +140,39 @@ export class TcbExpressionTranslator { return targetExpression; } else if ( - ast instanceof Binary && - Binary.isAssignmentOperation(ast.operation) && - ast.left instanceof PropertyRead && - (ast.left.receiver instanceof ImplicitReceiver || ast.left.receiver instanceof ThisReceiver) + (ast instanceof Binary && Binary.isAssignmentOperation(ast.operation)) || + (ast instanceof Unary && Unary.isUpdateOperation(ast.operator)) ) { - const read = ast.left; + const update = ast instanceof Unary ? ast : null; + + const read = unwrapWriteTarget(update !== null ? update.expr : ast.left); + + if ( + !(read instanceof PropertyRead) || + !(read.receiver instanceof ImplicitReceiver || read.receiver instanceof ThisReceiver) + ) { + return null; + } + const target = this.tcb.boundTarget.getExpressionTarget(read); if (target === null) { return null; } const targetExpression = this.getTargetNodeExpression(target, read); - const expr = this.translate(ast.right); - const result = new TcbExpr(`(${targetExpression.print()} = ${expr.print()})`); + let result: TcbExpr; + + if (update !== null) { + result = new TcbExpr( + update.isPrefix + ? `(${update.operator}${targetExpression.print()})` + : `(${targetExpression.print()}${update.operator})`, + ); + } else { + const expr = this.translate(ast.right); + result = new TcbExpr(`(${targetExpression.print()} = ${expr.print()})`); + } + result.addParseSpanInfo(read.sourceSpan); // Ignore diagnostics from TS produced for writes to `@let` and re-report them using