-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathdecorator-annotator.ts
352 lines (328 loc) · 12.9 KB
/
decorator-annotator.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
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {getDecoratorDeclarations} from './decorators';
import {getIdentifierText, Rewriter} from './rewriter';
import {SourceMapper, SourcePosition} from './source_map_utils';
import {assertTypeChecked, TypeTranslator} from './type-translator';
import {toArray} from './util';
// DecoratorClassVisitor rewrites a single "class Foo {...}" declaration.
// It's its own object because we collect decorators on the class and the ctor
// separately for each class we encounter.
export class DecoratorClassVisitor {
/** Decorators on the class itself. */
decorators: ts.Decorator[];
/** The constructor parameter list and decorators on each param. */
ctorParameters: ([string | undefined, ts.Decorator[]|undefined]|null)[];
/** Per-method decorators. */
propDecorators: Map<string, ts.Decorator[]>;
constructor(
private typeChecker: ts.TypeChecker, private rewriter: Rewriter,
private classDecl: ts.ClassDeclaration) {
if (classDecl.decorators) {
let toLower = this.decoratorsToLower(classDecl);
if (toLower.length > 0) this.decorators = toLower;
}
}
/**
* Determines whether the given decorator should be re-written as an annotation.
*/
private shouldLower(decorator: ts.Decorator) {
for (let d of getDecoratorDeclarations(decorator, this.typeChecker)) {
// Switch to the TS JSDoc parser in the future to avoid false positives here.
// For example using '@Annotation' in a true comment.
// However, a new TS API would be needed, track at
// https://github.com/Microsoft/TypeScript/issues/7393.
let commentNode: ts.Node = d;
// Not handling PropertyAccess expressions here, because they are
// filtered earlier.
if (commentNode.kind === ts.SyntaxKind.VariableDeclaration) {
if (!commentNode.parent) continue;
commentNode = commentNode.parent;
}
// Go up one more level to VariableDeclarationStatement, where usually
// the comment lives. If the declaration has an 'export', the
// VDList.getFullText will not contain the comment.
if (commentNode.kind === ts.SyntaxKind.VariableDeclarationList) {
if (!commentNode.parent) continue;
commentNode = commentNode.parent;
}
let range = ts.getLeadingCommentRanges(commentNode.getFullText(), 0);
if (!range) continue;
for (let {pos, end} of range) {
let jsDocText = commentNode.getFullText().substring(pos, end);
if (jsDocText.includes('@Annotation')) return true;
}
}
return false;
}
private decoratorsToLower(n: ts.Node): ts.Decorator[] {
if (n.decorators) {
return n.decorators.filter((d) => this.shouldLower(d));
}
return [];
}
/**
* gatherConstructor grabs the parameter list and decorators off the class
* constructor, and emits nothing.
*/
private gatherConstructor(ctor: ts.ConstructorDeclaration) {
let ctorParameters: ([string | undefined, ts.Decorator[] | undefined]|null)[] = [];
let hasDecoratedParam = false;
for (let param of ctor.parameters) {
let paramCtor: string|undefined;
let decorators: ts.Decorator[]|undefined;
if (param.decorators) {
decorators = this.decoratorsToLower(param);
hasDecoratedParam = decorators.length > 0;
}
if (param.type) {
// param has a type provided, e.g. "foo: Bar".
// Verify that "Bar" is a value (e.g. a constructor) and not just a type.
let sym = this.typeChecker.getTypeAtLocation(param.type).getSymbol();
if (sym && (sym.flags & ts.SymbolFlags.Value)) {
paramCtor = new TypeTranslator(this.typeChecker, param.type)
.symbolToString(sym, /* useFqn */ true);
}
}
if (paramCtor || decorators) {
ctorParameters.push([paramCtor, decorators]);
} else {
ctorParameters.push(null);
}
}
// Use the ctor parameter metadata only if the class or the ctor was decorated.
if (this.decorators || hasDecoratedParam) {
this.ctorParameters = ctorParameters;
}
}
/**
* gatherMethod grabs the decorators off a class method and emits nothing.
*/
private gatherMethodOrProperty(method: ts.Declaration) {
if (!method.decorators) return;
if (!method.name || method.name.kind !== ts.SyntaxKind.Identifier) {
// Method has a weird name, e.g.
// [Symbol.foo]() {...}
this.rewriter.error(method, 'cannot process decorators on strangely named method');
return;
}
let name = (method.name as ts.Identifier).text;
let decorators: ts.Decorator[] = this.decoratorsToLower(method);
if (decorators.length === 0) return;
if (!this.propDecorators) this.propDecorators = new Map<string, ts.Decorator[]>();
this.propDecorators.set(name, decorators);
}
beforeProcessNode(node: ts.Node) {
switch (node.kind) {
case ts.SyntaxKind.Constructor:
this.gatherConstructor(node as ts.ConstructorDeclaration);
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.MethodDeclaration:
this.gatherMethodOrProperty(node as ts.Declaration);
}
}
maybeProcessDecorator(node: ts.Node, start?: number): boolean {
if (this.shouldLower(node as ts.Decorator)) {
// Return true to signal that this node should not be emitted,
// but still emit the whitespace *before* the node.
if (!start) {
start = node.getFullStart();
}
this.rewriter.writeRange(node, start, node.getStart());
return true;
}
return false;
}
/**
* emits the types for the various gathered metadata to be used
* in the tsickle type annotations helper.
*/
emitMetadataTypeAnnotationsHelpers() {
if (!this.classDecl.name) return;
let className = getIdentifierText(this.classDecl.name);
if (this.decorators) {
this.rewriter.emit(`/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */\n`);
this.rewriter.emit(`${className}.decorators;\n`);
}
if (this.decorators || this.ctorParameters) {
this.rewriter.emit(`/**\n`);
this.rewriter.emit(` * @nocollapse\n`);
this.rewriter.emit(
` * @type {function(): !Array<(null|{type: ?, decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>)})>}\n`);
this.rewriter.emit(` */\n`);
this.rewriter.emit(`${className}.ctorParameters;\n`);
}
if (this.propDecorators) {
this.rewriter.emit(
`/** @type {!Object<string,!Array<{type: !Function, args: (undefined|!Array<?>)}>>} */\n`);
this.rewriter.emit(`${className}.propDecorators;\n`);
}
}
/**
* emits the various gathered metadata, as static fields.
*/
emitMetadataAsStaticProperties() {
const decoratorInvocations = '{type: Function, args?: any[]}[]';
if (this.decorators) {
this.rewriter.emit(`static decorators: ${decoratorInvocations} = [\n`);
for (let annotation of this.decorators) {
this.emitDecorator(annotation);
this.rewriter.emit(',\n');
}
this.rewriter.emit('];\n');
}
if (this.decorators || this.ctorParameters) {
this.rewriter.emit(`/** @nocollapse */\n`);
// ctorParameters may contain forward references in the type: field, so wrap in a function
// closure
this.rewriter.emit(
`static ctorParameters: () => ({type: any, decorators?: ` + decoratorInvocations +
`}|null)[] = () => [\n`);
for (let param of this.ctorParameters || []) {
if (!param) {
this.rewriter.emit('null,\n');
continue;
}
let [ctor, decorators] = param;
this.rewriter.emit(`{type: ${ctor}, `);
if (decorators) {
this.rewriter.emit('decorators: [');
for (let decorator of decorators) {
this.emitDecorator(decorator);
this.rewriter.emit(', ');
}
this.rewriter.emit(']');
}
this.rewriter.emit('},\n');
}
this.rewriter.emit(`];\n`);
}
if (this.propDecorators) {
this.rewriter.emit(
`static propDecorators: {[key: string]: ` + decoratorInvocations + `} = {\n`);
for (let name of toArray(this.propDecorators.keys())) {
this.rewriter.emit(`'${name}': [`);
for (let decorator of this.propDecorators.get(name)!) {
this.emitDecorator(decorator);
this.rewriter.emit(',');
}
this.rewriter.emit('],\n');
}
this.rewriter.emit('};\n');
}
}
private emitDecorator(decorator: ts.Decorator) {
this.rewriter.emit('{ type: ');
let expr = decorator.expression;
switch (expr.kind) {
case ts.SyntaxKind.Identifier:
// The decorator was a plain @Foo.
this.rewriter.visit(expr);
break;
case ts.SyntaxKind.CallExpression:
// The decorator was a call, like @Foo(bar).
let call = expr as ts.CallExpression;
this.rewriter.visit(call.expression);
if (call.arguments.length) {
this.rewriter.emit(', args: [');
for (let arg of call.arguments) {
this.rewriter.emit(arg.getText());
this.rewriter.emit(', ');
}
this.rewriter.emit(']');
}
break;
default:
this.rewriter.errorUnimplementedKind(expr, 'gathering metadata');
this.rewriter.emit('undefined');
}
this.rewriter.emit(' }');
}
}
class DecoratorRewriter extends Rewriter {
/** ComposableDecoratorRewriter when using tsickle as a TS transformer */
private currentDecoratorConverter: DecoratorClassVisitor;
constructor(
private typeChecker: ts.TypeChecker, file: ts.SourceFile, sourceMapper?: SourceMapper) {
super(file, sourceMapper);
}
process(): {output: string, diagnostics: ts.Diagnostic[]} {
this.visit(this.file);
return this.getOutput();
}
protected maybeProcess(node: ts.Node): boolean {
if (this.currentDecoratorConverter) {
this.currentDecoratorConverter.beforeProcessNode(node);
}
switch (node.kind) {
case ts.SyntaxKind.Decorator:
return this.currentDecoratorConverter &&
this.currentDecoratorConverter.maybeProcessDecorator(node);
case ts.SyntaxKind.ClassDeclaration:
const oldDecoratorConverter = this.currentDecoratorConverter;
this.currentDecoratorConverter =
new DecoratorClassVisitor(this.typeChecker, this, node as ts.ClassDeclaration);
this.writeRange(node, node.getFullStart(), node.getStart());
visitClassContent(node as ts.ClassDeclaration, this, this.currentDecoratorConverter);
this.currentDecoratorConverter = oldDecoratorConverter;
return true;
default:
return false;
}
}
}
export function convertDecorators(
typeChecker: ts.TypeChecker, sourceFile: ts.SourceFile,
sourceMapper?: SourceMapper): {output: string, diagnostics: ts.Diagnostic[]} {
assertTypeChecked(sourceFile);
return new DecoratorRewriter(typeChecker, sourceFile, sourceMapper).process();
}
export function visitClassContent(
classDecl: ts.ClassDeclaration, rewriter: Rewriter, decoratorVisitor?: DecoratorClassVisitor) {
let pos = classDecl.getStart();
if (decoratorVisitor) {
// strip out decorators if needed
ts.forEachChild(classDecl, child => {
if (child.kind !== ts.SyntaxKind.Decorator) {
return;
}
// Note: The getFullStart() of the first decorator is the same
// as the getFullStart() of the class declaration.
// Therefore, we need to use Math.max to not print the whitespace
// of the class again.
const childStart = Math.max(pos, child.getFullStart());
rewriter.writeRange(classDecl, pos, childStart);
if (decoratorVisitor.maybeProcessDecorator(child, childStart)) {
pos = child.getEnd();
}
});
}
if (classDecl.members.length > 0) {
rewriter.writeRange(classDecl, pos, classDecl.members[0].getFullStart());
for (let member of classDecl.members) {
rewriter.visit(member);
}
pos = classDecl.getLastToken().getFullStart();
}
// At this point, we've emitted up through the final child of the class, so all that
// remains is the trailing whitespace and closing curly brace.
// The final character owned by the class node should always be a '}',
// or we somehow got the AST wrong and should report an error.
// (Any whitespace or semicolon following the '}' will be part of the next Node.)
if (rewriter.file.text[classDecl.getEnd() - 1] !== '}') {
rewriter.error(classDecl, 'unexpected class terminator');
}
rewriter.writeRange(classDecl, pos, classDecl.getEnd() - 1);
if (decoratorVisitor) {
decoratorVisitor.emitMetadataAsStaticProperties();
}
rewriter.emit('}');
}