refactor(compiler): handle increment/decrement operators in template type checker

Updates the template type checker to handle the `++` and `--` operators.
This commit is contained in:
Kristiyan Kostadinov
2026-09-25 15:41:50 -07:00
committed by Andrew Scott
parent ead4f0f56d
commit 13618ea551
7 changed files with 193 additions and 16 deletions
@@ -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,
@@ -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);
@@ -117,6 +117,10 @@ describe('type check blocks', () => {
expect(tcb('<b (click)="a &&= b"></b>')).toContain('(((this).a)) &&= (((this).b));');
expect(tcb('<b (click)="a ||= b"></b>')).toContain('(((this).a)) ||= (((this).b));');
expect(tcb('<b (click)="a ??= b"></b>')).toContain('(((this).a)) ??= (((this).b));');
expect(tcb('<b (click)="a++"></b>')).toContain('(((this).a)++)');
expect(tcb('<b (click)="a--"></b>')).toContain('(((this).a)--)');
expect(tcb('<b (click)="++a"></b>')).toContain('(++((this).a))');
expect(tcb('<b (click)="--a"></b>')).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('<b (click)="a++ ** 2"></b>')).toContain('(((((this).a)++)) ** (2));');
expect(tcb('<b (click)="++a ** 2"></b>')).toContain('(((++((this).a))) ** (2));');
expect(tcb('<b (click)="2 ** a--"></b>')).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;
<button (click)="value++"></button>
`);
expect(result).toContain('const _t1 = (1);');
expect(result).toContain('(_t1++)');
});
});
describe('arrow functions', () => {
@@ -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': `
<div (a)="counter++"></div>
<div (b)="--counter"></div>
<div (c)="(counter)++"></div>
<div (d)="counter!++"></div>
`,
},
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([
@@ -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: '<button (click)="name++"></button>'})
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: '<button (click)="doesNotExist++"></button>'})
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;
<button (click)="value++">Click me</button>
<button (click)="--value">Click me</button>
\`,
})
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',
@@ -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);
}
@@ -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