feat(ivy): enable inheritance of factory functions in definitions (#25392)
This commit creates an API for factory functions which allows them to be inherited from one another. To do so, it differentiates between the factory function as a wrapper for a constructor and the factory function in ngInjectableDefs which is determined by a default provider. The new form is: factory: (t?) => new (t || SomeType)(inject(Dep1), inject(Dep2)) The 't' parameter allows for constructor inheritance. A subclass with no declared constructor inherits its constructor from the superclass. With the 't' parameter, a subclass can call the superclass' factory function and use it to create an instance of the subclass. For @Injectables with configured providers, the factory function is of the form: factory: (t?) => t ? constructorInject(t) : provider(); where constructorInject(t) creates an instance of 't' using the naturally declared constructor of the type, and where provider() creates an instance of the base type using the special declared provider on @Injectable. PR Close #25392
This commit is contained in:

committed by
Ben Lesh

parent
fba276d3d1
commit
5be186035f
@ -127,7 +127,7 @@ describe('Renderer', () => {
|
||||
.toBe(analyzedFile.analyzedClasses[0]);
|
||||
expect(renderer.addDefinitions.calls.first().args[2])
|
||||
.toEqual(
|
||||
`A.ngDirectiveDef = ɵngcc0.ɵdefineDirective({ type: A, selectors: [["", "a", ""]], factory: function A_Factory() { return new A(); }, features: [ɵngcc0.ɵPublicFeature] });`);
|
||||
`A.ngDirectiveDef = ɵngcc0.ɵdefineDirective({ type: A, selectors: [["", "a", ""]], factory: function A_Factory(t) { return new (t || A)(); }, features: [ɵngcc0.ɵPublicFeature] });`);
|
||||
});
|
||||
|
||||
it('should call removeDecorators with the source code, a map of class decorators that have been analyzed',
|
||||
|
@ -38,7 +38,7 @@ export class InjectableDecoratorHandler implements DecoratorHandler<R3Injectable
|
||||
return {
|
||||
name: 'ngInjectableDef',
|
||||
initializer: res.expression,
|
||||
statements: [],
|
||||
statements: res.statements,
|
||||
type: res.type,
|
||||
};
|
||||
}
|
||||
@ -56,6 +56,7 @@ function extractInjectableMetadata(
|
||||
}
|
||||
const name = clazz.name.text;
|
||||
const type = new WrappedNodeExpr(clazz.name);
|
||||
const ctorDeps = getConstructorDependencies(clazz, reflector, isCore);
|
||||
if (decorator.args === null) {
|
||||
throw new Error(`@Injectable must be called`);
|
||||
}
|
||||
@ -63,8 +64,7 @@ function extractInjectableMetadata(
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
providedIn: new LiteralExpr(null),
|
||||
deps: getConstructorDependencies(clazz, reflector, isCore),
|
||||
providedIn: new LiteralExpr(null), ctorDeps,
|
||||
};
|
||||
} else if (decorator.args.length === 1) {
|
||||
const metaNode = decorator.args[0];
|
||||
@ -81,30 +81,49 @@ function extractInjectableMetadata(
|
||||
if (meta.has('providedIn')) {
|
||||
providedIn = new WrappedNodeExpr(meta.get('providedIn') !);
|
||||
}
|
||||
|
||||
let userDeps: R3DependencyMetadata[]|undefined = undefined;
|
||||
if ((meta.has('useClass') || meta.has('useFactory')) && meta.has('deps')) {
|
||||
const depsExpr = meta.get('deps') !;
|
||||
if (!ts.isArrayLiteralExpression(depsExpr)) {
|
||||
throw new Error(`In Ivy, deps metadata must be inline.`);
|
||||
}
|
||||
if (depsExpr.elements.length > 0) {
|
||||
throw new Error(`deps not yet supported`);
|
||||
}
|
||||
userDeps = depsExpr.elements.map(dep => getDep(dep, reflector));
|
||||
}
|
||||
|
||||
if (meta.has('useValue')) {
|
||||
return {name, type, providedIn, useValue: new WrappedNodeExpr(meta.get('useValue') !)};
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
ctorDeps,
|
||||
providedIn,
|
||||
useValue: new WrappedNodeExpr(meta.get('useValue') !)
|
||||
};
|
||||
} else if (meta.has('useExisting')) {
|
||||
return {name, type, providedIn, useExisting: new WrappedNodeExpr(meta.get('useExisting') !)};
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
ctorDeps,
|
||||
providedIn,
|
||||
useExisting: new WrappedNodeExpr(meta.get('useExisting') !)
|
||||
};
|
||||
} else if (meta.has('useClass')) {
|
||||
return {name, type, providedIn, useClass: new WrappedNodeExpr(meta.get('useClass') !)};
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
ctorDeps,
|
||||
providedIn,
|
||||
useClass: new WrappedNodeExpr(meta.get('useClass') !), userDeps
|
||||
};
|
||||
} else if (meta.has('useFactory')) {
|
||||
// useFactory is special - the 'deps' property must be analyzed.
|
||||
const factory = new WrappedNodeExpr(meta.get('useFactory') !);
|
||||
const deps: R3DependencyMetadata[] = [];
|
||||
if (meta.has('deps')) {
|
||||
const depsExpr = meta.get('deps') !;
|
||||
if (!ts.isArrayLiteralExpression(depsExpr)) {
|
||||
throw new Error(`In Ivy, deps metadata must be inline.`);
|
||||
}
|
||||
if (depsExpr.elements.length > 0) {
|
||||
throw new Error(`deps not yet supported`);
|
||||
}
|
||||
deps.push(...depsExpr.elements.map(dep => getDep(dep, reflector)));
|
||||
}
|
||||
return {name, type, providedIn, useFactory: factory, deps};
|
||||
return {name, type, providedIn, useFactory: factory, ctorDeps, userDeps};
|
||||
} else {
|
||||
const deps = getConstructorDependencies(clazz, reflector, isCore);
|
||||
return {name, type, providedIn, deps};
|
||||
return {name, type, providedIn, ctorDeps};
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Too many arguments to @Injectable`);
|
||||
|
@ -13,10 +13,17 @@ import {Decorator, ReflectionHost} from '../../host';
|
||||
import {AbsoluteReference, ImportMode, Reference} from '../../metadata';
|
||||
|
||||
export function getConstructorDependencies(
|
||||
clazz: ts.ClassDeclaration, reflector: ReflectionHost,
|
||||
isCore: boolean): R3DependencyMetadata[] {
|
||||
clazz: ts.ClassDeclaration, reflector: ReflectionHost, isCore: boolean): R3DependencyMetadata[]|
|
||||
null {
|
||||
const useType: R3DependencyMetadata[] = [];
|
||||
const ctorParams = reflector.getConstructorParameters(clazz) || [];
|
||||
let ctorParams = reflector.getConstructorParameters(clazz);
|
||||
if (ctorParams === null) {
|
||||
if (reflector.hasBaseClass(clazz)) {
|
||||
return null;
|
||||
} else {
|
||||
ctorParams = [];
|
||||
}
|
||||
}
|
||||
ctorParams.forEach((param, idx) => {
|
||||
let tokenExpr = param.type;
|
||||
let optional = false, self = false, skipSelf = false, host = false;
|
||||
|
@ -338,4 +338,6 @@ export interface ReflectionHost {
|
||||
* Check whether the given declaration node actually represents a class.
|
||||
*/
|
||||
isClass(node: ts.Declaration): boolean;
|
||||
|
||||
hasBaseClass(node: ts.Declaration): boolean;
|
||||
}
|
||||
|
@ -132,6 +132,11 @@ export class TypeScriptReflectionHost implements ReflectionHost {
|
||||
return ts.isClassDeclaration(node);
|
||||
}
|
||||
|
||||
hasBaseClass(node: ts.Declaration): boolean {
|
||||
return ts.isClassDeclaration(node) && node.heritageClauses !== undefined &&
|
||||
node.heritageClauses.some(clause => clause.token === ts.SyntaxKind.ExtendsKeyword);
|
||||
}
|
||||
|
||||
getDeclarationOfIdentifier(id: ts.Identifier): Declaration|null {
|
||||
// Resolve the identifier to a Symbol, and return the declaration of that.
|
||||
let symbol: ts.Symbol|undefined = this.checker.getSymbolAtLocation(id);
|
||||
|
@ -72,7 +72,7 @@ class IvyVisitor extends Visitor {
|
||||
node.modifiers, node.name, node.typeParameters, node.heritageClauses || [],
|
||||
// Map over the class members and remove any Angular decorators from them.
|
||||
members.map(member => this._stripAngularDecorators(member)));
|
||||
return {node, before: statements};
|
||||
return {node, after: statements};
|
||||
}
|
||||
|
||||
return {node};
|
||||
|
@ -14,7 +14,8 @@ import * as ts from 'typescript';
|
||||
*/
|
||||
export type VisitListEntryResult<B extends ts.Node, T extends B> = {
|
||||
node: T,
|
||||
before?: B[]
|
||||
before?: B[],
|
||||
after?: B[],
|
||||
};
|
||||
|
||||
/**
|
||||
@ -35,6 +36,11 @@ export abstract class Visitor {
|
||||
*/
|
||||
private _before = new Map<ts.Node, ts.Statement[]>();
|
||||
|
||||
/**
|
||||
* Maps statements to an array of statements that should be inserted after them.
|
||||
*/
|
||||
private _after = new Map<ts.Node, ts.Statement[]>();
|
||||
|
||||
/**
|
||||
* Visit a class declaration, returning at least the transformed declaration and optionally other
|
||||
* nodes to insert before the declaration.
|
||||
@ -52,6 +58,10 @@ export abstract class Visitor {
|
||||
// parent's _visit call is responsible for performing this insertion.
|
||||
this._before.set(result.node, result.before);
|
||||
}
|
||||
if (result.after !== undefined) {
|
||||
// Same with nodes that should be inserted after.
|
||||
this._after.set(result.node, result.after);
|
||||
}
|
||||
return result.node;
|
||||
}
|
||||
|
||||
@ -88,8 +98,9 @@ export abstract class Visitor {
|
||||
|
||||
private _maybeProcessStatements<T extends ts.Node&{statements: ts.NodeArray<ts.Statement>}>(
|
||||
node: T): T {
|
||||
// Shortcut - if every statement doesn't require nodes to be prepended, this is a no-op.
|
||||
if (node.statements.every(stmt => !this._before.has(stmt))) {
|
||||
// Shortcut - if every statement doesn't require nodes to be prepended or appended,
|
||||
// this is a no-op.
|
||||
if (node.statements.every(stmt => !this._before.has(stmt) && !this._after.has(stmt))) {
|
||||
return node;
|
||||
}
|
||||
|
||||
@ -104,6 +115,10 @@ export abstract class Visitor {
|
||||
this._before.delete(stmt);
|
||||
}
|
||||
newStatements.push(stmt);
|
||||
if (this._after.has(stmt)) {
|
||||
newStatements.push(...(this._after.get(stmt) !as ts.Statement[]));
|
||||
this._after.delete(stmt);
|
||||
}
|
||||
});
|
||||
clone.statements = ts.createNodeArray(newStatements, node.statements.hasTrailingComma);
|
||||
return clone;
|
||||
|
Reference in New Issue
Block a user