-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
util.ts
357 lines (327 loc) Β· 12.7 KB
/
util.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
/**
* @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 {Expression, ExternalExpr, R3DependencyMetadata, R3Reference, R3ResolvedDependencyType, WrappedNodeExpr} from '@angular/compiler';
import * as ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../diagnostics';
import {DefaultImportRecorder, ImportMode, Reference, ReferenceEmitter} from '../../imports';
import {ForeignFunctionResolver, PartialEvaluator} from '../../partial_evaluator';
import {ClassDeclaration, CtorParameter, Decorator, Import, ReflectionHost, TypeValueReference, isNamedClassDeclaration} from '../../reflection';
export enum ConstructorDepErrorKind {
NO_SUITABLE_TOKEN,
}
export type ConstructorDeps = {
deps: R3DependencyMetadata[];
} |
{
deps: null;
errors: ConstructorDepError[];
};
export interface ConstructorDepError {
index: number;
param: CtorParameter;
kind: ConstructorDepErrorKind;
}
export function getConstructorDependencies(
clazz: ClassDeclaration, reflector: ReflectionHost,
defaultImportRecorder: DefaultImportRecorder, isCore: boolean): ConstructorDeps|null {
const deps: R3DependencyMetadata[] = [];
const errors: ConstructorDepError[] = [];
let ctorParams = reflector.getConstructorParameters(clazz);
if (ctorParams === null) {
if (reflector.hasBaseClass(clazz)) {
return null;
} else {
ctorParams = [];
}
}
ctorParams.forEach((param, idx) => {
let token = valueReferenceToExpression(param.typeValueReference, defaultImportRecorder);
let optional = false, self = false, skipSelf = false, host = false;
let resolved = R3ResolvedDependencyType.Token;
(param.decorators || []).filter(dec => isCore || isAngularCore(dec)).forEach(dec => {
const name = isCore || dec.import === null ? dec.name : dec.import !.name;
if (name === 'Inject') {
if (dec.args === null || dec.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, dec.node,
`Unexpected number of arguments to @Inject().`);
}
token = new WrappedNodeExpr(dec.args[0]);
} else if (name === 'Optional') {
optional = true;
} else if (name === 'SkipSelf') {
skipSelf = true;
} else if (name === 'Self') {
self = true;
} else if (name === 'Host') {
host = true;
} else if (name === 'Attribute') {
if (dec.args === null || dec.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, dec.node,
`Unexpected number of arguments to @Attribute().`);
}
token = new WrappedNodeExpr(dec.args[0]);
resolved = R3ResolvedDependencyType.Attribute;
} else {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_UNEXPECTED, dec.node, `Unexpected decorator ${name} on parameter.`);
}
});
if (token instanceof ExternalExpr && token.value.name === 'ChangeDetectorRef' &&
token.value.moduleName === '@angular/core') {
resolved = R3ResolvedDependencyType.ChangeDetectorRef;
}
if (token === null) {
errors.push({
index: idx,
kind: ConstructorDepErrorKind.NO_SUITABLE_TOKEN, param,
});
} else {
deps.push({token, optional, self, skipSelf, host, resolved});
}
});
if (errors.length === 0) {
return {deps};
} else {
return {deps: null, errors};
}
}
/**
* Convert a `TypeValueReference` to an `Expression` which refers to the type as a value.
*
* Local references are converted to a `WrappedNodeExpr` of the TypeScript expression, and non-local
* references are converted to an `ExternalExpr`. Note that this is only valid in the context of the
* file in which the `TypeValueReference` originated.
*/
export function valueReferenceToExpression(
valueRef: TypeValueReference, defaultImportRecorder: DefaultImportRecorder): Expression;
export function valueReferenceToExpression(
valueRef: null, defaultImportRecorder: DefaultImportRecorder): null;
export function valueReferenceToExpression(
valueRef: TypeValueReference | null, defaultImportRecorder: DefaultImportRecorder): Expression|
null;
export function valueReferenceToExpression(
valueRef: TypeValueReference | null, defaultImportRecorder: DefaultImportRecorder): Expression|
null {
if (valueRef === null) {
return null;
} else if (valueRef.local) {
if (defaultImportRecorder !== null && valueRef.defaultImportStatement !== null &&
ts.isIdentifier(valueRef.expression)) {
defaultImportRecorder.recordImportedIdentifier(
valueRef.expression, valueRef.defaultImportStatement);
}
return new WrappedNodeExpr(valueRef.expression);
} else {
// TODO(alxhub): this cast is necessary because the g3 typescript version doesn't narrow here.
return new ExternalExpr(valueRef as{moduleName: string, name: string});
}
}
/**
* Convert `ConstructorDeps` into the `R3DependencyMetadata` array for those deps if they're valid,
* or into an `'invalid'` signal if they're not.
*
* This is a companion function to `validateConstructorDependencies` which accepts invalid deps.
*/
export function unwrapConstructorDependencies(deps: ConstructorDeps | null): R3DependencyMetadata[]|
'invalid'|null {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
// These constructor dependencies are valid.
return deps.deps;
} else {
// These deps are invalid.
return 'invalid';
}
}
export function getValidConstructorDependencies(
clazz: ClassDeclaration, reflector: ReflectionHost,
defaultImportRecorder: DefaultImportRecorder, isCore: boolean): R3DependencyMetadata[]|null {
return validateConstructorDependencies(
clazz, getConstructorDependencies(clazz, reflector, defaultImportRecorder, isCore));
}
/**
* Validate that `ConstructorDeps` does not have any invalid dependencies and convert them into the
* `R3DependencyMetadata` array if so, or raise a diagnostic if some deps are invalid.
*
* This is a companion function to `unwrapConstructorDependencies` which does not accept invalid
* deps.
*/
export function validateConstructorDependencies(
clazz: ClassDeclaration, deps: ConstructorDeps | null): R3DependencyMetadata[]|null {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
return deps.deps;
} else {
// TODO(alxhub): this cast is necessary because the g3 typescript version doesn't narrow here.
const {param, index} = (deps as{errors: ConstructorDepError[]}).errors[0];
// There is at least one error.
throw new FatalDiagnosticError(
ErrorCode.PARAM_MISSING_TOKEN, param.nameNode,
`No suitable injection token for parameter '${param.name || index}' of class '${clazz.name.text}'.\n` +
(param.typeNode !== null ? `Found ${param.typeNode.getText()}` :
'no type or decorator'));
}
}
export function toR3Reference(
valueRef: Reference, typeRef: Reference, valueContext: ts.SourceFile,
typeContext: ts.SourceFile, refEmitter: ReferenceEmitter): R3Reference {
const value = refEmitter.emit(valueRef, valueContext, ImportMode.UseExistingImport);
const type = refEmitter.emit(typeRef, typeContext, ImportMode.ForceNewImport);
if (value === null || type === null) {
throw new Error(`Could not refer to ${ts.SyntaxKind[valueRef.node.kind]}`);
}
return {value, type};
}
export function isAngularCore(decorator: Decorator): decorator is Decorator&{import: Import} {
return decorator.import !== null && decorator.import.from === '@angular/core';
}
export function isAngularCoreReference(reference: Reference, symbolName: string): boolean {
return reference.ownedByModuleGuess === '@angular/core' && reference.debugName === symbolName;
}
export function findAngularDecorator(
decorators: Decorator[], name: string, isCore: boolean): Decorator|undefined {
return decorators.find(decorator => isAngularDecorator(decorator, name, isCore));
}
export function isAngularDecorator(decorator: Decorator, name: string, isCore: boolean): boolean {
if (isCore) {
return decorator.name === name;
} else if (isAngularCore(decorator)) {
return decorator.import.name === name;
}
return false;
}
/**
* Unwrap a `ts.Expression`, removing outer type-casts or parentheses until the expression is in its
* lowest level form.
*
* For example, the expression "(foo as Type)" unwraps to "foo".
*/
export function unwrapExpression(node: ts.Expression): ts.Expression {
while (ts.isAsExpression(node) || ts.isParenthesizedExpression(node)) {
node = node.expression;
}
return node;
}
function expandForwardRef(arg: ts.Expression): ts.Expression|null {
arg = unwrapExpression(arg);
if (!ts.isArrowFunction(arg) && !ts.isFunctionExpression(arg)) {
return null;
}
const body = arg.body;
// Either the body is a ts.Expression directly, or a block with a single return statement.
if (ts.isBlock(body)) {
// Block body - look for a single return statement.
if (body.statements.length !== 1) {
return null;
}
const stmt = body.statements[0];
if (!ts.isReturnStatement(stmt) || stmt.expression === undefined) {
return null;
}
return stmt.expression;
} else {
// Shorthand body - return as an expression.
return body;
}
}
/**
* Possibly resolve a forwardRef() expression into the inner value.
*
* @param node the forwardRef() expression to resolve
* @param reflector a ReflectionHost
* @returns the resolved expression, if the original expression was a forwardRef(), or the original
* expression otherwise
*/
export function unwrapForwardRef(node: ts.Expression, reflector: ReflectionHost): ts.Expression {
node = unwrapExpression(node);
if (!ts.isCallExpression(node) || node.arguments.length !== 1) {
return node;
}
const fn =
ts.isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression;
if (!ts.isIdentifier(fn)) {
return node;
}
const expr = expandForwardRef(node.arguments[0]);
if (expr === null) {
return node;
}
const imp = reflector.getImportOfIdentifier(fn);
if (imp === null || imp.from !== '@angular/core' || imp.name !== 'forwardRef') {
return node;
} else {
return expr;
}
}
/**
* A foreign function resolver for `staticallyResolve` which unwraps forwardRef() expressions.
*
* @param ref a Reference to the declaration of the function being called (which might be
* forwardRef)
* @param args the arguments to the invocation of the forwardRef expression
* @returns an unwrapped argument if `ref` pointed to forwardRef, or null otherwise
*/
export function forwardRefResolver(
ref: Reference<ts.FunctionDeclaration|ts.MethodDeclaration|ts.FunctionExpression>,
args: ReadonlyArray<ts.Expression>): ts.Expression|null {
if (!isAngularCoreReference(ref, 'forwardRef') || args.length !== 1) {
return null;
}
return expandForwardRef(args[0]);
}
/**
* Combines an array of resolver functions into a one.
* @param resolvers Resolvers to be combined.
*/
export function combineResolvers(resolvers: ForeignFunctionResolver[]): ForeignFunctionResolver {
return (ref: Reference<ts.FunctionDeclaration|ts.MethodDeclaration|ts.FunctionExpression>,
args: ReadonlyArray<ts.Expression>): ts.Expression |
null => {
for (const resolver of resolvers) {
const resolved = resolver(ref, args);
if (resolved !== null) {
return resolved;
}
}
return null;
};
}
export function isExpressionForwardReference(
expr: Expression, context: ts.Node, contextSource: ts.SourceFile): boolean {
if (isWrappedTsNodeExpr(expr)) {
const node = ts.getOriginalNode(expr.node);
return node.getSourceFile() === contextSource && context.pos < node.pos;
} else {
return false;
}
}
export function isWrappedTsNodeExpr(expr: Expression): expr is WrappedNodeExpr<ts.Node> {
return expr instanceof WrappedNodeExpr;
}
export function readBaseClass(
node: ClassDeclaration, reflector: ReflectionHost,
evaluator: PartialEvaluator): Reference<ClassDeclaration>|'dynamic'|null {
if (!isNamedClassDeclaration(node)) {
// If the node isn't a ts.ClassDeclaration, consider any base class to be dynamic for now.
return reflector.hasBaseClass(node) ? 'dynamic' : null;
}
const baseExpression = reflector.getBaseClassExpression(node);
if (baseExpression !== null) {
const baseClass = evaluator.evaluate(baseExpression);
if (baseClass instanceof Reference && isNamedClassDeclaration(baseClass.node)) {
return baseClass as Reference<ClassDeclaration>;
} else {
return 'dynamic';
}
}
return null;
}