Skip to content

Commit

Permalink
fix(compiler): emits quoted keys only iff they are quoted in the orig…
Browse files Browse the repository at this point in the history
…inal template

fixes #14292
  • Loading branch information
vicb authored and jasonaden committed Jul 8, 2017
1 parent 5ea9b62 commit 45ae14c
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 54 deletions.
16 changes: 7 additions & 9 deletions packages/compiler-cli/test/transformers/node_emitter_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const sameModuleIdentifier = new o.ExternalReference(null, 'someLocalId', null);

const externalModuleIdentifier = new o.ExternalReference(anotherModuleUrl, 'someExternalId', null);

describe('TypeScriptEmitter', () => {
describe('TypeScriptNodeEmitter', () => {
let context: MockAotContext;
let host: MockCompilerHost;
let emitter: TypeScriptNodeEmitter;
Expand Down Expand Up @@ -167,15 +167,13 @@ describe('TypeScriptEmitter', () => {
expect(emitStmt(o.literal(true).toStmt())).toEqual('true;');
expect(emitStmt(o.literal('someStr').toStmt())).toEqual(`"someStr";`);
expect(emitStmt(o.literalArr([o.literal(1)]).toStmt())).toEqual(`[1];`);
expect(emitStmt(o.literalMap([['someKey', o.literal(1)]]).toStmt()))
.toEqual(`({ someKey: 1 });`);
});

it('should apply quotes to each entry within a map produced with literalMap when true', () => {
expect(emitStmt(
o.literalMap([['a', o.literal('a')], ['*', o.literal('star')]], null, true).toStmt())
expect(emitStmt(o.literalMap([
{key: 'someKey', value: o.literal(1), quoted: false},
{key: 'a', value: o.literal('a'), quoted: false},
{key: '*', value: o.literal('star'), quoted: true},
]).toStmt())
.replace(/\s+/gm, ''))
.toEqual(`({"a":"a","*":"star"});`);
.toEqual(`({someKey:1,a:"a","*":"star"});`);
});

it('should support blank literals', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/aot/summary_serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ class ForJitSerializer {
}
visitStringMap(map: {[key: string]: any}, context: any): any {
return new o.LiteralMapExpr(Object.keys(map).map(
(key) => new o.LiteralMapEntry(key, visitValue(map[key], this, context))));
(key) => new o.LiteralMapEntry(key, visitValue(map[key], this, context), false)));
}
visitPrimitive(value: any, context: any): any { return o.literal(value); }
visitOther(value: any, context: any): any {
Expand Down
15 changes: 11 additions & 4 deletions packages/compiler/src/compiler_util/expression_converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,16 @@ export function convertActionBinding(
// Note: no caching for literal arrays in actions.
return (args: o.Expression[]) => o.literalArr(args);
},
createLiteralMapConverter: (keys: string[]) => {
createLiteralMapConverter: (keys: {key: string, quoted: boolean}[]) => {
// Note: no caching for literal maps in actions.
return (args: o.Expression[]) =>
o.literalMap(<[string, o.Expression][]>keys.map((key, i) => [key, args[i]]));
return (values: o.Expression[]) => {
const entries = keys.map((k, i) => ({
key: k.key,
value: values[i],
quoted: k.quoted,
}));
return o.literalMap(entries);
};
},
createPipeConverter: (name: string) => {
throw new Error(`Illegal State: Actions are not allowed to contain pipes. Pipe: ${name}`);
Expand Down Expand Up @@ -71,7 +77,7 @@ export interface BuiltinConverter { (args: o.Expression[]): o.Expression; }

export interface BuiltinConverterFactory {
createLiteralArrayConverter(argCount: number): BuiltinConverter;
createLiteralMapConverter(keys: string[]): BuiltinConverter;
createLiteralMapConverter(keys: {key: string, quoted: boolean}[]): BuiltinConverter;
createPipeConverter(name: string, argCount: number): BuiltinConverter;
}

Expand Down Expand Up @@ -169,6 +175,7 @@ class _BuiltinAstConverter extends cdAst.AstTransformer {
}
visitLiteralMap(ast: cdAst.LiteralMap, context: any): any {
const args = ast.values.map(ast => ast.visit(this, context));

return new BuiltinFunctionCall(
ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
}
Expand Down
10 changes: 5 additions & 5 deletions packages/compiler/src/output/output_ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ export class LiteralArrayExpr extends Expression {
}

export class LiteralMapEntry {
constructor(public key: string, public value: Expression, public quoted: boolean = false) {}
constructor(public key: string, public value: Expression, public quoted: boolean) {}
}

export class LiteralMapExpr extends Expression {
Expand Down Expand Up @@ -831,7 +831,7 @@ export class AstTransformer implements StatementVisitor, ExpressionVisitor {
visitLiteralMapExpr(ast: LiteralMapExpr, context: any): any {
const entries = ast.entries.map(
(entry): LiteralMapEntry => new LiteralMapEntry(
entry.key, entry.value.visitExpression(this, context), entry.quoted, ));
entry.key, entry.value.visitExpression(this, context), entry.quoted));
const mapType = new MapType(ast.valueType, null);
return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
}
Expand Down Expand Up @@ -1151,10 +1151,10 @@ export function literalArr(
}

export function literalMap(
values: [string, Expression][], type: MapType | null = null,
quoted: boolean = false): LiteralMapExpr {
values: {key: string, quoted: boolean, value: Expression}[],
type: MapType | null = null): LiteralMapExpr {
return new LiteralMapExpr(
values.map(entry => new LiteralMapEntry(entry[0], entry[1], quoted)), type, null);
values.map(e => new LiteralMapEntry(e.key, e.value, e.quoted)), type, null);
}

export function not(expr: Expression, sourceSpan?: ParseSourceSpan | null): NotExpr {
Expand Down
5 changes: 2 additions & 3 deletions packages/compiler/src/output/output_interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,8 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return this.visitAllExpressions(ast.entries, ctx);
}
visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: _ExecutionContext): any {
const result = {};
ast.entries.forEach(
(entry) => (result as any)[entry.key] = entry.value.visitExpression(this, ctx));
const result: {[k: string]: any} = {};
ast.entries.forEach(entry => result[entry.key] = entry.value.visitExpression(this, ctx));
return result;
}
visitCommaExpr(ast: o.CommaExpr, context: any): any {
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/output/output_jit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class JitEmitterVisitor extends AbstractJsEmitterVisitor {

createReturnStmt(ctx: EmitterVisitorContext) {
const stmt = new o.ReturnStatement(new o.LiteralMapExpr(this._evalExportedVars.map(
resultVar => new o.LiteralMapEntry(resultVar, o.variable(resultVar)))));
resultVar => new o.LiteralMapEntry(resultVar, o.variable(resultVar), false))));
stmt.visitStatement(this, ctx);
}

Expand Down
28 changes: 16 additions & 12 deletions packages/compiler/src/view_compiler/view_compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ export class ViewCompiler {
outputCtx.statements.push(
renderComponentVar
.set(o.importExpr(Identifiers.createRendererType2).callFn([new o.LiteralMapExpr([
new o.LiteralMapEntry('encapsulation', o.literal(template.encapsulation)),
new o.LiteralMapEntry('styles', styles),
new o.LiteralMapEntry('data', new o.LiteralMapExpr(customRenderData))
new o.LiteralMapEntry('encapsulation', o.literal(template.encapsulation), false),
new o.LiteralMapEntry('styles', styles, false),
new o.LiteralMapEntry('data', new o.LiteralMapExpr(customRenderData), false)
])]))
.toDeclStmt(
o.importType(Identifiers.RendererType2),
Expand Down Expand Up @@ -160,8 +160,8 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver {
nodeFlags: flags,
nodeDef: o.importExpr(Identifiers.queryDef).callFn([
o.literal(flags), o.literal(queryId),
new o.LiteralMapExpr(
[new o.LiteralMapEntry(query.propertyName, o.literal(bindingType))])
new o.LiteralMapExpr([new o.LiteralMapEntry(
query.propertyName, o.literal(bindingType), false)])
])
}));
});
Expand Down Expand Up @@ -504,8 +504,8 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver {
nodeFlags: flags,
nodeDef: o.importExpr(Identifiers.queryDef).callFn([
o.literal(flags), o.literal(queryId),
new o.LiteralMapExpr(
[new o.LiteralMapEntry(query.propertyName, o.literal(bindingType))])
new o.LiteralMapExpr([new o.LiteralMapEntry(
query.propertyName, o.literal(bindingType), false)])
]),
}));
});
Expand Down Expand Up @@ -705,23 +705,26 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver {

return (args: o.Expression[]) => callCheckStmt(nodeIndex, args);
}
createLiteralMapConverter(sourceSpan: ParseSourceSpan, keys: string[]): BuiltinConverter {

createLiteralMapConverter(sourceSpan: ParseSourceSpan, keys: {key: string, quoted: boolean}[]):
BuiltinConverter {
if (keys.length === 0) {
const valueExpr = o.importExpr(Identifiers.EMPTY_MAP);
return () => valueExpr;
}

// function pureObjectDef(propToIndex: {[p: string]: number}): NodeDef
const map = o.literalMap(keys.map((e, i) => ({...e, value: o.literal(i)})));
const nodeIndex = this.nodes.length;
// function pureObjectDef(propertyNames: string[]): NodeDef
this.nodes.push(() => ({
sourceSpan,
nodeFlags: NodeFlags.TypePureObject,
nodeDef: o.importExpr(Identifiers.pureObjectDef).callFn([o.literalArr(
keys.map(key => o.literal(key)))])
nodeDef: o.importExpr(Identifiers.pureObjectDef).callFn([map])
}));

return (args: o.Expression[]) => callCheckStmt(nodeIndex, args);
}

createPipeConverter(expression: UpdateExpression, name: string, argCount: number):
BuiltinConverter {
const pipe = this.usedPipes.find((pipeSummary) => pipeSummary.name === name) !;
Expand Down Expand Up @@ -795,7 +798,8 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver {
createLiteralArrayConverter: (argCount: number) => this.createLiteralArrayConverter(
expression.sourceSpan, argCount),
createLiteralMapConverter:
(keys: string[]) => this.createLiteralMapConverter(expression.sourceSpan, keys),
(keys: {key: string, quoted: boolean}[]) =>
this.createLiteralMapConverter(expression.sourceSpan, keys),
createPipeConverter: (name: string, argCount: number) =>
this.createPipeConverter(expression, name, argCount)
},
Expand Down
8 changes: 7 additions & 1 deletion packages/compiler/test/output/js_emitter_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,13 @@ export function main() {
expect(emitStmt(o.literal(true).toStmt())).toEqual('true;');
expect(emitStmt(o.literal('someStr').toStmt())).toEqual(`'someStr';`);
expect(emitStmt(o.literalArr([o.literal(1)]).toStmt())).toEqual(`[1];`);
expect(emitStmt(o.literalMap([['someKey', o.literal(1)]]).toStmt())).toEqual(`{someKey:1};`);
expect(emitStmt(o.literalMap([
{key: 'someKey', value: o.literal(1), quoted: false},
{key: 'a', value: o.literal('a'), quoted: false},
{key: '*', value: o.literal('star'), quoted: true},
]).toStmt())
.replace(/\s+/gm, ''))
.toEqual(`{someKey:1,a:'a','*':'star'};`);
});

it('should break expressions into multiple lines if they are too long', () => {
Expand Down
16 changes: 7 additions & 9 deletions packages/compiler/test/output/ts_emitter_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,13 @@ export function main() {
expect(emitStmt(o.literal(true).toStmt())).toEqual('true;');
expect(emitStmt(o.literal('someStr').toStmt())).toEqual(`'someStr';`);
expect(emitStmt(o.literalArr([o.literal(1)]).toStmt())).toEqual(`[1];`);
expect(emitStmt(o.literalMap([['someKey', o.literal(1)]]).toStmt())).toEqual(`{someKey:1};`);
expect(emitStmt(o.literalMap([
{key: 'someKey', value: o.literal(1), quoted: false},
{key: 'a', value: o.literal('a'), quoted: false},
{key: '*', value: o.literal('star'), quoted: true},
]).toStmt())
.replace(/\s+/gm, ''))
.toEqual(`{someKey:1,a:'a','*':'star'};`);
});

it('should break expressions into multiple lines if they are too long', () => {
Expand All @@ -166,14 +172,6 @@ export function main() {
].join('\n'));
});

it('should apply quotes to each entry within a map produced with literalMap when true', () => {
expect(
emitStmt(
o.literalMap([['a', o.literal('a')], ['*', o.literal('star')]], null, true).toStmt())
.replace(/\s+/gm, ''))
.toEqual(`{'a':'a','*':'star'};`);
});

it('should support blank literals', () => {
expect(emitStmt(o.literal(null).toStmt())).toEqual('(null as any);');
expect(emitStmt(o.literal(undefined).toStmt())).toEqual('(undefined as any);');
Expand Down
11 changes: 10 additions & 1 deletion packages/core/src/view/pure_expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@ export function pureArrayDef(argCount: number): NodeDef {
return _pureExpressionDef(NodeFlags.TypePureArray, new Array(argCount));
}

export function pureObjectDef(propertyNames: string[]): NodeDef {
export function pureObjectDef(propToIndex: {[p: string]: number}): NodeDef {
const keys = Object.keys(propToIndex);
const nbKeys = keys.length;
const propertyNames = new Array(nbKeys);
for (let i = 0; i < nbKeys; i++) {
const key = keys[i];
const index = propToIndex[key];
propertyNames[index] = key;
}

return _pureExpressionDef(NodeFlags.TypePureObject, propertyNames);
}

Expand Down
17 changes: 9 additions & 8 deletions packages/core/test/view/pure_expression_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/

import {Injector, PipeTransform, RenderComponentType, RootRenderer, Sanitizer, SecurityContext, ViewEncapsulation, WrappedValue} from '@angular/core';
import {ArgumentType, NodeDef, NodeFlags, RootData, Services, ViewData, ViewDefinition, ViewFlags, ViewHandleEventFn, ViewUpdateFn, anchorDef, asProviderData, asPureExpressionData, directiveDef, elementDef, nodeValue, pipeDef, pureArrayDef, pureObjectDef, purePipeDef, rootRenderNodes, textDef, viewDef} from '@angular/core/src/view/index';
import {inject} from '@angular/core/testing';
import {PipeTransform} from '@angular/core';
import {NodeDef, NodeFlags, Services, ViewData, ViewDefinition, ViewFlags, ViewUpdateFn, asProviderData, directiveDef, elementDef, nodeValue, pipeDef, pureArrayDef, pureObjectDef, purePipeDef, rootRenderNodes, viewDef} from '@angular/core/src/view/index';

import {ARG_TYPE_VALUES, checkNodeInlineOrDynamic, createRootView} from './helper';

Expand Down Expand Up @@ -38,8 +37,9 @@ export function main() {

const {view, rootNodes} = createAndGetRootNodes(compViewDef(
[
elementDef(NodeFlags.None, null !, null !, 2, 'span'), pureArrayDef(2),
directiveDef(NodeFlags.None, null !, 0, Service, [], {data: [0, 'data']})
elementDef(NodeFlags.None, null !, null !, 2, 'span'),
pureArrayDef(2),
directiveDef(NodeFlags.None, null !, 0, Service, [], {data: [0, 'data']}),
],
(check, view) => {
const pureValue = checkNodeInlineOrDynamic(check, view, 1, inlineDynamic, values);
Expand Down Expand Up @@ -75,7 +75,7 @@ export function main() {

const {view, rootNodes} = createAndGetRootNodes(compViewDef(
[
elementDef(NodeFlags.None, null !, null !, 2, 'span'), pureObjectDef(['a', 'b']),
elementDef(NodeFlags.None, null !, null !, 2, 'span'), pureObjectDef({a: 0, b: 1}),
directiveDef(NodeFlags.None, null !, 0, Service, [], {data: [0, 'data']})
],
(check, view) => {
Expand Down Expand Up @@ -116,8 +116,9 @@ export function main() {
const {view, rootNodes} = createAndGetRootNodes(compViewDef(
[
elementDef(NodeFlags.None, null !, null !, 3, 'span'),
pipeDef(NodeFlags.None, SomePipe, []), purePipeDef(2),
directiveDef(NodeFlags.None, null !, 0, Service, [], {data: [0, 'data']})
pipeDef(NodeFlags.None, SomePipe, []),
purePipeDef(2),
directiveDef(NodeFlags.None, null !, 0, Service, [], {data: [0, 'data']}),
],
(check, view) => {
const pureValue = checkNodeInlineOrDynamic(
Expand Down

0 comments on commit 45ae14c

Please sign in to comment.