Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {AST, AstVisitor, ASTWithSource, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, NonNullAssert, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead, ThisReceiver, Unary} from '@angular/compiler';
import {AST, AstVisitor, ASTWithSource, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, NonNullAssert, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeKeyedRead, SafeMethodCall, SafePropertyRead, ThisReceiver, Unary} from '@angular/compiler';
import * as ts from 'typescript';

import {TypeCheckingConfig} from '../api';
Expand Down Expand Up @@ -156,15 +156,15 @@ class AstTranslator implements AstVisitor {
}

visitKeyedRead(ast: KeyedRead): ts.Expression {
const receiver = wrapForDiagnostics(this.translate(ast.obj));
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const key = this.translate(ast.key);
const node = ts.createElementAccess(receiver, key);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}

visitKeyedWrite(ast: KeyedWrite): ts.Expression {
const receiver = wrapForDiagnostics(this.translate(ast.obj));
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const left = ts.createElementAccess(receiver, this.translate(ast.key));
// TODO(joost): annotate `left` with the span of the element access, which is not currently
// available on `ast`.
Expand Down Expand Up @@ -330,6 +330,30 @@ class AstTranslator implements AstVisitor {
addParseSpanInfo(node, ast.sourceSpan);
return node;
}

visitSafeKeyedRead(ast: SafeKeyedRead): ts.Expression {
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const key = this.translate(ast.key);
let node: ts.Expression;

// The form of safe property reads depends on whether strictness is in use.
if (this.config.strictSafeNavigationTypes) {
// "a?.[...]" becomes (null as any ? a![...] : undefined)
const expr = ts.createElementAccess(ts.createNonNullExpression(receiver), key);
addParseSpanInfo(expr, ast.sourceSpan);
node = ts.createParen(ts.createConditional(NULL_AS_ANY, expr, UNDEFINED));
} else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) {
// "a?.[...]" becomes (a as any)[...]
node = ts.createElementAccess(tsCastToAny(receiver), key);
} else {
// "a?.[...]" becomes (a!.[...] as any)
const expr = ts.createElementAccess(ts.createNonNullExpression(receiver), key);
addParseSpanInfo(expr, ast.sourceSpan);
node = tsCastToAny(expr);
}
addParseSpanInfo(node, ast.sourceSpan);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this is necessary/desirable. In 2 of the 3 cases, a sub-expression is already marked with the source span of the SafeKeyedRead. It's odd to have an outer expression that's also annotated.

I think this could be refactored:

  • don't have the catch-all addParseSpanInfo, and mark the element access expression with the span inside the veWillInferAnyFor case.
  • that'll let you get rid of let node and return from inside each case instead.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have the full context here, but I was following the pattern from visitSafeMethodCall and visitSafePropertyRead right above it. Should they be refactored as well?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly, but I think that's a bigger change that should be in a different PR. For now, I think following the pattern from visitSafeMethodCall and visitSafePropertyRead is correct.

return node;
}
}

/**
Expand All @@ -348,8 +372,9 @@ class AstTranslator implements AstVisitor {
class VeSafeLhsInferenceBugDetector implements AstVisitor {
private static SINGLETON = new VeSafeLhsInferenceBugDetector();

static veWillInferAnyFor(ast: SafeMethodCall|SafePropertyRead) {
return ast.receiver.visit(VeSafeLhsInferenceBugDetector.SINGLETON);
static veWillInferAnyFor(ast: SafeMethodCall|SafePropertyRead|SafeKeyedRead) {
const visitor = VeSafeLhsInferenceBugDetector.SINGLETON;
return ast instanceof SafeKeyedRead ? ast.receiver.visit(visitor) : ast.receiver.visit(visitor);
}

visitUnary(ast: Unary): boolean {
Expand Down Expand Up @@ -418,4 +443,7 @@ class VeSafeLhsInferenceBugDetector implements AstVisitor {
visitSafePropertyRead(ast: SafePropertyRead): boolean {
return false;
}
visitSafeKeyedRead(ast: SafeKeyedRead): boolean {
return false;
}
}
29 changes: 29 additions & 0 deletions packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,35 @@ runInEachFileSystem(() => {

expect(messages).toEqual([]);
});

it('does not produce diagnostic for safe keyed access', () => {
Comment thread
crisbeto marked this conversation as resolved.
Resolved
const messages =
diagnose(`<div [class.red-text]="person.favoriteColors?.[0] === 'red'"></div>`, `
Comment thread
crisbeto marked this conversation as resolved.
Resolved
export class TestComponent {
person: {
favoriteColors?: string[];
};
}`);

expect(messages).toEqual([]);
});

it('infers a safe keyed read as undefined', () => {
const messages = diagnose(`<div (click)="log(person.favoriteColors?.[0])"></div>`, `
export class TestComponent {
person: {
favoriteColors?: string[];
};

log(color: string) {
console.log(color);
}
}`);

expect(messages).toEqual([
`TestComponent.html(1, 19): Argument of type 'string | undefined' is not assignable to parameter of type 'string'.`
]);
});
});

it('computes line and column offsets', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export function typescriptLibDts(): TestFile {
call(...args: any[]): any;
}
declare interface Array<T> {
[index: number]: T;
length: number;
}
declare interface String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -997,35 +997,39 @@ describe('type check blocks', () => {
});

describe('config.strictSafeNavigationTypes', () => {
const TEMPLATE = `{{a?.b}} {{a?.method()}}`;
const TEMPLATE = `{{a?.b}} {{a?.method()}} {{a?.[0]}}`;

it('should use undefined for safe navigation operations when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('(null as any ? (((ctx).a))!.method() : undefined)');
expect(block).toContain('(null as any ? (((ctx).a))!.b : undefined)');
expect(block).toContain('(null as any ? (((ctx).a))![0] : undefined)');
});
it('should use an \'any\' type for safe navigation operations when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, strictSafeNavigationTypes: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('((((ctx).a))!.method() as any)');
expect(block).toContain('((((ctx).a))!.b as any)');
expect(block).toContain('(((((ctx).a))![0] as any)');
});
});

describe('config.strictSafeNavigationTypes (View Engine bug emulation)', () => {
const TEMPLATE = `{{a.method()?.b}} {{a()?.method()}}`;
const TEMPLATE = `{{a.method()?.b}} {{a()?.method()}} {{a.method()?.[0]}}`;
it('should check the presence of a property/method on the receiver when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('(null as any ? ((((ctx).a)).method())!.b : undefined)');
expect(block).toContain('(null as any ? ((ctx).a())!.method() : undefined)');
expect(block).toContain('(null as any ? ((((ctx).a)).method())![0] : undefined)');
});
it('should not check the presence of a property/method on the receiver when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, strictSafeNavigationTypes: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('(((((ctx).a)).method()) as any).b');
expect(block).toContain('(((ctx).a()) as any).method()');
expect(block).toContain('(((((ctx).a)).method()) as any)[0]');
});
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/****************************************************************************************************
* PARTIAL FILE: safe_keyed_read.js
****************************************************************************************************/
import { Component, NgModule } from '@angular/core';
import * as i0 from "@angular/core";
export class MyApp {
constructor() {
this.unknownNames = null;
this.knownNames = [['Frodo', 'Bilbo']];
this.species = null;
this.keys = null;
this.speciesMap = { key: 'unknown' };
}
}
MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component });
MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, selector: "ng-component", ngImport: i0, template: `
Comment thread
crisbeto marked this conversation as resolved.
Resolved
<span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')">
Hello, {{ knownNames?.[0]?.[1] }}!
You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }}
You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }}
You are an Orc: {{ speciesMap?.['key'] }}
</span>
`, isInline: true });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{
type: Component,
args: [{
template: `
<span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')">
Hello, {{ knownNames?.[0]?.[1] }}!
You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }}
You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }}
You are an Orc: {{ speciesMap?.['key'] }}
</span>
`
}]
}] });
export class MyModule {
}
MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [MyApp] });
MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, decorators: [{
type: NgModule,
args: [{ declarations: [MyApp] }]
}] });

/****************************************************************************************************
* PARTIAL FILE: safe_keyed_read.d.ts
****************************************************************************************************/
import * as i0 from "@angular/core";
export declare class MyApp {
unknownNames: string[] | null;
knownNames: string[][];
species: null;
keys: null;
speciesMap: Record<string, string>;
static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>;
static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never>;
}
export declare class MyModule {
static ɵfac: i0.ɵɵFactoryDeclaration<MyModule, never>;
static ɵmod: i0.ɵɵNgModuleDeclaration<MyModule, [typeof MyApp], never, never>;
static ɵinj: i0.ɵɵInjectorDeclaration<MyModule>;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "../../test_case_schema.json",
"cases": [
{
"description": "should handle safe keyed reads inside templates",
"inputFiles": [
"safe_keyed_read.ts"
],
"expectations": [
{
"files": [
{
"expected": "safe_keyed_read_template.js",
"generated": "safe_keyed_read.js"
}
],
"failureMessage": "Incorrect template"
}
]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {Component, NgModule} from '@angular/core';

@Component({
template: `
<span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')">
Hello, {{ knownNames?.[0]?.[1] }}!
You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }}
You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }}
You are an Orc: {{ speciesMap?.['key'] }}
</span>
`
})
export class MyApp {
unknownNames: string[]|null = null;
knownNames: string[][] = [['Frodo', 'Bilbo']];
species = null;
keys = null;
speciesMap: Record<string, string> = {key: 'unknown'};
}

@NgModule({declarations: [MyApp]})
export class MyModule {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
template: function MyApp_Template(rf, ctx) {
if (rf & 1) {
i0.ɵɵelementStart(0, "span", 0);
i0.ɵɵtext(1);
i0.ɵɵelementEnd();
}
if (rf & 2) {
let $tmp_0_0$;
i0.ɵɵproperty("title", "Your last name is " + ((ctx.unknownNames == null ? null : ctx.unknownNames[0]) || "unknown"));
Comment thread
JoostK marked this conversation as resolved.
Resolved
i0.ɵɵadvance(1);
i0.ɵɵtextInterpolate4(" Hello, ", ctx.knownNames == null ? null : ctx.knownNames[0] == null ? null : ctx.knownNames[0][1], "! You are a Balrog: ", (ctx.species == null ? null : ctx.species[0] == null ? null : ctx.species[0][1] == null ? null : ctx.species[0][1][2] == null ? null : ctx.species[0][1][2][3] == null ? null : ctx.species[0][1][2][3][4] == null ? null : ctx.species[0][1][2][3][4][5]) || "unknown", " You are an Elf: ", ctx.speciesMap == null ? null : ctx.speciesMap[($tmp_0_0$ = ctx.keys == null ? null : ctx.keys[0]) !== null && $tmp_0_0$ !== undefined ? $tmp_0_0$ : "key"], " You are an Orc: ", ctx.speciesMap == null ? null : ctx.speciesMap["key"], " ");
}
}
28 changes: 23 additions & 5 deletions packages/compiler/src/compiler_util/expression_converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,12 +478,13 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
return this.convertSafeAccess(ast, leftMostSafe, mode);
} else {
return convertToStatementIfNeeded(
mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
mode,
this._visit(ast.receiver, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
}
}

visitKeyedWrite(ast: cdAst.KeyedWrite, mode: _Mode): any {
const obj: o.Expression = this._visit(ast.obj, _Mode.Expression);
const obj: o.Expression = this._visit(ast.receiver, _Mode.Expression);
const key: o.Expression = this._visit(ast.key, _Mode.Expression);
const value: o.Expression = this._visit(ast.value, _Mode.Expression);
return convertToStatementIfNeeded(mode, obj.key(key).set(value));
Expand Down Expand Up @@ -627,6 +628,10 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
}

visitSafeKeyedRead(ast: cdAst.SafeKeyedRead, mode: _Mode): any {
return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
}

visitAll(asts: cdAst.AST[], mode: _Mode): any {
return asts.map(ast => this._visit(ast, mode));
}
Expand All @@ -643,7 +648,8 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
}

private convertSafeAccess(
ast: cdAst.AST, leftMostSafe: cdAst.SafeMethodCall|cdAst.SafePropertyRead, mode: _Mode): any {
ast: cdAst.AST, leftMostSafe: cdAst.SafeMethodCall|cdAst.SafePropertyRead|cdAst.SafeKeyedRead,
mode: _Mode): any {
// If the expression contains a safe access node on the left it needs to be converted to
// an expression that guards the access to the member by checking the receiver for blank. As
// execution proceeds from left to right, the left most part of the expression must be guarded
Expand Down Expand Up @@ -707,6 +713,11 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan,
leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args,
leftMostSafe.argumentSpan));
} else if (leftMostSafe instanceof cdAst.SafeKeyedRead) {
this._nodeMap.set(
leftMostSafe,
new cdAst.KeyedRead(
leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.receiver, leftMostSafe.key));
} else {
this._nodeMap.set(
leftMostSafe,
Expand Down Expand Up @@ -756,7 +767,8 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
// a == null ? null : a.c.b.c?.d.e
// then to:
// a == null ? null : a.b.c == null ? null : a.b.c.d.e
private leftMostSafeNode(ast: cdAst.AST): cdAst.SafePropertyRead|cdAst.SafeMethodCall {
private leftMostSafeNode(ast: cdAst.AST): cdAst.SafePropertyRead|cdAst.SafeMethodCall
|cdAst.SafeKeyedRead {
const visit = (visitor: cdAst.AstVisitor, ast: cdAst.AST): any => {
return (this._nodeMap.get(ast) || ast).visit(visitor);
};
Expand Down Expand Up @@ -786,7 +798,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
return null;
},
visitKeyedRead(ast: cdAst.KeyedRead) {
return visit(this, ast.obj);
return visit(this, ast.receiver);
},
visitKeyedWrite(ast: cdAst.KeyedWrite) {
return null;
Expand Down Expand Up @@ -826,6 +838,9 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
},
visitSafePropertyRead(ast: cdAst.SafePropertyRead) {
return visit(this, ast.receiver) || ast;
},
visitSafeKeyedRead(ast: cdAst.SafeKeyedRead) {
return visit(this, ast.receiver) || ast;
}
});
}
Expand Down Expand Up @@ -906,6 +921,9 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
},
visitSafePropertyRead(ast: cdAst.SafePropertyRead) {
return false;
},
visitSafeKeyedRead(ast: cdAst.SafeKeyedRead) {
return false;
}
});
}
Expand Down
Loading