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:
Alex Rickabaugh
2018-07-16 16:36:31 -07:00
committed by Ben Lesh
parent fba276d3d1
commit 5be186035f
29 changed files with 451 additions and 205 deletions

View File

@ -9,103 +9,103 @@
import {InjectFlags} from './core';
import {Identifiers} from './identifiers';
import * as o from './output/output_ast';
import {R3DependencyMetadata, compileFactoryFunction} from './render3/r3_factory';
import {R3DependencyMetadata, R3FactoryDelegateType, R3FactoryMetadata, compileFactoryFunction} from './render3/r3_factory';
import {mapToMapExpression} from './render3/util';
export interface InjectableDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
export interface R3InjectableMetadata {
name: string;
type: o.Expression;
ctorDeps: R3DependencyMetadata[]|null;
providedIn: o.Expression;
useClass?: o.Expression;
useFactory?: o.Expression;
useExisting?: o.Expression;
useValue?: o.Expression;
deps?: R3DependencyMetadata[];
userDeps?: R3DependencyMetadata[];
}
export function compileInjectable(meta: R3InjectableMetadata): InjectableDef {
let factory: o.Expression = o.NULL_EXPR;
let result: {factory: o.Expression, statements: o.Statement[]}|null = null;
function makeFn(ret: o.Expression): o.Expression {
return o.fn([], [new o.ReturnStatement(ret)], undefined, undefined, `${meta.name}_Factory`);
}
if (meta.useClass !== undefined || meta.useFactory !== undefined) {
// First, handle useClass and useFactory together, since both involve a similar call to
// `compileFactoryFunction`. Either dependencies are explicitly specified, in which case
// a factory function call is generated, or they're not specified and the calls are special-
// cased.
if (meta.deps !== undefined) {
// Either call `new meta.useClass(...)` or `meta.useFactory(...)`.
const fnOrClass: o.Expression = meta.useClass || meta.useFactory !;
const factoryMeta = {
name: meta.name,
type: meta.type,
deps: meta.ctorDeps,
injectFn: Identifiers.inject,
};
// useNew: true if meta.useClass, false for meta.useFactory.
const useNew = meta.useClass !== undefined;
if (meta.useClass !== undefined) {
// meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
// used to instantiate the class with dependencies injected, or deps are not specified and
// the factory of the class is used to instantiate it.
//
// A special case exists for useClass: Type where Type is the injectable type itself, in which
// case omitting deps just uses the constructor dependencies instead.
factory = compileFactoryFunction({
name: meta.name,
fnOrClass,
useNew,
injectFn: Identifiers.inject,
deps: meta.deps,
const useClassOnSelf = meta.useClass.isEquivalent(meta.type);
const deps = meta.userDeps || (useClassOnSelf && meta.ctorDeps) || undefined;
if (deps !== undefined) {
// factory: () => new meta.useClass(...deps)
result = compileFactoryFunction({
...factoryMeta,
delegate: meta.useClass,
delegateDeps: deps,
delegateType: R3FactoryDelegateType.Class,
});
} else if (meta.useClass !== undefined) {
// Special case for useClass where the factory from the class's ngInjectableDef is used.
if (meta.useClass.isEquivalent(meta.type)) {
// For the injectable compiler, useClass represents a foreign type that should be
// instantiated to satisfy construction of the given type. It's not valid to specify
// useClass === type, since the useClass type is expected to already be compiled.
throw new Error(
`useClass is the same as the type, but no deps specified, which is invalid.`);
}
factory =
makeFn(new o.ReadPropExpr(new o.ReadPropExpr(meta.useClass, 'ngInjectableDef'), 'factory')
.callFn([]));
} else if (meta.useFactory !== undefined) {
// Special case for useFactory where no arguments are passed.
factory = meta.useFactory.callFn([]);
} else {
// Can't happen - outer conditional guards against both useClass and useFactory being
// undefined.
throw new Error('Reached unreachable block in injectable compiler.');
result = compileFactoryFunction({
...factoryMeta,
delegate: meta.useClass,
delegateType: R3FactoryDelegateType.Factory,
});
}
} else if (meta.useFactory !== undefined) {
result = compileFactoryFunction({
...factoryMeta,
delegate: meta.useFactory,
delegateDeps: meta.userDeps || [],
delegateType: R3FactoryDelegateType.Function,
});
} else if (meta.useValue !== undefined) {
// Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
// client code because meta.useValue is an Expression which will be defined even if the actual
// value is undefined.
factory = makeFn(meta.useValue);
result = compileFactoryFunction({
...factoryMeta,
expression: meta.useValue,
});
} else if (meta.useExisting !== undefined) {
// useExisting is an `inject` call on the existing token.
factory = makeFn(o.importExpr(Identifiers.inject).callFn([meta.useExisting]));
} else {
// A strict type is compiled according to useClass semantics, except the dependencies are
// required.
if (meta.deps === undefined) {
throw new Error(`Type compilation of an injectable requires dependencies.`);
}
factory = compileFactoryFunction({
name: meta.name,
fnOrClass: meta.type,
useNew: true,
injectFn: Identifiers.inject,
deps: meta.deps,
result = compileFactoryFunction({
...factoryMeta,
expression: o.importExpr(Identifiers.inject).callFn([meta.useExisting]),
});
} else {
result = compileFactoryFunction(factoryMeta);
}
const token = meta.type;
const providedIn = meta.providedIn;
const expression = o.importExpr(Identifiers.defineInjectable).callFn([mapToMapExpression(
{token, factory, providedIn})]);
{token, factory: result.factory, providedIn})]);
const type = new o.ExpressionType(
o.importExpr(Identifiers.InjectableDef, [new o.ExpressionType(meta.type)]));
return {
expression, type,
expression,
type,
statements: result.statements,
};
}

View File

@ -15,12 +15,13 @@ import * as o from '../output/output_ast';
import {Identifiers as R3} from '../render3/r3_identifiers';
import {OutputContext} from '../util';
import {unsupported} from './view/util';
import {MEANING_SEPARATOR, unsupported} from './view/util';
/**
* Metadata required by the factory generator to generate a `factory` function for a type.
*/
export interface R3FactoryMetadata {
export interface R3ConstructorFactoryMetadata {
/**
* String name of the type being generated (used to name the factory function).
*/
@ -33,21 +34,15 @@ export interface R3FactoryMetadata {
* This could be a reference to a constructor type, or to a user-defined factory function. The
* `useNew` property determines whether it will be called as a constructor or not.
*/
fnOrClass: o.Expression;
type: o.Expression;
/**
* Regardless of whether `fnOrClass` is a constructor function or a user-defined factory, it
* may have 0 or more parameters, which will be injected according to the `R3DependencyMetadata`
* for those parameters.
* for those parameters. If this is `null`, then the type's constructor is nonexistent and will
* be inherited from `fnOrClass` which is interpreted as the current type.
*/
deps: R3DependencyMetadata[];
/**
* Whether to interpret `fnOrClass` as a constructor function (`useNew: true`) or as a factory
* (`useNew: false`).
*/
useNew: boolean;
deps: R3DependencyMetadata[]|null;
/**
* An expression for the function which will be used to inject dependencies. The API of this
@ -56,6 +51,30 @@ export interface R3FactoryMetadata {
injectFn: o.ExternalReference;
}
export enum R3FactoryDelegateType {
Class,
Function,
Factory,
}
export interface R3DelegatedFactoryMetadata extends R3ConstructorFactoryMetadata {
delegate: o.Expression;
delegateType: R3FactoryDelegateType.Factory;
}
export interface R3DelegatedFnOrClassMetadata extends R3ConstructorFactoryMetadata {
delegate: o.Expression;
delegateType: R3FactoryDelegateType.Class|R3FactoryDelegateType.Function;
delegateDeps: R3DependencyMetadata[];
}
export interface R3ExpressionFactoryMetadata extends R3ConstructorFactoryMetadata {
expression: o.Expression;
}
export type R3FactoryMetadata = R3ConstructorFactoryMetadata | R3DelegatedFactoryMetadata |
R3DelegatedFnOrClassMetadata | R3ExpressionFactoryMetadata;
/**
* Resolved type of a dependency.
*
@ -142,16 +161,84 @@ export interface R3DependencyMetadata {
/**
* Construct a factory function expression for the given `R3FactoryMetadata`.
*/
export function compileFactoryFunction(meta: R3FactoryMetadata): o.Expression {
// Each dependency becomes an invocation of an inject*() function.
const args = meta.deps.map(dep => compileInjectDependency(dep, meta.injectFn));
export function compileFactoryFunction(meta: R3FactoryMetadata):
{factory: o.Expression, statements: o.Statement[]} {
const t = o.variable('t');
const statements: o.Statement[] = [];
// The overall result depends on whether this is construction or function invocation.
const expr = meta.useNew ? new o.InstantiateExpr(meta.fnOrClass, args) :
new o.InvokeFunctionExpr(meta.fnOrClass, args);
// The type to instantiate via constructor invocation. If there is no delegated factory, meaning
// this type is always created by constructor invocation, then this is the type-to-create
// parameter provided by the user (t) if specified, or the current type if not. If there is a
// delegated factory (which is used to create the current type) then this is only the type-to-
// create parameter (t).
const typeForCtor =
!isDelegatedMetadata(meta) ? new o.BinaryOperatorExpr(o.BinaryOperator.Or, t, meta.type) : t;
return o.fn(
[], [new o.ReturnStatement(expr)], o.INFERRED_TYPE, undefined, `${meta.name}_Factory`);
let ctorExpr: o.Expression|null = null;
if (meta.deps !== null) {
// There is a constructor (either explicitly or implicitly defined).
ctorExpr = new o.InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn));
} else {
const baseFactory = o.variable(`ɵ${meta.name}_BaseFactory`);
const getInheritedFactory = o.importExpr(R3.getInheritedFactory);
const baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.type])).toDeclStmt();
statements.push(baseFactoryStmt);
// There is no constructor, use the base class' factory to construct typeForCtor.
ctorExpr = baseFactory.callFn([typeForCtor]);
}
const ctorExprFinal = ctorExpr;
const body: o.Statement[] = [];
let retExpr: o.Expression|null = null;
function makeConditionalFactory(nonCtorExpr: o.Expression): o.ReadVarExpr {
const r = o.variable('r');
body.push(r.set(o.NULL_EXPR).toDeclStmt());
body.push(o.ifStmt(t, [r.set(ctorExprFinal).toStmt()], [r.set(nonCtorExpr).toStmt()]));
return r;
}
if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) {
const delegateFactory = o.variable(`ɵ${meta.name}_BaseFactory`);
const getFactoryOf = o.importExpr(R3.getFactoryOf);
if (meta.delegate.isEquivalent(meta.type)) {
throw new Error(`Illegal state: compiling factory that delegates to itself`);
}
const delegateFactoryStmt =
delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt();
statements.push(delegateFactoryStmt);
const r = makeConditionalFactory(delegateFactory.callFn([]));
retExpr = r;
} else if (isDelegatedMetadata(meta)) {
// This type is created with a delegated factory. If a type parameter is not specified, call
// the factory instead.
const delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn);
// Either call `new delegate(...)` or `delegate(...)` depending on meta.useNewForDelegate.
const factoryExpr = new (
meta.delegateType === R3FactoryDelegateType.Class ?
o.InstantiateExpr :
o.InvokeFunctionExpr)(meta.delegate, delegateArgs);
retExpr = makeConditionalFactory(factoryExpr);
} else if (isExpressionFactoryMetadata(meta)) {
// TODO(alxhub): decide whether to lower the value here or in the caller
retExpr = makeConditionalFactory(meta.expression);
} else {
retExpr = ctorExpr;
}
return {
factory: o.fn(
[new o.FnParam('t', o.DYNAMIC_TYPE)], [...body, new o.ReturnStatement(retExpr)],
o.INFERRED_TYPE, undefined, `${meta.name}_Factory`),
statements,
};
}
function injectDependencies(
deps: R3DependencyMetadata[], injectFn: o.ExternalReference): o.Expression[] {
return deps.map(dep => compileInjectDependency(dep, injectFn));
}
function compileInjectDependency(
@ -253,3 +340,12 @@ export function dependenciesFromGlobalMetadata(
return deps;
}
function isDelegatedMetadata(meta: R3FactoryMetadata): meta is R3DelegatedFactoryMetadata|
R3DelegatedFnOrClassMetadata {
return (meta as any).delegateType !== undefined;
}
function isExpressionFactoryMetadata(meta: R3FactoryMetadata): meta is R3ExpressionFactoryMetadata {
return (meta as any).expression !== undefined;
}

View File

@ -162,6 +162,16 @@ export class Identifiers {
static listener: o.ExternalReference = {name: 'ɵL', moduleName: CORE};
static getFactoryOf: o.ExternalReference = {
name: 'ɵgetFactoryOf',
moduleName: CORE,
};
static getInheritedFactory: o.ExternalReference = {
name: 'ɵgetInheritedFactory',
moduleName: CORE,
};
// Reserve slots for pure functions
static reserveSlots: o.ExternalReference = {name: 'ɵrS', moduleName: CORE};

View File

@ -60,12 +60,12 @@ class R3JitReflector implements CompileReflector {
*/
export function jitExpression(
def: o.Expression, context: {[key: string]: any}, sourceUrl: string,
constantPool?: ConstantPool): any {
preStatements: o.Statement[]): any {
// The ConstantPool may contain Statements which declare variables used in the final expression.
// Therefore, its statements need to precede the actual JIT operation. The final statement is a
// declaration of $def which is set to the expression being compiled.
const statements: o.Statement[] = [
...(constantPool !== undefined ? constantPool.statements : []),
...preStatements,
new o.DeclareVarStmt('$def', def, undefined, [o.StmtModifier.Exported]),
];

View File

@ -85,31 +85,32 @@ export function compileNgModule(meta: R3NgModuleMetadata): R3NgModuleDef {
export interface R3InjectorDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
export interface R3InjectorMetadata {
name: string;
type: o.Expression;
deps: R3DependencyMetadata[];
deps: R3DependencyMetadata[]|null;
providers: o.Expression;
imports: o.Expression;
}
export function compileInjector(meta: R3InjectorMetadata): R3InjectorDef {
const result = compileFactoryFunction({
name: meta.name,
type: meta.type,
deps: meta.deps,
injectFn: R3.inject,
});
const expression = o.importExpr(R3.defineInjector).callFn([mapToMapExpression({
factory: compileFactoryFunction({
name: meta.name,
fnOrClass: meta.type,
deps: meta.deps,
useNew: true,
injectFn: R3.inject,
}),
factory: result.factory,
providers: meta.providers,
imports: meta.imports,
})]);
const type =
new o.ExpressionType(o.importExpr(R3.InjectorDef, [new o.ExpressionType(meta.type)]));
return {expression, type};
return {expression, type, statements: result.statements};
}
// TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations.

View File

@ -19,13 +19,14 @@ export interface R3PipeMetadata {
name: string;
type: o.Expression;
pipeName: string;
deps: R3DependencyMetadata[];
deps: R3DependencyMetadata[]|null;
pure: boolean;
}
export interface R3PipeDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
export function compilePipeFromMetadata(metadata: R3PipeMetadata) {
@ -39,12 +40,11 @@ export function compilePipeFromMetadata(metadata: R3PipeMetadata) {
const templateFactory = compileFactoryFunction({
name: metadata.name,
fnOrClass: metadata.type,
type: metadata.type,
deps: metadata.deps,
useNew: true,
injectFn: R3.directiveInject,
});
definitionMapValues.push({key: 'factory', value: templateFactory, quoted: false});
definitionMapValues.push({key: 'factory', value: templateFactory.factory, quoted: false});
// e.g. `pure: true`
definitionMapValues.push({key: 'pure', value: o.literal(metadata.pure), quoted: false});
@ -54,7 +54,7 @@ export function compilePipeFromMetadata(metadata: R3PipeMetadata) {
new o.ExpressionType(metadata.type),
new o.ExpressionType(new o.LiteralExpr(metadata.pipeName)),
]));
return {expression, type};
return {expression, type, statements: templateFactory.statements};
}
/**

View File

@ -38,7 +38,7 @@ export interface R3DirectiveMetadata {
/**
* Dependencies of the directive's constructor.
*/
deps: R3DependencyMetadata[];
deps: R3DependencyMetadata[]|null;
/**
* Unparsed selector of the directive, or `null` if there was no selector.
@ -177,6 +177,7 @@ export interface R3QueryMetadata {
export interface R3DirectiveDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
/**
@ -185,4 +186,5 @@ export interface R3DirectiveDef {
export interface R3ComponentDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}

View File

@ -29,7 +29,7 @@ import {CONTEXT_NAME, DefinitionMap, RENDER_FLAGS, TEMPORARY_NAME, asLiteral, co
function baseDirectiveFields(
meta: R3DirectiveMetadata, constantPool: ConstantPool,
bindingParser: BindingParser): DefinitionMap {
bindingParser: BindingParser): {definitionMap: DefinitionMap, statements: o.Statement[]} {
const definitionMap = new DefinitionMap();
// e.g. `type: MyDirective`
@ -40,13 +40,13 @@ function baseDirectiveFields(
// e.g. `factory: () => new MyApp(injectElementRef())`
definitionMap.set('factory', compileFactoryFunction({
name: meta.name,
fnOrClass: meta.type,
deps: meta.deps,
useNew: true,
injectFn: R3.directiveInject,
}));
const result = compileFactoryFunction({
name: meta.name,
type: meta.type,
deps: meta.deps,
injectFn: R3.directiveInject,
});
definitionMap.set('factory', result.factory);
definitionMap.set('contentQueries', createContentQueriesFunction(meta, constantPool));
@ -80,7 +80,7 @@ function baseDirectiveFields(
definitionMap.set('features', o.literalArr(features));
}
return definitionMap;
return {definitionMap, statements: result.statements};
}
/**
@ -89,7 +89,7 @@ function baseDirectiveFields(
export function compileDirectiveFromMetadata(
meta: R3DirectiveMetadata, constantPool: ConstantPool,
bindingParser: BindingParser): R3DirectiveDef {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
const {definitionMap, statements} = baseDirectiveFields(meta, constantPool, bindingParser);
const expression = o.importExpr(R3.defineDirective).callFn([definitionMap.toLiteralMap()]);
// On the type side, remove newlines from the selector as it will need to fit into a TypeScript
@ -100,7 +100,7 @@ export function compileDirectiveFromMetadata(
typeWithParameters(meta.type, meta.typeArgumentCount),
new o.ExpressionType(o.literal(selectorForType))
]));
return {expression, type};
return {expression, type, statements};
}
/**
@ -109,7 +109,7 @@ export function compileDirectiveFromMetadata(
export function compileComponentFromMetadata(
meta: R3ComponentMetadata, constantPool: ConstantPool,
bindingParser: BindingParser): R3ComponentDef {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
const {definitionMap, statements} = baseDirectiveFields(meta, constantPool, bindingParser);
const selector = meta.selector && CssSelector.parse(meta.selector);
const firstSelector = selector && selector[0];
@ -180,7 +180,7 @@ export function compileComponentFromMetadata(
new o.ExpressionType(o.literal(selectorForType))
]));
return {expression, type};
return {expression, type, statements};
}
/**