-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
translator.ts
787 lines (684 loc) Β· 32.4 KB
/
translator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ArrayType, AssertNotNull, BinaryOperator, BinaryOperatorExpr, BuiltinType, BuiltinTypeName, CastExpr, ClassStmt, CommaExpr, CommentStmt, ConditionalExpr, DeclareFunctionStmt, DeclareVarStmt, Expression, ExpressionStatement, ExpressionType, ExpressionVisitor, ExternalExpr, FunctionExpr, IfStmt, InstantiateExpr, InvokeFunctionExpr, InvokeMethodExpr, JSDocCommentStmt, LiteralArrayExpr, LiteralExpr, LiteralMapExpr, MapType, NotExpr, ParseSourceSpan, ReadKeyExpr, ReadPropExpr, ReadVarExpr, ReturnStatement, Statement, StatementVisitor, StmtModifier, ThrowStmt, TryCatchStmt, Type, TypeofExpr, TypeVisitor, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr} from '@angular/compiler';
import {LocalizedString, UnaryOperator, UnaryOperatorExpr} from '@angular/compiler/src/output/output_ast';
import * as ts from 'typescript';
import {DefaultImportRecorder, ImportRewriter, NOOP_DEFAULT_IMPORT_RECORDER, NoopImportRewriter} from '../../imports';
export class Context {
constructor(readonly isStatement: boolean) {}
get withExpressionMode(): Context {
return this.isStatement ? new Context(false) : this;
}
get withStatementMode(): Context {
return !this.isStatement ? new Context(true) : this;
}
}
const UNARY_OPERATORS = new Map<UnaryOperator, ts.PrefixUnaryOperator>([
[UnaryOperator.Minus, ts.SyntaxKind.MinusToken],
[UnaryOperator.Plus, ts.SyntaxKind.PlusToken],
]);
const BINARY_OPERATORS = new Map<BinaryOperator, ts.BinaryOperator>([
[BinaryOperator.And, ts.SyntaxKind.AmpersandAmpersandToken],
[BinaryOperator.Bigger, ts.SyntaxKind.GreaterThanToken],
[BinaryOperator.BiggerEquals, ts.SyntaxKind.GreaterThanEqualsToken],
[BinaryOperator.BitwiseAnd, ts.SyntaxKind.AmpersandToken],
[BinaryOperator.Divide, ts.SyntaxKind.SlashToken],
[BinaryOperator.Equals, ts.SyntaxKind.EqualsEqualsToken],
[BinaryOperator.Identical, ts.SyntaxKind.EqualsEqualsEqualsToken],
[BinaryOperator.Lower, ts.SyntaxKind.LessThanToken],
[BinaryOperator.LowerEquals, ts.SyntaxKind.LessThanEqualsToken],
[BinaryOperator.Minus, ts.SyntaxKind.MinusToken],
[BinaryOperator.Modulo, ts.SyntaxKind.PercentToken],
[BinaryOperator.Multiply, ts.SyntaxKind.AsteriskToken],
[BinaryOperator.NotEquals, ts.SyntaxKind.ExclamationEqualsToken],
[BinaryOperator.NotIdentical, ts.SyntaxKind.ExclamationEqualsEqualsToken],
[BinaryOperator.Or, ts.SyntaxKind.BarBarToken],
[BinaryOperator.Plus, ts.SyntaxKind.PlusToken],
]);
/**
* Information about an import that has been added to a module.
*/
export interface Import {
/** The name of the module that has been imported. */
specifier: string;
/** The alias of the imported module. */
qualifier: string;
}
/**
* The symbol name and import namespace of an imported symbol,
* which has been registered through the ImportManager.
*/
export interface NamedImport {
/** The import namespace containing this imported symbol. */
moduleImport: string|null;
/** The (possibly rewritten) name of the imported symbol. */
symbol: string;
}
export class ImportManager {
private specifierToIdentifier = new Map<string, string>();
private nextIndex = 0;
constructor(protected rewriter: ImportRewriter = new NoopImportRewriter(), private prefix = 'i') {
}
generateNamedImport(moduleName: string, originalSymbol: string): NamedImport {
// First, rewrite the symbol name.
const symbol = this.rewriter.rewriteSymbol(originalSymbol, moduleName);
// Ask the rewriter if this symbol should be imported at all. If not, it can be referenced
// directly (moduleImport: null).
if (!this.rewriter.shouldImportSymbol(symbol, moduleName)) {
// The symbol should be referenced directly.
return {moduleImport: null, symbol};
}
// If not, this symbol will be imported. Allocate a prefix for the imported module if needed.
if (!this.specifierToIdentifier.has(moduleName)) {
this.specifierToIdentifier.set(moduleName, `${this.prefix}${this.nextIndex++}`);
}
const moduleImport = this.specifierToIdentifier.get(moduleName)!;
return {moduleImport, symbol};
}
getAllImports(contextPath: string): Import[] {
const imports: {specifier: string, qualifier: string}[] = [];
this.specifierToIdentifier.forEach((qualifier, specifier) => {
specifier = this.rewriter.rewriteSpecifier(specifier, contextPath);
imports.push({specifier, qualifier});
});
return imports;
}
}
export function translateExpression(
expression: Expression, imports: ImportManager, defaultImportRecorder: DefaultImportRecorder,
scriptTarget: Exclude<ts.ScriptTarget, ts.ScriptTarget.JSON>): ts.Expression {
return expression.visitExpression(
new ExpressionTranslatorVisitor(imports, defaultImportRecorder, scriptTarget),
new Context(false));
}
export function translateStatement(
statement: Statement, imports: ImportManager, defaultImportRecorder: DefaultImportRecorder,
scriptTarget: Exclude<ts.ScriptTarget, ts.ScriptTarget.JSON>): ts.Statement {
return statement.visitStatement(
new ExpressionTranslatorVisitor(imports, defaultImportRecorder, scriptTarget),
new Context(true));
}
export function translateType(type: Type, imports: ImportManager): ts.TypeNode {
return type.visitType(new TypeTranslatorVisitor(imports), new Context(false));
}
class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor {
private externalSourceFiles = new Map<string, ts.SourceMapSource>();
constructor(
private imports: ImportManager, private defaultImportRecorder: DefaultImportRecorder,
private scriptTarget: Exclude<ts.ScriptTarget, ts.ScriptTarget.JSON>) {}
visitDeclareVarStmt(stmt: DeclareVarStmt, context: Context): ts.VariableStatement {
const nodeFlags =
((this.scriptTarget >= ts.ScriptTarget.ES2015) && stmt.hasModifier(StmtModifier.Final)) ?
ts.NodeFlags.Const :
ts.NodeFlags.None;
return ts.createVariableStatement(
undefined,
ts.createVariableDeclarationList(
[ts.createVariableDeclaration(
stmt.name, undefined,
stmt.value && stmt.value.visitExpression(this, context.withExpressionMode))],
nodeFlags));
}
visitDeclareFunctionStmt(stmt: DeclareFunctionStmt, context: Context): ts.FunctionDeclaration {
return ts.createFunctionDeclaration(
undefined, undefined, undefined, stmt.name, undefined,
stmt.params.map(param => ts.createParameter(undefined, undefined, undefined, param.name)),
undefined,
ts.createBlock(
stmt.statements.map(child => child.visitStatement(this, context.withStatementMode))));
}
visitExpressionStmt(stmt: ExpressionStatement, context: Context): ts.ExpressionStatement {
return ts.createStatement(stmt.expr.visitExpression(this, context.withStatementMode));
}
visitReturnStmt(stmt: ReturnStatement, context: Context): ts.ReturnStatement {
return ts.createReturn(stmt.value.visitExpression(this, context.withExpressionMode));
}
visitDeclareClassStmt(stmt: ClassStmt, context: Context) {
if (this.scriptTarget < ts.ScriptTarget.ES2015) {
throw new Error(
`Unsupported mode: Visiting a "declare class" statement (class ${stmt.name}) while ` +
`targeting ${ts.ScriptTarget[this.scriptTarget]}.`);
}
throw new Error('Method not implemented.');
}
visitIfStmt(stmt: IfStmt, context: Context): ts.IfStatement {
return ts.createIf(
stmt.condition.visitExpression(this, context),
ts.createBlock(
stmt.trueCase.map(child => child.visitStatement(this, context.withStatementMode))),
stmt.falseCase.length > 0 ?
ts.createBlock(stmt.falseCase.map(
child => child.visitStatement(this, context.withStatementMode))) :
undefined);
}
visitTryCatchStmt(stmt: TryCatchStmt, context: Context) {
throw new Error('Method not implemented.');
}
visitThrowStmt(stmt: ThrowStmt, context: Context): ts.ThrowStatement {
return ts.createThrow(stmt.error.visitExpression(this, context.withExpressionMode));
}
visitCommentStmt(stmt: CommentStmt, context: Context): ts.NotEmittedStatement {
const commentStmt = ts.createNotEmittedStatement(ts.createLiteral(''));
ts.addSyntheticLeadingComment(
commentStmt,
stmt.multiline ? ts.SyntaxKind.MultiLineCommentTrivia :
ts.SyntaxKind.SingleLineCommentTrivia,
stmt.comment, /** hasTrailingNewLine */ false);
return commentStmt;
}
visitJSDocCommentStmt(stmt: JSDocCommentStmt, context: Context): ts.NotEmittedStatement {
const commentStmt = ts.createNotEmittedStatement(ts.createLiteral(''));
const text = stmt.toString();
const kind = ts.SyntaxKind.MultiLineCommentTrivia;
ts.setSyntheticLeadingComments(commentStmt, [{kind, text, pos: -1, end: -1}]);
return commentStmt;
}
visitReadVarExpr(ast: ReadVarExpr, context: Context): ts.Identifier {
const identifier = ts.createIdentifier(ast.name!);
this.setSourceMapRange(identifier, ast.sourceSpan);
return identifier;
}
visitWriteVarExpr(expr: WriteVarExpr, context: Context): ts.Expression {
const result: ts.Expression = ts.createBinary(
ts.createIdentifier(expr.name), ts.SyntaxKind.EqualsToken,
expr.value.visitExpression(this, context));
return context.isStatement ? result : ts.createParen(result);
}
visitWriteKeyExpr(expr: WriteKeyExpr, context: Context): ts.Expression {
const exprContext = context.withExpressionMode;
const lhs = ts.createElementAccess(
expr.receiver.visitExpression(this, exprContext),
expr.index.visitExpression(this, exprContext));
const rhs = expr.value.visitExpression(this, exprContext);
const result: ts.Expression = ts.createBinary(lhs, ts.SyntaxKind.EqualsToken, rhs);
return context.isStatement ? result : ts.createParen(result);
}
visitWritePropExpr(expr: WritePropExpr, context: Context): ts.BinaryExpression {
return ts.createBinary(
ts.createPropertyAccess(expr.receiver.visitExpression(this, context), expr.name),
ts.SyntaxKind.EqualsToken, expr.value.visitExpression(this, context));
}
visitInvokeMethodExpr(ast: InvokeMethodExpr, context: Context): ts.CallExpression {
const target = ast.receiver.visitExpression(this, context);
const call = ts.createCall(
ast.name !== null ? ts.createPropertyAccess(target, ast.name) : target, undefined,
ast.args.map(arg => arg.visitExpression(this, context)));
this.setSourceMapRange(call, ast.sourceSpan);
return call;
}
visitInvokeFunctionExpr(ast: InvokeFunctionExpr, context: Context): ts.CallExpression {
const expr = ts.createCall(
ast.fn.visitExpression(this, context), undefined,
ast.args.map(arg => arg.visitExpression(this, context)));
if (ast.pure) {
ts.addSyntheticLeadingComment(expr, ts.SyntaxKind.MultiLineCommentTrivia, '@__PURE__', false);
}
this.setSourceMapRange(expr, ast.sourceSpan);
return expr;
}
visitInstantiateExpr(ast: InstantiateExpr, context: Context): ts.NewExpression {
return ts.createNew(
ast.classExpr.visitExpression(this, context), undefined,
ast.args.map(arg => arg.visitExpression(this, context)));
}
visitLiteralExpr(ast: LiteralExpr, context: Context): ts.Expression {
let expr: ts.Expression;
if (ast.value === undefined) {
expr = ts.createIdentifier('undefined');
} else if (ast.value === null) {
expr = ts.createNull();
} else {
expr = ts.createLiteral(ast.value);
}
this.setSourceMapRange(expr, ast.sourceSpan);
return expr;
}
visitLocalizedString(ast: LocalizedString, context: Context): ts.Expression {
const localizedString = this.scriptTarget >= ts.ScriptTarget.ES2015 ?
this.createLocalizedStringTaggedTemplate(ast, context) :
this.createLocalizedStringFunctionCall(ast, context);
this.setSourceMapRange(localizedString, ast.sourceSpan);
return localizedString;
}
visitExternalExpr(ast: ExternalExpr, context: Context): ts.PropertyAccessExpression
|ts.Identifier {
if (ast.value.name === null) {
throw new Error(`Import unknown module or symbol ${ast.value}`);
}
// If a moduleName is specified, this is a normal import. If there's no module name, it's a
// reference to a global/ambient symbol.
if (ast.value.moduleName !== null) {
// This is a normal import. Find the imported module.
const {moduleImport, symbol} =
this.imports.generateNamedImport(ast.value.moduleName, ast.value.name);
if (moduleImport === null) {
// The symbol was ambient after all.
return ts.createIdentifier(symbol);
} else {
return ts.createPropertyAccess(
ts.createIdentifier(moduleImport), ts.createIdentifier(symbol));
}
} else {
// The symbol is ambient, so just reference it.
return ts.createIdentifier(ast.value.name);
}
}
visitConditionalExpr(ast: ConditionalExpr, context: Context): ts.ConditionalExpression {
let cond: ts.Expression = ast.condition.visitExpression(this, context);
// Ordinarily the ternary operator is right-associative. The following are equivalent:
// `a ? b : c ? d : e` => `a ? b : (c ? d : e)`
//
// However, occasionally Angular needs to produce a left-associative conditional, such as in
// the case of a null-safe navigation production: `{{a?.b ? c : d}}`. This template produces
// a ternary of the form:
// `a == null ? null : rest of expression`
// If the rest of the expression is also a ternary though, this would produce the form:
// `a == null ? null : a.b ? c : d`
// which, if left as right-associative, would be incorrectly associated as:
// `a == null ? null : (a.b ? c : d)`
//
// In such cases, the left-associativity needs to be enforced with parentheses:
// `(a == null ? null : a.b) ? c : d`
//
// Such parentheses could always be included in the condition (guaranteeing correct behavior) in
// all cases, but this has a code size cost. Instead, parentheses are added only when a
// conditional expression is directly used as the condition of another.
//
// TODO(alxhub): investigate better logic for precendence of conditional operators
if (ast.condition instanceof ConditionalExpr) {
// The condition of this ternary needs to be wrapped in parentheses to maintain
// left-associativity.
cond = ts.createParen(cond);
}
return ts.createConditional(
cond, ast.trueCase.visitExpression(this, context),
ast.falseCase!.visitExpression(this, context));
}
visitNotExpr(ast: NotExpr, context: Context): ts.PrefixUnaryExpression {
return ts.createPrefix(
ts.SyntaxKind.ExclamationToken, ast.condition.visitExpression(this, context));
}
visitAssertNotNullExpr(ast: AssertNotNull, context: Context): ts.NonNullExpression {
return ast.condition.visitExpression(this, context);
}
visitCastExpr(ast: CastExpr, context: Context): ts.Expression {
return ast.value.visitExpression(this, context);
}
visitFunctionExpr(ast: FunctionExpr, context: Context): ts.FunctionExpression {
return ts.createFunctionExpression(
undefined, undefined, ast.name || undefined, undefined,
ast.params.map(
param => ts.createParameter(
undefined, undefined, undefined, param.name, undefined, undefined, undefined)),
undefined, ts.createBlock(ast.statements.map(stmt => stmt.visitStatement(this, context))));
}
visitUnaryOperatorExpr(ast: UnaryOperatorExpr, context: Context): ts.Expression {
if (!UNARY_OPERATORS.has(ast.operator)) {
throw new Error(`Unknown unary operator: ${UnaryOperator[ast.operator]}`);
}
return ts.createPrefix(
UNARY_OPERATORS.get(ast.operator)!, ast.expr.visitExpression(this, context));
}
visitBinaryOperatorExpr(ast: BinaryOperatorExpr, context: Context): ts.Expression {
if (!BINARY_OPERATORS.has(ast.operator)) {
throw new Error(`Unknown binary operator: ${BinaryOperator[ast.operator]}`);
}
return ts.createBinary(
ast.lhs.visitExpression(this, context), BINARY_OPERATORS.get(ast.operator)!,
ast.rhs.visitExpression(this, context));
}
visitReadPropExpr(ast: ReadPropExpr, context: Context): ts.PropertyAccessExpression {
return ts.createPropertyAccess(ast.receiver.visitExpression(this, context), ast.name);
}
visitReadKeyExpr(ast: ReadKeyExpr, context: Context): ts.ElementAccessExpression {
return ts.createElementAccess(
ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context));
}
visitLiteralArrayExpr(ast: LiteralArrayExpr, context: Context): ts.ArrayLiteralExpression {
const expr =
ts.createArrayLiteral(ast.entries.map(expr => expr.visitExpression(this, context)));
this.setSourceMapRange(expr, ast.sourceSpan);
return expr;
}
visitLiteralMapExpr(ast: LiteralMapExpr, context: Context): ts.ObjectLiteralExpression {
const entries = ast.entries.map(
entry => ts.createPropertyAssignment(
entry.quoted ? ts.createLiteral(entry.key) : ts.createIdentifier(entry.key),
entry.value.visitExpression(this, context)));
const expr = ts.createObjectLiteral(entries);
this.setSourceMapRange(expr, ast.sourceSpan);
return expr;
}
visitCommaExpr(ast: CommaExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitWrappedNodeExpr(ast: WrappedNodeExpr<any>, context: Context): any {
if (ts.isIdentifier(ast.node)) {
this.defaultImportRecorder.recordUsedIdentifier(ast.node);
}
return ast.node;
}
visitTypeofExpr(ast: TypeofExpr, context: Context): ts.TypeOfExpression {
return ts.createTypeOf(ast.expr.visitExpression(this, context));
}
/**
* Translate the `LocalizedString` node into a `TaggedTemplateExpression` for ES2015 formatted
* output.
*/
private createLocalizedStringTaggedTemplate(ast: LocalizedString, context: Context):
ts.TaggedTemplateExpression {
let template: ts.TemplateLiteral;
const length = ast.messageParts.length;
const metaBlock = ast.serializeI18nHead();
if (length === 1) {
template = ts.createNoSubstitutionTemplateLiteral(metaBlock.cooked, metaBlock.raw);
this.setSourceMapRange(template, ast.getMessagePartSourceSpan(0));
} else {
// Create the head part
const head = ts.createTemplateHead(metaBlock.cooked, metaBlock.raw);
this.setSourceMapRange(head, ast.getMessagePartSourceSpan(0));
const spans: ts.TemplateSpan[] = [];
// Create the middle parts
for (let i = 1; i < length - 1; i++) {
const resolvedExpression = ast.expressions[i - 1].visitExpression(this, context);
this.setSourceMapRange(resolvedExpression, ast.getPlaceholderSourceSpan(i - 1));
const templatePart = ast.serializeI18nTemplatePart(i);
const templateMiddle = createTemplateMiddle(templatePart.cooked, templatePart.raw);
this.setSourceMapRange(templateMiddle, ast.getMessagePartSourceSpan(i));
const templateSpan = ts.createTemplateSpan(resolvedExpression, templateMiddle);
spans.push(templateSpan);
}
// Create the tail part
const resolvedExpression = ast.expressions[length - 2].visitExpression(this, context);
this.setSourceMapRange(resolvedExpression, ast.getPlaceholderSourceSpan(length - 2));
const templatePart = ast.serializeI18nTemplatePart(length - 1);
const templateTail = createTemplateTail(templatePart.cooked, templatePart.raw);
this.setSourceMapRange(templateTail, ast.getMessagePartSourceSpan(length - 1));
spans.push(ts.createTemplateSpan(resolvedExpression, templateTail));
// Put it all together
template = ts.createTemplateExpression(head, spans);
}
const expression = ts.createTaggedTemplate(ts.createIdentifier('$localize'), template);
this.setSourceMapRange(expression, ast.sourceSpan);
return expression;
}
/**
* Translate the `LocalizedString` node into a `$localize` call using the imported
* `__makeTemplateObject` helper for ES5 formatted output.
*/
private createLocalizedStringFunctionCall(ast: LocalizedString, context: Context) {
// A `$localize` message consists `messageParts` and `expressions`, which get interleaved
// together. The interleaved pieces look like:
// `[messagePart0, expression0, messagePart1, expression1, messagePart2]`
//
// Note that there is always a message part at the start and end, and so therefore
// `messageParts.length === expressions.length + 1`.
//
// Each message part may be prefixed with "metadata", which is wrapped in colons (:) delimiters.
// The metadata is attached to the first and subsequent message parts by calls to
// `serializeI18nHead()` and `serializeI18nTemplatePart()` respectively.
// The first message part (i.e. `ast.messageParts[0]`) is used to initialize `messageParts`
// array.
const messageParts = [ast.serializeI18nHead()];
const expressions: any[] = [];
// The rest of the `ast.messageParts` and each of the expressions are `ast.expressions` pushed
// into the arrays. Note that `ast.messagePart[i]` corresponds to `expressions[i-1]`
for (let i = 1; i < ast.messageParts.length; i++) {
expressions.push(ast.expressions[i - 1].visitExpression(this, context));
messageParts.push(ast.serializeI18nTemplatePart(i));
}
// The resulting downlevelled tagged template string uses a call to the `__makeTemplateObject()`
// helper, so we must ensure it has been imported.
const {moduleImport, symbol} =
this.imports.generateNamedImport('tslib', '__makeTemplateObject');
const __makeTemplateObjectHelper = (moduleImport === null) ?
ts.createIdentifier(symbol) :
ts.createPropertyAccess(ts.createIdentifier(moduleImport), ts.createIdentifier(symbol));
// Generate the call in the form:
// `$localize(__makeTemplateObject(cookedMessageParts, rawMessageParts), ...expressions);`
const cookedLiterals = messageParts.map(
(messagePart, i) =>
this.createLiteral(messagePart.cooked, ast.getMessagePartSourceSpan(i)));
const rawLiterals = messageParts.map(
(messagePart, i) => this.createLiteral(messagePart.raw, ast.getMessagePartSourceSpan(i)));
return ts.createCall(
/* expression */ ts.createIdentifier('$localize'),
/* typeArguments */ undefined,
/* argumentsArray */[
ts.createCall(
/* expression */ __makeTemplateObjectHelper,
/* typeArguments */ undefined,
/* argumentsArray */
[
ts.createArrayLiteral(cookedLiterals),
ts.createArrayLiteral(rawLiterals),
]),
...expressions,
]);
}
private setSourceMapRange(expr: ts.Node, sourceSpan: ParseSourceSpan|null) {
if (sourceSpan) {
const {start, end} = sourceSpan;
const {url, content} = start.file;
if (url) {
if (!this.externalSourceFiles.has(url)) {
this.externalSourceFiles.set(url, ts.createSourceMapSource(url, content, pos => pos));
}
const source = this.externalSourceFiles.get(url);
ts.setSourceMapRange(expr, {pos: start.offset, end: end.offset, source});
}
}
}
private createLiteral(text: string, span: ParseSourceSpan|null) {
const literal = ts.createStringLiteral(text);
this.setSourceMapRange(literal, span);
return literal;
}
}
export class TypeTranslatorVisitor implements ExpressionVisitor, TypeVisitor {
constructor(private imports: ImportManager) {}
visitBuiltinType(type: BuiltinType, context: Context): ts.KeywordTypeNode {
switch (type.name) {
case BuiltinTypeName.Bool:
return ts.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
case BuiltinTypeName.Dynamic:
return ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);
case BuiltinTypeName.Int:
case BuiltinTypeName.Number:
return ts.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
case BuiltinTypeName.String:
return ts.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
case BuiltinTypeName.None:
return ts.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword);
default:
throw new Error(`Unsupported builtin type: ${BuiltinTypeName[type.name]}`);
}
}
visitExpressionType(type: ExpressionType, context: Context): ts.TypeNode {
const typeNode = this.translateExpression(type.value, context);
if (type.typeParams === null) {
return typeNode;
}
if (!ts.isTypeReferenceNode(typeNode)) {
throw new Error(
'An ExpressionType with type arguments must translate into a TypeReferenceNode');
} else if (typeNode.typeArguments !== undefined) {
throw new Error(
`An ExpressionType with type arguments cannot have multiple levels of type arguments`);
}
const typeArgs = type.typeParams.map(param => this.translateType(param, context));
return ts.createTypeReferenceNode(typeNode.typeName, typeArgs);
}
visitArrayType(type: ArrayType, context: Context): ts.ArrayTypeNode {
return ts.createArrayTypeNode(this.translateType(type.of, context));
}
visitMapType(type: MapType, context: Context): ts.TypeLiteralNode {
const parameter = ts.createParameter(
undefined, undefined, undefined, 'key', undefined,
ts.createKeywordTypeNode(ts.SyntaxKind.StringKeyword));
const typeArgs = type.valueType !== null ?
this.translateType(type.valueType, context) :
ts.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword);
const indexSignature = ts.createIndexSignature(undefined, undefined, [parameter], typeArgs);
return ts.createTypeLiteralNode([indexSignature]);
}
visitReadVarExpr(ast: ReadVarExpr, context: Context): ts.TypeQueryNode {
if (ast.name === null) {
throw new Error(`ReadVarExpr with no variable name in type`);
}
return ts.createTypeQueryNode(ts.createIdentifier(ast.name));
}
visitWriteVarExpr(expr: WriteVarExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitWriteKeyExpr(expr: WriteKeyExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitWritePropExpr(expr: WritePropExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitInvokeMethodExpr(ast: InvokeMethodExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitInvokeFunctionExpr(ast: InvokeFunctionExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitInstantiateExpr(ast: InstantiateExpr, context: Context): never {
throw new Error('Method not implemented.');
}
visitLiteralExpr(ast: LiteralExpr, context: Context): ts.TypeNode {
if (ast.value === null) {
// TODO(alan-agius4): Remove when we no longer support TS 3.9
// Use: return ts.createLiteralTypeNode(ts.createNull()) directly.
return ts.versionMajorMinor.charAt(0) === '4' ?
ts.createLiteralTypeNode(ts.createNull() as any) :
ts.createKeywordTypeNode(ts.SyntaxKind.NullKeyword as any);
} else if (ast.value === undefined) {
return ts.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword);
} else if (typeof ast.value === 'boolean') {
return ts.createLiteralTypeNode(ts.createLiteral(ast.value));
} else if (typeof ast.value === 'number') {
return ts.createLiteralTypeNode(ts.createLiteral(ast.value));
} else {
return ts.createLiteralTypeNode(ts.createLiteral(ast.value));
}
}
visitLocalizedString(ast: LocalizedString, context: Context): never {
throw new Error('Method not implemented.');
}
visitExternalExpr(ast: ExternalExpr, context: Context): ts.EntityName|ts.TypeReferenceNode {
if (ast.value.moduleName === null || ast.value.name === null) {
throw new Error(`Import unknown module or symbol`);
}
const {moduleImport, symbol} =
this.imports.generateNamedImport(ast.value.moduleName, ast.value.name);
const symbolIdentifier = ts.createIdentifier(symbol);
const typeName = moduleImport ?
ts.createQualifiedName(ts.createIdentifier(moduleImport), symbolIdentifier) :
symbolIdentifier;
const typeArguments = ast.typeParams !== null ?
ast.typeParams.map(type => this.translateType(type, context)) :
undefined;
return ts.createTypeReferenceNode(typeName, typeArguments);
}
visitConditionalExpr(ast: ConditionalExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitNotExpr(ast: NotExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitAssertNotNullExpr(ast: AssertNotNull, context: Context) {
throw new Error('Method not implemented.');
}
visitCastExpr(ast: CastExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitFunctionExpr(ast: FunctionExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitUnaryOperatorExpr(ast: UnaryOperatorExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitBinaryOperatorExpr(ast: BinaryOperatorExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitReadPropExpr(ast: ReadPropExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitReadKeyExpr(ast: ReadKeyExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitLiteralArrayExpr(ast: LiteralArrayExpr, context: Context): ts.TupleTypeNode {
const values = ast.entries.map(expr => this.translateExpression(expr, context));
return ts.createTupleTypeNode(values);
}
visitLiteralMapExpr(ast: LiteralMapExpr, context: Context): ts.TypeLiteralNode {
const entries = ast.entries.map(entry => {
const {key, quoted} = entry;
const type = this.translateExpression(entry.value, context);
return ts.createPropertySignature(
/* modifiers */ undefined,
/* name */ quoted ? ts.createStringLiteral(key) : key,
/* questionToken */ undefined,
/* type */ type,
/* initializer */ undefined);
});
return ts.createTypeLiteralNode(entries);
}
visitCommaExpr(ast: CommaExpr, context: Context) {
throw new Error('Method not implemented.');
}
visitWrappedNodeExpr(ast: WrappedNodeExpr<any>, context: Context): ts.TypeNode {
const node: ts.Node = ast.node;
if (ts.isEntityName(node)) {
return ts.createTypeReferenceNode(node, /* typeArguments */ undefined);
} else if (ts.isTypeNode(node)) {
return node;
} else if (ts.isLiteralExpression(node)) {
return ts.createLiteralTypeNode(node);
} else {
throw new Error(
`Unsupported WrappedNodeExpr in TypeTranslatorVisitor: ${ts.SyntaxKind[node.kind]}`);
}
}
visitTypeofExpr(ast: TypeofExpr, context: Context): ts.TypeQueryNode {
let expr = translateExpression(
ast.expr, this.imports, NOOP_DEFAULT_IMPORT_RECORDER, ts.ScriptTarget.ES2015);
return ts.createTypeQueryNode(expr as ts.Identifier);
}
private translateType(type: Type, context: Context): ts.TypeNode {
const typeNode = type.visitType(this, context);
if (!ts.isTypeNode(typeNode)) {
throw new Error(
`A Type must translate to a TypeNode, but was ${ts.SyntaxKind[typeNode.kind]}`);
}
return typeNode;
}
private translateExpression(expr: Expression, context: Context): ts.TypeNode {
const typeNode = expr.visitExpression(this, context);
if (!ts.isTypeNode(typeNode)) {
throw new Error(
`An Expression must translate to a TypeNode, but was ${ts.SyntaxKind[typeNode.kind]}`);
}
return typeNode;
}
}
// HACK: Use this in place of `ts.createTemplateMiddle()`.
// Revert once https://github.com/microsoft/TypeScript/issues/35374 is fixed
function createTemplateMiddle(cooked: string, raw: string): ts.TemplateMiddle {
const node: ts.TemplateLiteralLikeNode = ts.createTemplateHead(cooked, raw);
(node.kind as ts.SyntaxKind) = ts.SyntaxKind.TemplateMiddle;
return node as ts.TemplateMiddle;
}
// HACK: Use this in place of `ts.createTemplateTail()`.
// Revert once https://github.com/microsoft/TypeScript/issues/35374 is fixed
function createTemplateTail(cooked: string, raw: string): ts.TemplateTail {
const node: ts.TemplateLiteralLikeNode = ts.createTemplateHead(cooked, raw);
(node.kind as ts.SyntaxKind) = ts.SyntaxKind.TemplateTail;
return node as ts.TemplateTail;
}