refactor(ivy): move directive, component and pipe factories to ngFactoryFn (#31953)

Reworks the compiler to output the factories for directives, components and pipes under a new static field called `ngFactoryFn`, instead of the usual `factory` property in their respective defs. This should eventually allow us to inject any kind of decorated class (e.g. a pipe).

**Note:** these changes are the first part of the refactor and they don't include injectables. I decided to leave injectables for a follow-up PR, because there's some more cases we need to handle when it comes to their factories. Furthermore, directives, components and pipes make up most of the compiler output tests that need to be refactored and it'll make follow-up PRs easier to review if the tests are cleaned up now.

This is part of the larger refactor for FW-1468.

PR Close #31953
This commit is contained in:
Kristiyan Kostadinov
2019-08-12 09:26:20 +03:00
committed by atscott
parent 14feb56139
commit c885178d5f
71 changed files with 894 additions and 675 deletions

View File

@ -39,6 +39,10 @@ export interface CompilerFacade {
angularCoreEnv: CoreEnvironment, sourceMapUrl: string, meta: R3ComponentMetadataFacade): any;
compileBase(angularCoreEnv: CoreEnvironment, sourceMapUrl: string, meta: R3BaseMetadataFacade):
any;
compileFactory(
angularCoreEnv: CoreEnvironment, sourceMapUrl: string,
meta: R3PipeMetadataFacade|R3DirectiveMetadataFacade|R3ComponentMetadataFacade,
isPipe?: boolean): any;
createParseSourceSpan(kind: string, typeName: string, sourceUrl: string): ParseSourceSpan;

View File

@ -156,6 +156,7 @@ export {
ɵɵBaseDef,
ComponentDef as ɵComponentDef,
ɵɵComponentDefWithMeta,
ɵɵFactoryDef,
DirectiveDef as ɵDirectiveDef,
ɵɵDirectiveDefWithMeta,
PipeDef as ɵPipeDef,

View File

@ -10,6 +10,7 @@ import '../util/ng_dev_mode';
import {OnDestroy} from '../interface/lifecycle_hooks';
import {Type} from '../interface/type';
import {getFactoryDef} from '../render3/definition';
import {throwCyclicDependencyError, throwInvalidProviderError, throwMixedMultiProviderError} from '../render3/errors';
import {deepForEach, newArray} from '../util/array_utils';
import {stringify} from '../util/stringify';
@ -398,8 +399,10 @@ export class R3Injector {
function injectableDefOrInjectorDefFactory(token: Type<any>| InjectionToken<any>): () => any {
// Most tokens will have an ngInjectableDef directly on them, which specifies a factory directly.
const injectableDef = getInjectableDef(token);
if (injectableDef !== null) {
return injectableDef.factory;
const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
if (factory !== null) {
return factory;
}
// If the token is an NgModule, it's also injectable but the factory is on its ngInjectorDef.

View File

@ -7,6 +7,7 @@
*/
import '../util/ng_dev_mode';
import {ChangeDetectionStrategy} from '../change_detection/constants';
import {NG_INJECTABLE_DEF, ɵɵdefineInjectable} from '../di/interface/defs';
import {Mutable, Type} from '../interface/type';
@ -15,8 +16,9 @@ import {SchemaMetadata} from '../metadata/schema';
import {ViewEncapsulation} from '../metadata/view';
import {noSideEffects} from '../util/closure';
import {stringify} from '../util/stringify';
import {EMPTY_ARRAY, EMPTY_OBJ} from './empty';
import {NG_BASE_DEF, NG_COMPONENT_DEF, NG_DIRECTIVE_DEF, NG_LOCALE_ID_DEF, NG_MODULE_DEF, NG_PIPE_DEF} from './fields';
import {NG_BASE_DEF, NG_COMPONENT_DEF, NG_DIRECTIVE_DEF, NG_FACTORY_DEF, NG_LOCALE_ID_DEF, NG_MODULE_DEF, NG_PIPE_DEF} from './fields';
import {ComponentDef, ComponentDefFeature, ComponentTemplate, ComponentType, ContentQueriesFunction, DirectiveDef, DirectiveDefFeature, DirectiveType, DirectiveTypesOrFactory, FactoryFn, HostBindingsFunction, PipeDef, PipeType, PipeTypesOrFactory, ViewQueriesFunction, ɵɵBaseDef} from './interfaces/definition';
// while SelectorFlags is unused here, it's required so that types don't get resolved lazily
// see: https://github.com/Microsoft/web-build-tools/issues/1050
@ -49,11 +51,6 @@ export function ɵɵdefineComponent<T>(componentDefinition: {
/** The selectors that will be used to match nodes to this component. */
selectors: CssSelectorList;
/**
* Factory method used to create an instance of directive.
*/
factory: FactoryFn<T>;
/**
* The number of nodes, local refs, and pipes in this component template.
*
@ -251,7 +248,7 @@ export function ɵɵdefineComponent<T>(componentDefinition: {
providersResolver: null,
consts: componentDefinition.consts,
vars: componentDefinition.vars,
factory: componentDefinition.factory,
factory: null,
template: componentDefinition.template || null !,
ngContentSelectors: componentDefinition.ngContentSelectors,
hostBindings: componentDefinition.hostBindings || null,
@ -300,15 +297,6 @@ export function ɵɵdefineComponent<T>(componentDefinition: {
def.pipeDefs = pipeTypes ?
() => (typeof pipeTypes === 'function' ? pipeTypes() : pipeTypes).map(extractPipeDef) :
null;
// Add ngInjectableDef so components are reachable through the module injector by default
// (unless it has already been set by the @Injectable decorator). This is mostly to
// support injecting components in tests. In real application code, components should
// be retrieved through the node injector, so this isn't a problem.
if (!type.hasOwnProperty(NG_INJECTABLE_DEF)) {
(type as any)[NG_INJECTABLE_DEF] =
ɵɵdefineInjectable<T>({token: type, factory: componentDefinition.factory as() => T});
}
}) as never;
return def as never;
@ -615,11 +603,6 @@ export const ɵɵdefineDirective = ɵɵdefineComponent as any as<T>(directiveDef
/** The selectors that will be used to match nodes to this directive. */
selectors: CssSelectorList;
/**
* Factory method used to create an instance of directive.
*/
factory: FactoryFn<T>;
/**
* A map of input names.
*
@ -731,15 +714,13 @@ export function ɵɵdefinePipe<T>(pipeDef: {
/** Pipe class reference. Needed to extract pipe lifecycle hooks. */
type: Type<T>,
/** A factory for creating a pipe instance. */
factory: FactoryFn<T>,
/** Whether the pipe is pure. */
pure?: boolean
}): never {
return (<PipeDef<T>>{
type: pipeDef.type,
name: pipeDef.name,
factory: pipeDef.factory,
factory: null,
pure: pipeDef.pure !== false,
onDestroy: pipeDef.type.prototype.ngOnDestroy || null
}) as never;
@ -752,25 +733,35 @@ export function ɵɵdefinePipe<T>(pipeDef: {
*/
export function getComponentDef<T>(type: any): ComponentDef<T>|null {
return (type as any)[NG_COMPONENT_DEF] || null;
return type[NG_COMPONENT_DEF] || null;
}
export function getDirectiveDef<T>(type: any): DirectiveDef<T>|null {
return (type as any)[NG_DIRECTIVE_DEF] || null;
return type[NG_DIRECTIVE_DEF] || null;
}
export function getPipeDef<T>(type: any): PipeDef<T>|null {
return (type as any)[NG_PIPE_DEF] || null;
return type[NG_PIPE_DEF] || null;
}
export function getBaseDef<T>(type: any): ɵɵBaseDef<T>|null {
return (type as any)[NG_BASE_DEF] || null;
return type[NG_BASE_DEF] || null;
}
export function getFactoryDef<T>(type: any, throwNotFound: true): FactoryFn<T>;
export function getFactoryDef<T>(type: any): FactoryFn<T>|null;
export function getFactoryDef<T>(type: any, throwNotFound?: boolean): FactoryFn<T>|null {
const factoryFn = type[NG_FACTORY_DEF] || null;
if (!factoryFn && throwNotFound === true && ngDevMode) {
throw new Error(`Type ${stringify(type)} does not have 'ngFactoryDef' property.`);
}
return factoryFn;
}
export function getNgModuleDef<T>(type: any, throwNotFound: true): NgModuleDef<T>;
export function getNgModuleDef<T>(type: any): NgModuleDef<T>|null;
export function getNgModuleDef<T>(type: any, throwNotFound?: boolean): NgModuleDef<T>|null {
const ngModuleDef = (type as any)[NG_MODULE_DEF] || null;
const ngModuleDef = type[NG_MODULE_DEF] || null;
if (!ngModuleDef && throwNotFound === true) {
throw new Error(`Type ${stringify(type)} does not have 'ngModuleDef' property.`);
}

View File

@ -15,7 +15,7 @@ import {InjectFlags} from '../di/interface/injector';
import {Type} from '../interface/type';
import {assertDefined, assertEqual} from '../util/assert';
import {getComponentDef, getDirectiveDef, getPipeDef} from './definition';
import {getFactoryDef} from './definition';
import {NG_ELEMENT_ID} from './fields';
import {DirectiveDef, FactoryFn} from './interfaces/definition';
import {NO_PARENT_INJECTOR, NodeInjectorFactory, PARENT_INJECTOR, RelativeInjectorLocation, RelativeInjectorLocationFlags, TNODE, isFactory} from './interfaces/injector';
@ -642,12 +642,10 @@ export function ɵɵgetFactoryOf<T>(type: Type<any>): FactoryFn<T>|null {
}) as any;
}
const def = getComponentDef<T>(typeAny) || getDirectiveDef<T>(typeAny) ||
getPipeDef<T>(typeAny) || getInjectableDef<T>(typeAny) || getInjectorDef<T>(typeAny);
if (!def || def.factory === undefined) {
return null;
}
return def.factory;
// TODO(crisbeto): unify injectable factories with getFactory.
const def = getInjectableDef<T>(typeAny) || getInjectorDef<T>(typeAny);
const factory = def && def.factory || getFactoryDef<T>(typeAny);
return factory || null;
}
/**

View File

@ -14,6 +14,7 @@ export const NG_PIPE_DEF = getClosureSafeProperty({ngPipeDef: getClosureSafeProp
export const NG_MODULE_DEF = getClosureSafeProperty({ngModuleDef: getClosureSafeProperty});
export const NG_LOCALE_ID_DEF = getClosureSafeProperty({ngLocaleIdDef: getClosureSafeProperty});
export const NG_BASE_DEF = getClosureSafeProperty({ngBaseDef: getClosureSafeProperty});
export const NG_FACTORY_DEF = getClosureSafeProperty({ngFactoryDef: getClosureSafeProperty});
/**
* If a directive is diPublic, bloomAdd sets a property on the type with this constant as

View File

@ -10,11 +10,12 @@ import {ɵɵdefineBase, ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineNgMo
import {ɵɵInheritDefinitionFeature} from './features/inherit_definition_feature';
import {ɵɵNgOnChangesFeature} from './features/ng_onchanges_feature';
import {ɵɵProvidersFeature} from './features/providers_feature';
import {ComponentDef, ComponentTemplate, ComponentType, DirectiveDef, DirectiveDefFlags, DirectiveType, PipeDef, ɵɵBaseDef, ɵɵComponentDefWithMeta, ɵɵDirectiveDefWithMeta, ɵɵPipeDefWithMeta} from './interfaces/definition';
import {ComponentDef, ComponentTemplate, ComponentType, DirectiveDef, DirectiveDefFlags, DirectiveType, PipeDef, ɵɵBaseDef, ɵɵComponentDefWithMeta, ɵɵDirectiveDefWithMeta, ɵɵFactoryDef, ɵɵPipeDefWithMeta} from './interfaces/definition';
import {getComponent, getDirectives, getHostElement, getRenderedText} from './util/discovery_utils';
export {ComponentFactory, ComponentFactoryResolver, ComponentRef, injectComponentFactoryResolver} from './component_ref';
export {ɵɵgetFactoryOf, ɵɵgetInheritedFactory} from './di';
// clang-format off
export {
detectChanges,
@ -205,6 +206,7 @@ export {
ɵɵBaseDef,
ComponentDef,
ɵɵComponentDefWithMeta,
ɵɵFactoryDef,
ComponentTemplate,
ComponentType,
DirectiveDef,

View File

@ -15,6 +15,7 @@ import {createNamedArrayType} from '../../util/named_array_type';
import {normalizeDebugBindingName, normalizeDebugBindingValue} from '../../util/ng_reflect';
import {assertFirstTemplatePass, assertLView} from '../assert';
import {attachPatchData, getComponentViewByInstance} from '../context_discovery';
import {getFactoryDef} from '../definition';
import {diPublicInInjector, getNodeInjectable, getOrCreateNodeInjectorForNode} from '../di';
import {throwMultipleComponentError} from '../errors';
import {executeCheckHooks, executeInitAndCheckHooks, incrementInitPhaseFlags, registerPreOrderHooks} from '../hooks';
@ -1028,7 +1029,7 @@ export function instantiateRootComponent<T>(
if (tView.firstTemplatePass) {
if (def.providersResolver) def.providersResolver(def);
generateExpandoInstructionBlock(tView, rootTNode, 1);
baseResolveDirective(tView, viewData, def, def.factory);
baseResolveDirective(tView, viewData, def);
}
const directive =
getNodeInjectable(tView.data, viewData, viewData.length - 1, rootTNode as TElementNode);
@ -1072,7 +1073,7 @@ export function resolveDirectives(
const def = directives[i] as DirectiveDef<any>;
const directiveDefIdx = tView.data.length;
baseResolveDirective(tView, lView, def, def.factory);
baseResolveDirective(tView, lView, def);
saveNameToExportMap(tView.data !.length - 1, def, exportsMap);
@ -1311,9 +1312,9 @@ export function initNodeFlags(tNode: TNode, index: number, numberOfDirectives: n
tNode.providerIndexes = index;
}
function baseResolveDirective<T>(
tView: TView, viewData: LView, def: DirectiveDef<T>, directiveFactory: FactoryFn<T>) {
function baseResolveDirective<T>(tView: TView, viewData: LView, def: DirectiveDef<T>) {
tView.data.push(def);
const directiveFactory = def.factory || (def.factory = getFactoryDef(def.type, true));
const nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), null);
tView.blueprint.push(nodeInjectorFactory);
viewData.push(nodeInjectorFactory);

View File

@ -76,7 +76,10 @@ export interface ComponentType<T> extends Type<T> { ngComponentDef: never; }
* A subclass of `Type` which has a static `ngDirectiveDef`:`DirectiveDef` field making it
* consumable for rendering.
*/
export interface DirectiveType<T> extends Type<T> { ngDirectiveDef: never; }
export interface DirectiveType<T> extends Type<T> {
ngDirectiveDef: never;
ngFactoryDef: () => T;
}
export const enum DirectiveDefFlags {ContentQuery = 0b10}
@ -175,9 +178,10 @@ export interface DirectiveDef<T> extends ɵɵBaseDef<T> {
readonly exportAs: string[]|null;
/**
* Factory function used to create a new directive instance.
* Factory function used to create a new directive instance. Will be null initially.
* Populated when the factory is first requested by directive instantiation logic.
*/
factory: FactoryFn<T>;
factory: FactoryFn<T>|null;
/* The following are lifecycle hooks for this component */
onChanges: (() => void)|null;
@ -207,6 +211,11 @@ export type ɵɵComponentDefWithMeta<
T, Selector extends String, ExportAs extends string[], InputMap extends{[key: string]: string},
OutputMap extends{[key: string]: string}, QueryFields extends string[]> = ComponentDef<T>;
/**
* @codeGenApi
*/
export type ɵɵFactoryDef<T> = () => T;
/**
* Runtime link information for Components.
*
@ -329,6 +338,9 @@ export interface ComponentDef<T> extends DirectiveDef<T> {
* See: {@link definePipe}
*/
export interface PipeDef<T> {
/** Token representing the pipe. */
type: Type<T>;
/**
* Pipe name.
*
@ -337,9 +349,10 @@ export interface PipeDef<T> {
readonly name: string;
/**
* Factory function used to create a new pipe instance.
* Factory function used to create a new pipe instance. Will be null initially.
* Populated when the factory is first requested by pipe instantiation logic.
*/
factory: FactoryFn<T>;
factory: FactoryFn<T>|null;
/**
* Whether or not the pipe is pure.

View File

@ -7,7 +7,7 @@
*/
import {R3DirectiveMetadataFacade, getCompilerFacade} from '../../compiler/compiler_facade';
import {R3BaseMetadataFacade, R3ComponentMetadataFacade, R3QueryMetadataFacade} from '../../compiler/compiler_facade_interface';
import {CompilerFacade, R3BaseMetadataFacade, R3ComponentMetadataFacade, R3QueryMetadataFacade} from '../../compiler/compiler_facade_interface';
import {resolveForwardRef} from '../../di/forward_ref';
import {compileInjectable} from '../../di/jit/injectable';
import {getReflect, reflectDependencies} from '../../di/jit/util';
@ -18,7 +18,7 @@ import {componentNeedsResolution, maybeQueueResolutionOfComponentResources} from
import {ViewEncapsulation} from '../../metadata/view';
import {getBaseDef, getComponentDef, getDirectiveDef} from '../definition';
import {EMPTY_ARRAY, EMPTY_OBJ} from '../empty';
import {NG_BASE_DEF, NG_COMPONENT_DEF, NG_DIRECTIVE_DEF} from '../fields';
import {NG_BASE_DEF, NG_COMPONENT_DEF, NG_DIRECTIVE_DEF, NG_FACTORY_DEF} from '../fields';
import {ComponentType} from '../interfaces/definition';
import {stringifyForError} from '../util/misc_utils';
@ -38,43 +38,31 @@ import {flushModuleScopingQueueAsMuchAsPossible, patchComponentDefWithScope, tra
*/
export function compileComponent(type: Type<any>, metadata: Component): void {
let ngComponentDef: any = null;
let ngFactoryDef: any = null;
// Metadata may have resources which need to be resolved.
maybeQueueResolutionOfComponentResources(type, metadata);
Object.defineProperty(type, NG_FACTORY_DEF, {
get: () => {
if (ngFactoryDef === null) {
const compiler = getCompilerFacade();
const meta = getComponentMetadata(compiler, type, metadata);
ngFactoryDef = compiler.compileFactory(
angularCoreEnv, `ng:///${type.name}/ngFactory.js`, meta.metadata);
}
return ngFactoryDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
Object.defineProperty(type, NG_COMPONENT_DEF, {
get: () => {
const compiler = getCompilerFacade();
if (ngComponentDef === null) {
if (componentNeedsResolution(metadata)) {
const error = [`Component '${type.name}' is not resolved:`];
if (metadata.templateUrl) {
error.push(` - templateUrl: ${metadata.templateUrl}`);
}
if (metadata.styleUrls && metadata.styleUrls.length) {
error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
}
error.push(`Did you run and wait for 'resolveComponentResources()'?`);
throw new Error(error.join('\n'));
}
const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
const meta: R3ComponentMetadataFacade = {
...directiveMetadata(type, metadata),
typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl),
template: metadata.template || '',
preserveWhitespaces: metadata.preserveWhitespaces || false,
styles: metadata.styles || EMPTY_ARRAY,
animations: metadata.animations,
directives: [],
changeDetection: metadata.changeDetection,
pipes: new Map(),
encapsulation: metadata.encapsulation || ViewEncapsulation.Emulated,
interpolation: metadata.interpolation,
viewProviders: metadata.viewProviders || null,
};
if (meta.usesInheritance) {
addBaseDefToUndecoratedParents(type);
}
ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
const compiler = getCompilerFacade();
const meta = getComponentMetadata(compiler, type, metadata);
ngComponentDef = compiler.compileComponent(angularCoreEnv, meta.templateUrl, meta.metadata);
// When NgModule decorator executed, we enqueued the module definition such that
// it would only dequeue and add itself as module scope to all of its declarations,
@ -98,13 +86,46 @@ export function compileComponent(type: Type<any>, metadata: Component): void {
configurable: !!ngDevMode,
});
// Add ngInjectableDef so components are reachable through the module injector by default
// This is mostly to support injecting components in tests. In real application code,
// components should be retrieved through the node injector, so this isn't a problem.
compileInjectable(type);
}
function getComponentMetadata(compiler: CompilerFacade, type: Type<any>, metadata: Component) {
if (componentNeedsResolution(metadata)) {
const error = [`Component '${type.name}' is not resolved:`];
if (metadata.templateUrl) {
error.push(` - templateUrl: ${metadata.templateUrl}`);
}
if (metadata.styleUrls && metadata.styleUrls.length) {
error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
}
error.push(`Did you run and wait for 'resolveComponentResources()'?`);
throw new Error(error.join('\n'));
}
const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
const meta: R3ComponentMetadataFacade = {
...directiveMetadata(type, metadata),
typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl),
template: metadata.template || '',
preserveWhitespaces: metadata.preserveWhitespaces || false,
styles: metadata.styles || EMPTY_ARRAY,
animations: metadata.animations,
directives: [],
changeDetection: metadata.changeDetection,
pipes: new Map(),
encapsulation: metadata.encapsulation || ViewEncapsulation.Emulated,
interpolation: metadata.interpolation,
viewProviders: metadata.viewProviders || null,
};
if (meta.usesInheritance) {
addBaseDefToUndecoratedParents(type);
}
return {metadata: meta, templateUrl};
}
function hasSelectorScope<T>(component: Type<T>): component is Type<T>&
{ngSelectorScope: Type<any>} {
return (component as{ngSelectorScope?: any}).ngSelectorScope !== undefined;
@ -119,21 +140,33 @@ function hasSelectorScope<T>(component: Type<T>): component is Type<T>&
*/
export function compileDirective(type: Type<any>, directive: Directive | null): void {
let ngDirectiveDef: any = null;
Object.defineProperty(type, NG_DIRECTIVE_DEF, {
let ngFactoryDef: any = null;
Object.defineProperty(type, NG_FACTORY_DEF, {
get: () => {
if (ngDirectiveDef === null) {
const name = type && type.name;
const sourceMapUrl = `ng:///${name}/ngDirectiveDef.js`;
const compiler = getCompilerFacade();
if (ngFactoryDef === null) {
// `directive` can be null in the case of abstract directives as a base class
// that use `@Directive()` with no selector. In that case, pass empty object to the
// `directiveMetadata` function instead of null.
const facade = directiveMetadata(type as ComponentType<any>, directive || {});
facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
if (facade.usesInheritance) {
addBaseDefToUndecoratedParents(type);
}
ngDirectiveDef = compiler.compileDirective(angularCoreEnv, sourceMapUrl, facade);
const meta = getDirectiveMetadata(type, directive || {});
ngFactoryDef = getCompilerFacade().compileFactory(
angularCoreEnv, `ng:///${type.name}/ngFactory.js`, meta.metadata);
}
return ngFactoryDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
Object.defineProperty(type, NG_DIRECTIVE_DEF, {
get: () => {
if (ngDirectiveDef === null) {
// `directive` can be null in the case of abstract directives as a base class
// that use `@Directive()` with no selector. In that case, pass empty object to the
// `directiveMetadata` function instead of null.
const meta = getDirectiveMetadata(type, directive || {});
ngDirectiveDef =
getCompilerFacade().compileDirective(angularCoreEnv, meta.sourceMapUrl, meta.metadata);
}
return ngDirectiveDef;
},
@ -147,6 +180,18 @@ export function compileDirective(type: Type<any>, directive: Directive | null):
compileInjectable(type);
}
function getDirectiveMetadata(type: Type<any>, metadata: Directive) {
const name = type && type.name;
const sourceMapUrl = `ng:///${name}/ngDirectiveDef.js`;
const compiler = getCompilerFacade();
const facade = directiveMetadata(type as ComponentType<any>, metadata);
facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
if (facade.usesInheritance) {
addBaseDefToUndecoratedParents(type);
}
return {metadata: facade, sourceMapUrl};
}
export function extendsDirectlyFromObject(type: Type<any>): boolean {
return Object.getPrototypeOf(type.prototype) === Object.prototype;
}

View File

@ -10,25 +10,33 @@ import {getCompilerFacade} from '../../compiler/compiler_facade';
import {reflectDependencies} from '../../di/jit/util';
import {Type} from '../../interface/type';
import {Pipe} from '../../metadata/directives';
import {NG_PIPE_DEF} from '../fields';
import {NG_FACTORY_DEF, NG_PIPE_DEF} from '../fields';
import {angularCoreEnv} from './environment';
export function compilePipe(type: Type<any>, meta: Pipe): void {
let ngPipeDef: any = null;
let ngFactoryDef: any = null;
Object.defineProperty(type, NG_FACTORY_DEF, {
get: () => {
if (ngFactoryDef === null) {
const metadata = getPipeMetadata(type, meta);
ngFactoryDef = getCompilerFacade().compileFactory(
angularCoreEnv, `ng:///${metadata.name}/ngFactory.js`, metadata, true);
}
return ngFactoryDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
Object.defineProperty(type, NG_PIPE_DEF, {
get: () => {
if (ngPipeDef === null) {
const typeName = type.name;
ngPipeDef =
getCompilerFacade().compilePipe(angularCoreEnv, `ng:///${typeName}/ngPipeDef.js`, {
type: type,
typeArgumentCount: 0,
name: typeName,
deps: reflectDependencies(type),
pipeName: meta.name,
pure: meta.pure !== undefined ? meta.pure : true
});
const metadata = getPipeMetadata(type, meta);
ngPipeDef = getCompilerFacade().compilePipe(
angularCoreEnv, `ng:///${metadata.name}/ngPipeDef.js`, metadata);
}
return ngPipeDef;
},
@ -36,3 +44,14 @@ export function compilePipe(type: Type<any>, meta: Pipe): void {
configurable: !!ngDevMode,
});
}
function getPipeMetadata(type: Type<any>, meta: Pipe) {
return {
type: type,
typeArgumentCount: 0,
name: type.name,
deps: reflectDependencies(type),
pipeName: meta.name,
pure: meta.pure !== undefined ? meta.pure : true
};
}

View File

@ -9,6 +9,7 @@
import {WrappedValue} from '../change_detection/change_detection_util';
import {PipeTransform} from '../change_detection/pipe_transform';
import {getFactoryDef} from './definition';
import {store} from './instructions/all';
import {PipeDef, PipeDefList} from './interfaces/definition';
import {BINDING_INDEX, HEADER_OFFSET, TVIEW} from './interfaces/view';
@ -43,7 +44,8 @@ export function ɵɵpipe(index: number, pipeName: string): any {
pipeDef = tView.data[adjustedIndex] as PipeDef<any>;
}
const pipeInstance = pipeDef.factory();
const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
const pipeInstance = pipeFactory();
store(index, pipeInstance);
return pipeInstance;
}