refactor(compiler): replace `CompileIdentifierMap` with regular `Map`

closes #11145

Also rename `CompileIdentifierMetadata.runtime` into `CompileIdentifierMetadata.reference`.

Also remove `CompileIdentifierMetadata.equalsTo` as
now it is enough to just check the `reference` fields for equality.
This commit is contained in:
Tobias Bosch 2016-08-29 08:52:25 -07:00 committed by Victor Berchet
parent 51877ef4ed
commit d7de5c4f8e
27 changed files with 347 additions and 471 deletions

View File

@ -42,12 +42,12 @@ export class StaticAndDynamicReflectionCapabilities {
setter(name: string) { return this.dynamicDelegate.setter(name); }
method(name: string) { return this.dynamicDelegate.method(name); }
importUri(type: any): string { return this.staticDelegate.importUri(type); }
resolveType(name: string, moduleUrl: string) {
return this.staticDelegate.resolveType(name, moduleUrl);
resolveIdentifier(name: string, moduleUrl: string, runtime: any) {
return this.staticDelegate.resolveIdentifier(name, moduleUrl, runtime);
}
resolveEnum(enumType: any, name: string): any {
if (isStaticType(enumType)) {
return this.staticDelegate.resolveEnum(enumType, name);
resolveEnum(enumIdentifier: any, name: string): any {
if (isStaticType(enumIdentifier)) {
return this.staticDelegate.resolveEnum(enumIdentifier, name);
} else {
return null;
}

View File

@ -74,13 +74,13 @@ export class StaticReflector implements ReflectorReader {
return staticSymbol ? staticSymbol.filePath : null;
}
resolveType(name: string, moduleUrl: string): any {
resolveIdentifier(name: string, moduleUrl: string, runtime: any): any {
const result = this.host.findDeclaration(moduleUrl, name, '');
return result;
}
resolveEnum(enumType: any, name: string): any {
const staticSymbol: StaticSymbol = enumType;
resolveEnum(enumIdentifier: any, name: string): any {
const staticSymbol: StaticSymbol = enumIdentifier;
return this.host.getStaticSymbol(staticSymbol.filePath, staticSymbol.name, [name]);
}

View File

@ -10,7 +10,7 @@ import {ChangeDetectionStrategy, SchemaMetadata, Type, ViewEncapsulation} from '
import {LifecycleHooks, reflector} from '../core_private';
import {ListWrapper, StringMapWrapper} from './facade/collection';
import {ListWrapper, MapWrapper, StringMapWrapper} from './facade/collection';
import {isBlank, isPresent, isStringMap, normalizeBlank, normalizeBool} from './facade/lang';
import {CssSelector} from './selector';
import {getUrlScheme} from './url_resolver';
@ -29,10 +29,6 @@ const UNDEFINED = new Object();
export abstract class CompileMetadataWithIdentifier {
get identifier(): CompileIdentifierMetadata { return <CompileIdentifierMetadata>unimplemented(); }
get runtimeCacheKey(): any { return unimplemented(); }
equalsTo(id2: CompileMetadataWithIdentifier): boolean { return unimplemented(); }
}
export class CompileAnimationEntryMetadata {
@ -86,16 +82,16 @@ export class CompileAnimationGroupMetadata extends CompileAnimationWithStepsMeta
}
export class CompileIdentifierMetadata implements CompileMetadataWithIdentifier {
runtime: any;
reference: any;
name: string;
prefix: string;
moduleUrl: string;
value: any;
constructor(
{runtime, name, moduleUrl, prefix, value}:
{runtime?: any, name?: string, moduleUrl?: string, prefix?: string, value?: any} = {}) {
this.runtime = runtime;
{reference, name, moduleUrl, prefix, value}:
{reference?: any, name?: string, moduleUrl?: string, prefix?: string, value?: any} = {}) {
this.reference = reference;
this.name = name;
this.prefix = prefix;
this.moduleUrl = moduleUrl;
@ -103,13 +99,6 @@ export class CompileIdentifierMetadata implements CompileMetadataWithIdentifier
}
get identifier(): CompileIdentifierMetadata { return this; }
get runtimeCacheKey(): any { return this.identifier.runtime; }
equalsTo(id2: CompileIdentifierMetadata): boolean {
var rk = this.runtimeCacheKey;
return isPresent(rk) && rk == id2.runtimeCacheKey;
}
}
export class CompileDiDependencyMetadata {
@ -182,15 +171,15 @@ export class CompileProviderMetadata {
export class CompileFactoryMetadata extends CompileIdentifierMetadata {
diDeps: CompileDiDependencyMetadata[];
constructor({runtime, name, moduleUrl, prefix, diDeps, value}: {
runtime?: Function,
constructor({reference, name, moduleUrl, prefix, diDeps, value}: {
reference?: Function,
name?: string,
prefix?: string,
moduleUrl?: string,
value?: boolean,
diDeps?: CompileDiDependencyMetadata[]
}) {
super({runtime: runtime, name: name, prefix: prefix, moduleUrl: moduleUrl, value: value});
super({reference: reference, name: name, prefix: prefix, moduleUrl: moduleUrl, value: value});
this.diDeps = _normalizeArray(diDeps);
}
}
@ -208,64 +197,19 @@ export class CompileTokenMetadata implements CompileMetadataWithIdentifier {
this.identifierIsInstance = normalizeBool(identifierIsInstance);
}
get runtimeCacheKey(): any {
get reference(): any {
if (isPresent(this.identifier)) {
return this.identifier.runtimeCacheKey;
return this.identifier.reference;
} else {
return this.value;
}
}
equalsTo(token2: CompileTokenMetadata): boolean {
var rk = this.runtimeCacheKey;
return isPresent(rk) && rk == token2.runtimeCacheKey;
}
get name(): string {
return isPresent(this.value) ? sanitizeIdentifier(this.value) : this.identifier.name;
}
}
/**
* Note: We only need this in places where we need to support identifiers that
* don't have a `runtime` value given by the `StaticReflector`. E.g. see the `identifiers`
* file where we have some identifiers hard coded by name/module path.
*
* TODO(tbosch): Eventually, all of these places should go through the static reflector
* as well, providing them with a valid `StaticSymbol` that is again a singleton.
*/
export class CompileIdentifierMap<KEY extends CompileMetadataWithIdentifier, VALUE> {
private _valueMap = new Map<any, VALUE>();
private _values: VALUE[] = [];
private _tokens: KEY[] = [];
add(token: KEY, value: VALUE) {
var existing = this.get(token);
if (isPresent(existing)) {
throw new Error(
`Cannot overwrite in a CompileIdentifierMap! Token: ${token.identifier.name}`);
}
this._tokens.push(token);
this._values.push(value);
var rk = token.runtimeCacheKey;
if (!isPresent(rk)) {
throw new Error(`Cannot find a key for Token: ${token.identifier.name}`);
}
this._valueMap.set(rk, value);
}
get(token: KEY): VALUE {
var rk = token.runtimeCacheKey;
var result: VALUE;
if (isPresent(rk)) {
result = this._valueMap.get(rk);
}
return result;
}
keys(): KEY[] { return this._tokens; }
values(): VALUE[] { return this._values; }
get size(): number { return this._values.length; }
}
/**
* Metadata regarding compilation of a type.
*/
@ -274,8 +218,8 @@ export class CompileTypeMetadata extends CompileIdentifierMetadata {
diDeps: CompileDiDependencyMetadata[];
lifecycleHooks: LifecycleHooks[];
constructor({runtime, name, moduleUrl, prefix, isHost, value, diDeps, lifecycleHooks}: {
runtime?: Type<any>,
constructor({reference, name, moduleUrl, prefix, isHost, value, diDeps, lifecycleHooks}: {
reference?: Type<any>,
name?: string,
moduleUrl?: string,
prefix?: string,
@ -284,7 +228,7 @@ export class CompileTypeMetadata extends CompileIdentifierMetadata {
diDeps?: CompileDiDependencyMetadata[],
lifecycleHooks?: LifecycleHooks[];
} = {}) {
super({runtime: runtime, name: name, moduleUrl: moduleUrl, prefix: prefix, value: value});
super({reference: reference, name: name, moduleUrl: moduleUrl, prefix: prefix, value: value});
this.isHost = normalizeBool(isHost);
this.diDeps = _normalizeArray(diDeps);
this.lifecycleHooks = _normalizeArray(lifecycleHooks);
@ -510,12 +454,6 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
}
get identifier(): CompileIdentifierMetadata { return this.type; }
get runtimeCacheKey(): any { return this.type.runtimeCacheKey; }
equalsTo(other: CompileMetadataWithIdentifier): boolean {
return this.type.equalsTo(other.identifier);
}
}
/**
@ -526,7 +464,7 @@ export function createHostComponentMeta(compMeta: CompileDirectiveMetadata):
var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
return CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({
runtime: Object,
reference: Object,
name: `${compMeta.type.name}_Host`,
moduleUrl: compMeta.type.moduleUrl,
isHost: true
@ -569,11 +507,6 @@ export class CompilePipeMetadata implements CompileMetadataWithIdentifier {
this.pure = normalizeBool(pure);
}
get identifier(): CompileIdentifierMetadata { return this.type; }
get runtimeCacheKey(): any { return this.type.runtimeCacheKey; }
equalsTo(other: CompileMetadataWithIdentifier): boolean {
return this.type.equalsTo(other.identifier);
}
}
/**
@ -629,11 +562,6 @@ export class CompileNgModuleMetadata implements CompileMetadataWithIdentifier {
}
get identifier(): CompileIdentifierMetadata { return this.type; }
get runtimeCacheKey(): any { return this.type.runtimeCacheKey; }
equalsTo(other: CompileMetadataWithIdentifier): boolean {
return this.type.equalsTo(other.identifier);
}
}
export class TransitiveCompileNgModuleMetadata {
@ -643,20 +571,20 @@ export class TransitiveCompileNgModuleMetadata {
public modules: CompileNgModuleMetadata[], public providers: CompileProviderMetadata[],
public entryComponents: CompileTypeMetadata[], public directives: CompileDirectiveMetadata[],
public pipes: CompilePipeMetadata[]) {
directives.forEach(dir => this.directivesSet.add(dir.type.runtime));
pipes.forEach(pipe => this.pipesSet.add(pipe.type.runtime));
directives.forEach(dir => this.directivesSet.add(dir.type.reference));
pipes.forEach(pipe => this.pipesSet.add(pipe.type.reference));
}
}
export function removeIdentifierDuplicates<T extends CompileMetadataWithIdentifier>(items: T[]):
T[] {
const map = new CompileIdentifierMap<T, T>();
const map = new Map<any, T>();
items.forEach((item) => {
if (!map.get(item)) {
map.add(item, item);
if (!map.get(item.identifier.reference)) {
map.set(item.identifier.reference, item);
}
});
return map.keys();
return MapWrapper.values(map);
}
function _normalizeArray(obj: any[]): any[] {

View File

@ -8,7 +8,7 @@
import {ANALYZE_FOR_ENTRY_COMPONENTS, ChangeDetectionStrategy, ChangeDetectorRef, ComponentFactory, ComponentFactoryResolver, ElementRef, Injector, LOCALE_ID as LOCALE_ID_, NgModuleFactory, QueryList, RenderComponentType, Renderer, SecurityContext, SimpleChange, TRANSLATIONS_FORMAT as TRANSLATIONS_FORMAT_, TemplateRef, ViewContainerRef, ViewEncapsulation} from '@angular/core';
import {AnimationGroupPlayer as AnimationGroupPlayer_, AnimationKeyframe as AnimationKeyframe_, AnimationOutput as AnimationOutput_, AnimationSequencePlayer as AnimationSequencePlayer_, AnimationStyles as AnimationStyles_, AppElement, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, DebugAppView, DebugContext, EMPTY_ARRAY, EMPTY_MAP, NgModuleInjector, NoOpAnimationPlayer as NoOpAnimationPlayer_, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewType, ViewUtils, balanceAnimationKeyframes as impBalanceAnimationKeyframes, castByValue, checkBinding, clearStyles as impClearStyles, collectAndResolveStyles as impCollectAndResolveStyles, devModeEqual, flattenNestedViewRenderNodes, interpolate, prepareFinalAnimationStyles as impBalanceAnimationStyles, pureProxy1, pureProxy10, pureProxy2, pureProxy3, pureProxy4, pureProxy5, pureProxy6, pureProxy7, pureProxy8, pureProxy9, reflector, renderStyles as impRenderStyles} from '../core_private';
import {AnimationGroupPlayer, AnimationKeyframe, AnimationOutput, AnimationSequencePlayer, AnimationStyles, AppElement, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, DebugAppView, DebugContext, EMPTY_ARRAY, EMPTY_MAP, NgModuleInjector, NoOpAnimationPlayer, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewType, ViewUtils, balanceAnimationKeyframes, castByValue, checkBinding, clearStyles, collectAndResolveStyles, devModeEqual, flattenNestedViewRenderNodes, interpolate, prepareFinalAnimationStyles, pureProxy1, pureProxy10, pureProxy2, pureProxy3, pureProxy4, pureProxy5, pureProxy6, pureProxy7, pureProxy8, pureProxy9, reflector, renderStyles} from '../core_private';
import {CompileIdentifierMetadata, CompileTokenMetadata} from './compile_metadata';
import {assetUrl} from './util';
@ -17,45 +17,6 @@ var APP_VIEW_MODULE_URL = assetUrl('core', 'linker/view');
var VIEW_UTILS_MODULE_URL = assetUrl('core', 'linker/view_utils');
var CD_MODULE_URL = assetUrl('core', 'change_detection/change_detection');
// Reassign the imports to different variables so we can
// define static variables with the name of the import.
// (only needed for Dart).
var impViewUtils = ViewUtils;
var impAppView = AppView;
var impDebugAppView = DebugAppView;
var impDebugContext = DebugContext;
var impAppElement = AppElement;
var impElementRef = ElementRef;
var impViewContainerRef = ViewContainerRef;
var impChangeDetectorRef = ChangeDetectorRef;
var impRenderComponentType = RenderComponentType;
var impQueryList = QueryList;
var impTemplateRef = TemplateRef;
var impTemplateRef_ = TemplateRef_;
var impValueUnwrapper = ValueUnwrapper;
var impInjector = Injector;
var impViewEncapsulation = ViewEncapsulation;
var impViewType = ViewType;
var impChangeDetectionStrategy = ChangeDetectionStrategy;
var impStaticNodeDebugInfo = StaticNodeDebugInfo;
var impRenderer = Renderer;
var impSimpleChange = SimpleChange;
var impUNINITIALIZED = UNINITIALIZED;
var impChangeDetectorStatus = ChangeDetectorStatus;
var impFlattenNestedViewRenderNodes = flattenNestedViewRenderNodes;
var impDevModeEqual = devModeEqual;
var impInterpolate = interpolate;
var impCheckBinding = checkBinding;
var impCastByValue = castByValue;
var impEMPTY_ARRAY = EMPTY_ARRAY;
var impEMPTY_MAP = EMPTY_MAP;
var impAnimationGroupPlayer = AnimationGroupPlayer_;
var impAnimationSequencePlayer = AnimationSequencePlayer_;
var impAnimationKeyframe = AnimationKeyframe_;
var impAnimationStyles = AnimationStyles_;
var impNoOpAnimationPlayer = NoOpAnimationPlayer_;
var impAnimationOutput = AnimationOutput_;
var ANIMATION_STYLE_UTIL_ASSET_URL = assetUrl('core', 'animation/animation_style_util');
export interface IdentifierSpec {
@ -73,54 +34,54 @@ export class Identifiers {
static ViewUtils: IdentifierSpec = {
name: 'ViewUtils',
moduleUrl: assetUrl('core', 'linker/view_utils'),
runtime: impViewUtils
runtime: ViewUtils
};
static AppView:
IdentifierSpec = {name: 'AppView', moduleUrl: APP_VIEW_MODULE_URL, runtime: impAppView};
IdentifierSpec = {name: 'AppView', moduleUrl: APP_VIEW_MODULE_URL, runtime: AppView};
static DebugAppView: IdentifierSpec = {
name: 'DebugAppView',
moduleUrl: APP_VIEW_MODULE_URL,
runtime: impDebugAppView
runtime: DebugAppView
};
static AppElement: IdentifierSpec = {
name: 'AppElement',
moduleUrl: assetUrl('core', 'linker/element'),
runtime: impAppElement
runtime: AppElement
};
static ElementRef: IdentifierSpec = {
name: 'ElementRef',
moduleUrl: assetUrl('core', 'linker/element_ref'),
runtime: impElementRef
runtime: ElementRef
};
static ViewContainerRef: IdentifierSpec = {
name: 'ViewContainerRef',
moduleUrl: assetUrl('core', 'linker/view_container_ref'),
runtime: impViewContainerRef
runtime: ViewContainerRef
};
static ChangeDetectorRef: IdentifierSpec = {
name: 'ChangeDetectorRef',
moduleUrl: assetUrl('core', 'change_detection/change_detector_ref'),
runtime: impChangeDetectorRef
runtime: ChangeDetectorRef
};
static RenderComponentType: IdentifierSpec = {
name: 'RenderComponentType',
moduleUrl: assetUrl('core', 'render/api'),
runtime: impRenderComponentType
runtime: RenderComponentType
};
static QueryList: IdentifierSpec = {
name: 'QueryList',
moduleUrl: assetUrl('core', 'linker/query_list'),
runtime: impQueryList
runtime: QueryList
};
static TemplateRef: IdentifierSpec = {
name: 'TemplateRef',
moduleUrl: assetUrl('core', 'linker/template_ref'),
runtime: impTemplateRef
runtime: TemplateRef
};
static TemplateRef_: IdentifierSpec = {
name: 'TemplateRef_',
moduleUrl: assetUrl('core', 'linker/template_ref'),
runtime: impTemplateRef_
runtime: TemplateRef_
};
static CodegenComponentFactoryResolver: IdentifierSpec = {
name: 'CodegenComponentFactoryResolver',
@ -147,84 +108,81 @@ export class Identifiers {
runtime: NgModuleInjector,
moduleUrl: assetUrl('core', 'linker/ng_module_factory')
};
static ValueUnwrapper: IdentifierSpec = {
name: 'ValueUnwrapper',
moduleUrl: CD_MODULE_URL,
runtime: impValueUnwrapper
};
static ValueUnwrapper:
IdentifierSpec = {name: 'ValueUnwrapper', moduleUrl: CD_MODULE_URL, runtime: ValueUnwrapper};
static Injector: IdentifierSpec = {
name: 'Injector',
moduleUrl: assetUrl('core', 'di/injector'),
runtime: impInjector
runtime: Injector
};
static ViewEncapsulation: IdentifierSpec = {
name: 'ViewEncapsulation',
moduleUrl: assetUrl('core', 'metadata/view'),
runtime: impViewEncapsulation
runtime: ViewEncapsulation
};
static ViewType: IdentifierSpec = {
name: 'ViewType',
moduleUrl: assetUrl('core', 'linker/view_type'),
runtime: impViewType
runtime: ViewType
};
static ChangeDetectionStrategy: IdentifierSpec = {
name: 'ChangeDetectionStrategy',
moduleUrl: CD_MODULE_URL,
runtime: impChangeDetectionStrategy
runtime: ChangeDetectionStrategy
};
static StaticNodeDebugInfo: IdentifierSpec = {
name: 'StaticNodeDebugInfo',
moduleUrl: assetUrl('core', 'linker/debug_context'),
runtime: impStaticNodeDebugInfo
runtime: StaticNodeDebugInfo
};
static DebugContext: IdentifierSpec = {
name: 'DebugContext',
moduleUrl: assetUrl('core', 'linker/debug_context'),
runtime: impDebugContext
runtime: DebugContext
};
static Renderer: IdentifierSpec = {
name: 'Renderer',
moduleUrl: assetUrl('core', 'render/api'),
runtime: impRenderer
runtime: Renderer
};
static SimpleChange:
IdentifierSpec = {name: 'SimpleChange', moduleUrl: CD_MODULE_URL, runtime: impSimpleChange};
IdentifierSpec = {name: 'SimpleChange', moduleUrl: CD_MODULE_URL, runtime: SimpleChange};
static UNINITIALIZED:
IdentifierSpec = {name: 'UNINITIALIZED', moduleUrl: CD_MODULE_URL, runtime: impUNINITIALIZED};
IdentifierSpec = {name: 'UNINITIALIZED', moduleUrl: CD_MODULE_URL, runtime: UNINITIALIZED};
static ChangeDetectorStatus: IdentifierSpec = {
name: 'ChangeDetectorStatus',
moduleUrl: CD_MODULE_URL,
runtime: impChangeDetectorStatus
runtime: ChangeDetectorStatus
};
static checkBinding: IdentifierSpec = {
name: 'checkBinding',
moduleUrl: VIEW_UTILS_MODULE_URL,
runtime: impCheckBinding
runtime: checkBinding
};
static flattenNestedViewRenderNodes: IdentifierSpec = {
name: 'flattenNestedViewRenderNodes',
moduleUrl: VIEW_UTILS_MODULE_URL,
runtime: impFlattenNestedViewRenderNodes
runtime: flattenNestedViewRenderNodes
};
static devModeEqual:
IdentifierSpec = {name: 'devModeEqual', moduleUrl: CD_MODULE_URL, runtime: impDevModeEqual};
IdentifierSpec = {name: 'devModeEqual', moduleUrl: CD_MODULE_URL, runtime: devModeEqual};
static interpolate: IdentifierSpec = {
name: 'interpolate',
moduleUrl: VIEW_UTILS_MODULE_URL,
runtime: impInterpolate
runtime: interpolate
};
static castByValue: IdentifierSpec = {
name: 'castByValue',
moduleUrl: VIEW_UTILS_MODULE_URL,
runtime: impCastByValue
runtime: castByValue
};
static EMPTY_ARRAY: IdentifierSpec = {
name: 'EMPTY_ARRAY',
moduleUrl: VIEW_UTILS_MODULE_URL,
runtime: impEMPTY_ARRAY
runtime: EMPTY_ARRAY
};
static EMPTY_MAP:
IdentifierSpec = {name: 'EMPTY_MAP', moduleUrl: VIEW_UTILS_MODULE_URL, runtime: impEMPTY_MAP};
IdentifierSpec = {name: 'EMPTY_MAP', moduleUrl: VIEW_UTILS_MODULE_URL, runtime: EMPTY_MAP};
static pureProxies = [
null,
@ -247,52 +205,52 @@ export class Identifiers {
static AnimationKeyframe: IdentifierSpec = {
name: 'AnimationKeyframe',
moduleUrl: assetUrl('core', 'animation/animation_keyframe'),
runtime: impAnimationKeyframe
runtime: AnimationKeyframe
};
static AnimationStyles: IdentifierSpec = {
name: 'AnimationStyles',
moduleUrl: assetUrl('core', 'animation/animation_styles'),
runtime: impAnimationStyles
runtime: AnimationStyles
};
static NoOpAnimationPlayer: IdentifierSpec = {
name: 'NoOpAnimationPlayer',
moduleUrl: assetUrl('core', 'animation/animation_player'),
runtime: impNoOpAnimationPlayer
runtime: NoOpAnimationPlayer
};
static AnimationGroupPlayer: IdentifierSpec = {
name: 'AnimationGroupPlayer',
moduleUrl: assetUrl('core', 'animation/animation_group_player'),
runtime: impAnimationGroupPlayer
runtime: AnimationGroupPlayer
};
static AnimationSequencePlayer: IdentifierSpec = {
name: 'AnimationSequencePlayer',
moduleUrl: assetUrl('core', 'animation/animation_sequence_player'),
runtime: impAnimationSequencePlayer
runtime: AnimationSequencePlayer
};
static prepareFinalAnimationStyles: IdentifierSpec = {
name: 'prepareFinalAnimationStyles',
moduleUrl: ANIMATION_STYLE_UTIL_ASSET_URL,
runtime: impBalanceAnimationStyles
runtime: prepareFinalAnimationStyles
};
static balanceAnimationKeyframes: IdentifierSpec = {
name: 'balanceAnimationKeyframes',
moduleUrl: ANIMATION_STYLE_UTIL_ASSET_URL,
runtime: impBalanceAnimationKeyframes
runtime: balanceAnimationKeyframes
};
static clearStyles: IdentifierSpec = {
name: 'clearStyles',
moduleUrl: ANIMATION_STYLE_UTIL_ASSET_URL,
runtime: impClearStyles
runtime: clearStyles
};
static renderStyles: IdentifierSpec = {
name: 'renderStyles',
moduleUrl: ANIMATION_STYLE_UTIL_ASSET_URL,
runtime: impRenderStyles
runtime: renderStyles
};
static collectAndResolveStyles: IdentifierSpec = {
name: 'collectAndResolveStyles',
moduleUrl: ANIMATION_STYLE_UTIL_ASSET_URL,
runtime: impCollectAndResolveStyles
runtime: collectAndResolveStyles
};
static LOCALE_ID: IdentifierSpec = {
name: 'LOCALE_ID',
@ -307,7 +265,7 @@ export class Identifiers {
static AnimationOutput: IdentifierSpec = {
name: 'AnimationOutput',
moduleUrl: assetUrl('core', 'animation/animation_output'),
runtime: impAnimationOutput
runtime: AnimationOutput
};
}
@ -315,7 +273,8 @@ export function resolveIdentifier(identifier: IdentifierSpec) {
return new CompileIdentifierMetadata({
name: identifier.name,
moduleUrl: identifier.moduleUrl,
runtime: reflector.resolveType(identifier.name, identifier.moduleUrl) || identifier.runtime
reference:
reflector.resolveIdentifier(identifier.name, identifier.moduleUrl, identifier.runtime)
});
}
@ -329,15 +288,7 @@ export function resolveIdentifierToken(identifier: IdentifierSpec): CompileToken
export function resolveEnumIdentifier(
enumType: CompileIdentifierMetadata, name: string): CompileIdentifierMetadata {
const resolvedEnum = reflector.resolveEnum(enumType, name);
if (resolvedEnum) {
return new CompileIdentifierMetadata(
{name: enumType.name, moduleUrl: enumType.moduleUrl, runtime: resolvedEnum});
} else {
return new CompileIdentifierMetadata({
name: `${enumType.name}.${name}`,
moduleUrl: enumType.moduleUrl,
runtime: enumType.runtime[name]
});
}
const resolvedEnum = reflector.resolveEnum(enumType.reference, name);
return new CompileIdentifierMetadata(
{name: `${enumType.name}.${name}`, moduleUrl: enumType.moduleUrl, reference: resolvedEnum});
}

View File

@ -340,15 +340,15 @@ export class CompileMetadataResolver {
private _verifyModule(moduleMeta: cpl.CompileNgModuleMetadata) {
moduleMeta.exportedDirectives.forEach((dirMeta) => {
if (!moduleMeta.transitiveModule.directivesSet.has(dirMeta.type.runtime)) {
if (!moduleMeta.transitiveModule.directivesSet.has(dirMeta.type.reference)) {
throw new Error(
`Can't export directive ${stringify(dirMeta.type.runtime)} from ${stringify(moduleMeta.type.runtime)} as it was neither declared nor imported!`);
`Can't export directive ${stringify(dirMeta.type.reference)} from ${stringify(moduleMeta.type.reference)} as it was neither declared nor imported!`);
}
});
moduleMeta.exportedPipes.forEach((pipeMeta) => {
if (!moduleMeta.transitiveModule.pipesSet.has(pipeMeta.type.runtime)) {
if (!moduleMeta.transitiveModule.pipesSet.has(pipeMeta.type.reference)) {
throw new Error(
`Can't export pipe ${stringify(pipeMeta.type.runtime)} from ${stringify(moduleMeta.type.runtime)} as it was neither declared nor imported!`);
`Can't export pipe ${stringify(pipeMeta.type.reference)} from ${stringify(moduleMeta.type.reference)} as it was neither declared nor imported!`);
}
});
}
@ -397,11 +397,11 @@ export class CompileMetadataResolver {
dirMeta: cpl.CompileDirectiveMetadata, moduleType: any,
transitiveModule: cpl.TransitiveCompileNgModuleMetadata,
declaredDirectives: cpl.CompileDirectiveMetadata[], force: boolean = false): boolean {
if (force || !transitiveModule.directivesSet.has(dirMeta.type.runtime)) {
transitiveModule.directivesSet.add(dirMeta.type.runtime);
if (force || !transitiveModule.directivesSet.has(dirMeta.type.reference)) {
transitiveModule.directivesSet.add(dirMeta.type.reference);
transitiveModule.directives.push(dirMeta);
declaredDirectives.push(dirMeta);
this._addTypeToModule(dirMeta.type.runtime, moduleType);
this._addTypeToModule(dirMeta.type.reference, moduleType);
return true;
}
return false;
@ -411,11 +411,11 @@ export class CompileMetadataResolver {
pipeMeta: cpl.CompilePipeMetadata, moduleType: any,
transitiveModule: cpl.TransitiveCompileNgModuleMetadata,
declaredPipes: cpl.CompilePipeMetadata[], force: boolean = false): boolean {
if (force || !transitiveModule.pipesSet.has(pipeMeta.type.runtime)) {
transitiveModule.pipesSet.add(pipeMeta.type.runtime);
if (force || !transitiveModule.pipesSet.has(pipeMeta.type.reference)) {
transitiveModule.pipesSet.add(pipeMeta.type.reference);
transitiveModule.pipes.push(pipeMeta);
declaredPipes.push(pipeMeta);
this._addTypeToModule(pipeMeta.type.runtime, moduleType);
this._addTypeToModule(pipeMeta.type.reference, moduleType);
return true;
}
return false;
@ -427,7 +427,7 @@ export class CompileMetadataResolver {
return new cpl.CompileTypeMetadata({
name: this.sanitizeTokenName(type),
moduleUrl: moduleUrl,
runtime: type,
reference: type,
diDeps: this.getDependenciesMetadata(type, dependencies),
lifecycleHooks: LIFECYCLE_HOOKS_VALUES.filter(hook => hasLifecycleHook(hook, type)),
});
@ -439,7 +439,7 @@ export class CompileMetadataResolver {
return new cpl.CompileFactoryMetadata({
name: this.sanitizeTokenName(factory),
moduleUrl: moduleUrl,
runtime: factory,
reference: factory,
diDeps: this.getDependenciesMetadata(factory, dependencies)
});
}
@ -542,7 +542,7 @@ export class CompileMetadataResolver {
} else {
compileToken = new cpl.CompileTokenMetadata({
identifier: new cpl.CompileIdentifierMetadata({
runtime: token,
reference: token,
name: this.sanitizeTokenName(token),
moduleUrl: staticTypeModuleUrl(token)
})
@ -565,7 +565,8 @@ export class CompileMetadataResolver {
compileProvider = this.getProvidersMetadata(provider, targetEntryComponents, debugInfo);
} else if (provider instanceof cpl.ProviderMeta) {
let tokenMeta = this.getTokenMetadata(provider.token);
if (tokenMeta.equalsTo(resolveIdentifierToken(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS))) {
if (tokenMeta.reference ===
resolveIdentifierToken(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS).reference) {
targetEntryComponents.push(...this._getEntryComponentsFromProvider(provider));
} else {
compileProvider = this.getProviderMetadata(provider);
@ -608,7 +609,7 @@ export class CompileMetadataResolver {
}
convertToCompileValue(provider.useValue, collectedIdentifiers);
collectedIdentifiers.forEach((identifier) => {
let dirMeta = this.getDirectiveMetadata(identifier.runtime, false);
let dirMeta = this.getDirectiveMetadata(identifier.reference, false);
if (dirMeta) {
components.push(dirMeta.type);
}
@ -682,8 +683,8 @@ function getTransitiveModules(
targetModules: cpl.CompileNgModuleMetadata[] = [],
visitedModules = new Set<Type<any>>()): cpl.CompileNgModuleMetadata[] {
modules.forEach((ngModule) => {
if (!visitedModules.has(ngModule.type.runtime)) {
visitedModules.add(ngModule.type.runtime);
if (!visitedModules.has(ngModule.type.reference)) {
visitedModules.add(ngModule.type.reference);
const nestedModules = includeImports ?
ngModule.importedModules.concat(ngModule.exportedModules) :
ngModule.exportedModules;
@ -745,9 +746,9 @@ class _CompileValueConverter extends ValueTransformer {
let identifier: cpl.CompileIdentifierMetadata;
if (cpl.isStaticSymbol(value)) {
identifier = new cpl.CompileIdentifierMetadata(
{name: value.name, moduleUrl: value.filePath, runtime: value});
{name: value.name, moduleUrl: value.filePath, reference: value});
} else {
identifier = new cpl.CompileIdentifierMetadata({runtime: value});
identifier = new cpl.CompileIdentifierMetadata({reference: value});
}
targetIdentifiers.push(identifier);
return identifier;

View File

@ -10,7 +10,7 @@ import {Injectable} from '@angular/core';
import {LifecycleHooks} from '../core_private';
import {CompileDiDependencyMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileTokenMetadata} from './compile_metadata';
import {CompileDiDependencyMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileTokenMetadata} from './compile_metadata';
import {isBlank, isPresent} from './facade/lang';
import {Identifiers, identifierToken, resolveIdentifier, resolveIdentifierToken} from './identifiers';
import * as o from './output/output_ast';
@ -76,7 +76,8 @@ export class NgModuleCompiler {
}
class _InjectorBuilder {
private _instances = new CompileIdentifierMap<CompileTokenMetadata, o.Expression>();
private _tokens: CompileTokenMetadata[] = [];
private _instances = new Map<any, o.Expression>();
private _fields: o.ClassField[] = [];
private _createStmts: o.Statement[] = [];
private _destroyStmts: o.Statement[] = [];
@ -98,12 +99,13 @@ class _InjectorBuilder {
if (resolvedProvider.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
this._destroyStmts.push(instance.callMethod('ngOnDestroy', []).toStmt());
}
this._instances.add(resolvedProvider.token, instance);
this._tokens.push(resolvedProvider.token);
this._instances.set(resolvedProvider.token.reference, instance);
}
build(): o.ClassStmt {
let getMethodStmts: o.Statement[] = this._instances.keys().map((token) => {
var providerExpr = this._instances.get(token);
let getMethodStmts: o.Statement[] = this._tokens.map((token) => {
var providerExpr = this._instances.get(token.reference);
return new o.IfStmt(
InjectMethodVars.token.identical(createDiTokenExpression(token)),
[new o.ReturnStatement(providerExpr)]);
@ -111,7 +113,7 @@ class _InjectorBuilder {
var methods = [
new o.ClassMethod(
'createInternal', [], this._createStmts.concat(
new o.ReturnStatement(this._instances.get(identifierToken(this._ngModuleMeta.type)))
new o.ReturnStatement(this._instances.get(this._ngModuleMeta.type.reference))
), o.importType(this._ngModuleMeta.type)
),
new o.ClassMethod(
@ -209,12 +211,13 @@ class _InjectorBuilder {
}
if (!dep.isSkipSelf) {
if (dep.token &&
(dep.token.equalsTo(resolveIdentifierToken(Identifiers.Injector)) ||
dep.token.equalsTo(resolveIdentifierToken(Identifiers.ComponentFactoryResolver)))) {
(dep.token.reference === resolveIdentifierToken(Identifiers.Injector).reference ||
dep.token.reference ===
resolveIdentifierToken(Identifiers.ComponentFactoryResolver).reference)) {
result = o.THIS_EXPR;
}
if (isBlank(result)) {
result = this._instances.get(dep.token);
result = this._instances.get(dep.token.reference);
}
}
if (isBlank(result)) {

View File

@ -43,7 +43,7 @@ export class OfflineCompiler {
const ngModuleMeta = this._metadataResolver.getNgModuleMetadata(<any>ngModule);
ngModuleMeta.declaredDirectives.forEach((dirMeta) => {
if (dirMeta.isComponent) {
ngModuleByComponent.set(dirMeta.type.runtime, ngModuleMeta);
ngModuleByComponent.set(dirMeta.type.reference, ngModuleMeta);
}
});
});

View File

@ -220,7 +220,9 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return new clazz(...args);
}
visitLiteralExpr(ast: o.LiteralExpr, ctx: _ExecutionContext): any { return ast.value; }
visitExternalExpr(ast: o.ExternalExpr, ctx: _ExecutionContext): any { return ast.value.runtime; }
visitExternalExpr(ast: o.ExternalExpr, ctx: _ExecutionContext): any {
return ast.value.reference;
}
visitConditionalExpr(ast: o.ConditionalExpr, ctx: _ExecutionContext): any {
if (ast.condition.visitExpression(this, ctx)) {
return ast.trueCase.visitExpression(this, ctx);

View File

@ -34,7 +34,7 @@ class JitEmitterVisitor extends AbstractJsEmitterVisitor {
}
visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any {
var value = ast.value.runtime;
var value = ast.value.reference;
var id = this._evalArgValues.indexOf(value);
if (id === -1) {
id = this._evalArgValues.length;

View File

@ -311,16 +311,18 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
}
ctx.print(`${prefix}.`);
}
ctx.print(value.name);
if (value.reference && value.reference.members) {
ctx.print(value.reference.name);
ctx.print('.');
ctx.print(value.reference.members.join('.'));
} else {
ctx.print(value.name);
}
if (isPresent(typeParams) && typeParams.length > 0) {
ctx.print(`<`);
this.visitAllObjects(
(type: any /** TODO #9100 */) => type.visitType(this, ctx), typeParams, ctx, ',');
ctx.print(`>`);
}
if (value.runtime && value.runtime.members) {
ctx.print('.');
ctx.print(value.runtime.members.join('.'));
}
}
}

View File

@ -7,8 +7,8 @@
*/
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata';
import {ListWrapper} from './facade/collection';
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata';
import {ListWrapper, MapWrapper} from './facade/collection';
import {isArray, isBlank, isPresent, normalizeBlank} from './facade/lang';
import {Identifiers, resolveIdentifierToken} from './identifiers';
import {ParseError, ParseSourceSpan} from './parse_util';
@ -22,30 +22,30 @@ export class ProviderViewContext {
/**
* @internal
*/
viewQueries: CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]>;
viewQueries: Map<any, CompileQueryMetadata[]>;
/**
* @internal
*/
viewProviders: CompileIdentifierMap<CompileTokenMetadata, boolean>;
viewProviders: Map<any, boolean>;
errors: ProviderError[] = [];
constructor(public component: CompileDirectiveMetadata, public sourceSpan: ParseSourceSpan) {
this.viewQueries = _getViewQueries(component);
this.viewProviders = new CompileIdentifierMap<CompileTokenMetadata, boolean>();
this.viewProviders = new Map<any, boolean>();
_normalizeProviders(component.viewProviders, sourceSpan, this.errors).forEach((provider) => {
if (isBlank(this.viewProviders.get(provider.token))) {
this.viewProviders.add(provider.token, true);
if (isBlank(this.viewProviders.get(provider.token.reference))) {
this.viewProviders.set(provider.token.reference, true);
}
});
}
}
export class ProviderElementContext {
private _contentQueries: CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]>;
private _contentQueries: Map<any, CompileQueryMetadata[]>;
private _transformedProviders = new CompileIdentifierMap<CompileTokenMetadata, ProviderAst>();
private _seenProviders = new CompileIdentifierMap<CompileTokenMetadata, boolean>();
private _allProviders: CompileIdentifierMap<CompileTokenMetadata, ProviderAst>;
private _transformedProviders = new Map<any, ProviderAst>();
private _seenProviders = new Map<any, boolean>();
private _allProviders: Map<any, ProviderAst>;
private _attrs: {[key: string]: string};
private _hasViewContainer: boolean = false;
@ -59,19 +59,21 @@ export class ProviderElementContext {
this._allProviders =
_resolveProvidersFromDirectives(directivesMeta, _sourceSpan, _viewContext.errors);
this._contentQueries = _getContentQueries(directivesMeta);
var queriedTokens = new CompileIdentifierMap<CompileTokenMetadata, boolean>();
this._allProviders.values().forEach(
(provider) => { this._addQueryReadsTo(provider.token, queriedTokens); });
var queriedTokens = new Map<any, boolean>();
MapWrapper.values(this._allProviders).forEach((provider) => {
this._addQueryReadsTo(provider.token, queriedTokens);
});
refs.forEach((refAst) => {
this._addQueryReadsTo(new CompileTokenMetadata({value: refAst.name}), queriedTokens);
});
if (isPresent(queriedTokens.get(resolveIdentifierToken(Identifiers.ViewContainerRef)))) {
if (isPresent(
queriedTokens.get(resolveIdentifierToken(Identifiers.ViewContainerRef).reference))) {
this._hasViewContainer = true;
}
// create the providers that we know are eager first
this._allProviders.values().forEach((provider) => {
const eager = provider.eager || isPresent(queriedTokens.get(provider.token));
MapWrapper.values(this._allProviders).forEach((provider) => {
const eager = provider.eager || isPresent(queriedTokens.get(provider.token.reference));
if (eager) {
this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
}
@ -80,16 +82,15 @@ export class ProviderElementContext {
afterElement() {
// collect lazy providers
this._allProviders.values().forEach((provider) => {
MapWrapper.values(this._allProviders).forEach((provider) => {
this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
});
}
get transformProviders(): ProviderAst[] { return this._transformedProviders.values(); }
get transformProviders(): ProviderAst[] { return MapWrapper.values(this._transformedProviders); }
get transformedDirectiveAsts(): DirectiveAst[] {
var sortedProviderTypes =
this._transformedProviders.values().map(provider => provider.token.identifier);
var sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);
var sortedDirectives = ListWrapper.clone(this._directiveAsts);
ListWrapper.sort(
sortedDirectives, (dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -
@ -99,13 +100,11 @@ export class ProviderElementContext {
get transformedHasViewContainer(): boolean { return this._hasViewContainer; }
private _addQueryReadsTo(
token: CompileTokenMetadata,
queryReadTokens: CompileIdentifierMap<CompileTokenMetadata, boolean>) {
private _addQueryReadsTo(token: CompileTokenMetadata, queryReadTokens: Map<any, boolean>) {
this._getQueriesFor(token).forEach((query) => {
const queryReadToken = isPresent(query.read) ? query.read : token;
if (isBlank(queryReadTokens.get(queryReadToken))) {
queryReadTokens.add(queryReadToken, true);
if (isBlank(queryReadTokens.get(queryReadToken.reference))) {
queryReadTokens.set(queryReadToken.reference, true);
}
});
}
@ -116,7 +115,7 @@ export class ProviderElementContext {
var distance = 0;
var queries: CompileQueryMetadata[];
while (currentEl !== null) {
queries = currentEl._contentQueries.get(token);
queries = currentEl._contentQueries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries.filter((query) => query.descendants || distance <= 1));
}
@ -125,7 +124,7 @@ export class ProviderElementContext {
}
currentEl = currentEl._parent;
}
queries = this._viewContext.viewQueries.get(token);
queries = this._viewContext.viewQueries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries);
}
@ -136,7 +135,7 @@ export class ProviderElementContext {
private _getOrCreateLocalProvider(
requestingProviderType: ProviderAstType, token: CompileTokenMetadata,
eager: boolean): ProviderAst {
var resolvedProvider = this._allProviders.get(token);
var resolvedProvider = this._allProviders.get(token.reference);
if (isBlank(resolvedProvider) ||
((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.PublicService) &&
@ -146,16 +145,16 @@ export class ProviderElementContext {
resolvedProvider.providerType === ProviderAstType.Builtin)) {
return null;
}
var transformedProviderAst = this._transformedProviders.get(token);
var transformedProviderAst = this._transformedProviders.get(token.reference);
if (isPresent(transformedProviderAst)) {
return transformedProviderAst;
}
if (isPresent(this._seenProviders.get(token))) {
if (isPresent(this._seenProviders.get(token.reference))) {
this._viewContext.errors.push(new ProviderError(
`Cannot instantiate cyclic dependency! ${token.name}`, this._sourceSpan));
return null;
}
this._seenProviders.add(token, true);
this._seenProviders.set(token.reference, true);
var transformedProviders = resolvedProvider.providers.map((provider) => {
var transformedUseValue = provider.useValue;
var transformedUseExisting = provider.useExisting;
@ -187,7 +186,7 @@ export class ProviderElementContext {
});
transformedProviderAst =
_transformProviderAst(resolvedProvider, {eager: eager, providers: transformedProviders});
this._transformedProviders.add(token, transformedProviderAst);
this._transformedProviders.set(token.reference, transformedProviderAst);
return transformedProviderAst;
}
@ -206,18 +205,20 @@ export class ProviderElementContext {
// access builtints
if ((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.Component)) {
if (dep.token.equalsTo(resolveIdentifierToken(Identifiers.Renderer)) ||
dep.token.equalsTo(resolveIdentifierToken(Identifiers.ElementRef)) ||
dep.token.equalsTo(resolveIdentifierToken(Identifiers.ChangeDetectorRef)) ||
dep.token.equalsTo(resolveIdentifierToken(Identifiers.TemplateRef))) {
if (dep.token.reference === resolveIdentifierToken(Identifiers.Renderer).reference ||
dep.token.reference === resolveIdentifierToken(Identifiers.ElementRef).reference ||
dep.token.reference ===
resolveIdentifierToken(Identifiers.ChangeDetectorRef).reference ||
dep.token.reference === resolveIdentifierToken(Identifiers.TemplateRef).reference) {
return dep;
}
if (dep.token.equalsTo(resolveIdentifierToken(Identifiers.ViewContainerRef))) {
if (dep.token.reference ===
resolveIdentifierToken(Identifiers.ViewContainerRef).reference) {
this._hasViewContainer = true;
}
}
// access the injector
if (dep.token.equalsTo(resolveIdentifierToken(Identifiers.Injector))) {
if (dep.token.reference === resolveIdentifierToken(Identifiers.Injector).reference) {
return dep;
}
// access providers
@ -254,8 +255,8 @@ export class ProviderElementContext {
// check @Host restriction
if (isBlank(result)) {
if (!dep.isHost || this._viewContext.component.type.isHost ||
resolveIdentifierToken(this._viewContext.component.type).equalsTo(dep.token) ||
isPresent(this._viewContext.viewProviders.get(dep.token))) {
this._viewContext.component.type.reference === dep.token.reference ||
isPresent(this._viewContext.viewProviders.get(dep.token.reference))) {
result = dep;
} else {
result = dep.isOptional ?
@ -274,15 +275,15 @@ export class ProviderElementContext {
export class NgModuleProviderAnalyzer {
private _transformedProviders = new CompileIdentifierMap<CompileTokenMetadata, ProviderAst>();
private _seenProviders = new CompileIdentifierMap<CompileTokenMetadata, boolean>();
private _allProviders: CompileIdentifierMap<CompileTokenMetadata, ProviderAst>;
private _transformedProviders = new Map<any, ProviderAst>();
private _seenProviders = new Map<any, boolean>();
private _allProviders: Map<any, ProviderAst>;
private _errors: ProviderError[] = [];
constructor(
ngModule: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[],
sourceSpan: ParseSourceSpan) {
this._allProviders = new CompileIdentifierMap<CompileTokenMetadata, ProviderAst>();
this._allProviders = new Map<any, ProviderAst>();
const ngModuleTypes = ngModule.transitiveModule.modules.map((moduleMeta) => moduleMeta.type);
ngModuleTypes.forEach((ngModuleType: CompileTypeMetadata) => {
const ngModuleProvider = new CompileProviderMetadata(
@ -298,30 +299,31 @@ export class NgModuleProviderAnalyzer {
}
parse(): ProviderAst[] {
this._allProviders.values().forEach(
(provider) => { this._getOrCreateLocalProvider(provider.token, provider.eager); });
MapWrapper.values(this._allProviders).forEach((provider) => {
this._getOrCreateLocalProvider(provider.token, provider.eager);
});
if (this._errors.length > 0) {
const errorString = this._errors.join('\n');
throw new Error(`Provider parse errors:\n${errorString}`);
}
return this._transformedProviders.values();
return MapWrapper.values(this._transformedProviders);
}
private _getOrCreateLocalProvider(token: CompileTokenMetadata, eager: boolean): ProviderAst {
var resolvedProvider = this._allProviders.get(token);
var resolvedProvider = this._allProviders.get(token.reference);
if (isBlank(resolvedProvider)) {
return null;
}
var transformedProviderAst = this._transformedProviders.get(token);
var transformedProviderAst = this._transformedProviders.get(token.reference);
if (isPresent(transformedProviderAst)) {
return transformedProviderAst;
}
if (isPresent(this._seenProviders.get(token))) {
if (isPresent(this._seenProviders.get(token.reference))) {
this._errors.push(new ProviderError(
`Cannot instantiate cyclic dependency! ${token.name}`, resolvedProvider.sourceSpan));
return null;
}
this._seenProviders.add(token, true);
this._seenProviders.set(token.reference, true);
var transformedProviders = resolvedProvider.providers.map((provider) => {
var transformedUseValue = provider.useValue;
var transformedUseExisting = provider.useExisting;
@ -353,7 +355,7 @@ export class NgModuleProviderAnalyzer {
});
transformedProviderAst =
_transformProviderAst(resolvedProvider, {eager: eager, providers: transformedProviders});
this._transformedProviders.add(token, transformedProviderAst);
this._transformedProviders.set(token.reference, transformedProviderAst);
return transformedProviderAst;
}
@ -363,8 +365,9 @@ export class NgModuleProviderAnalyzer {
var foundLocal = false;
if (!dep.isSkipSelf && isPresent(dep.token)) {
// access the injector
if (dep.token.equalsTo(resolveIdentifierToken(Identifiers.Injector)) ||
dep.token.equalsTo(resolveIdentifierToken(Identifiers.ComponentFactoryResolver))) {
if (dep.token.reference === resolveIdentifierToken(Identifiers.Injector).reference ||
dep.token.reference ===
resolveIdentifierToken(Identifiers.ComponentFactoryResolver).reference) {
foundLocal = true;
// access providers
} else if (isPresent(this._getOrCreateLocalProvider(dep.token, eager))) {
@ -440,8 +443,8 @@ function _normalizeProviders(
function _resolveProvidersFromDirectives(
directives: CompileDirectiveMetadata[], sourceSpan: ParseSourceSpan,
targetErrors: ParseError[]): CompileIdentifierMap<CompileTokenMetadata, ProviderAst> {
var providersByToken = new CompileIdentifierMap<CompileTokenMetadata, ProviderAst>();
targetErrors: ParseError[]): Map<any, ProviderAst> {
var providersByToken = new Map<any, ProviderAst>();
directives.forEach((directive) => {
var dirProvider = new CompileProviderMetadata(
{token: new CompileTokenMetadata({identifier: directive.type}), useClass: directive.type});
@ -468,9 +471,9 @@ function _resolveProvidersFromDirectives(
function _resolveProviders(
providers: CompileProviderMetadata[], providerType: ProviderAstType, eager: boolean,
sourceSpan: ParseSourceSpan, targetErrors: ParseError[],
targetProvidersByToken: CompileIdentifierMap<CompileTokenMetadata, ProviderAst>) {
targetProvidersByToken: Map<any, ProviderAst>) {
providers.forEach((provider) => {
var resolvedProvider = targetProvidersByToken.get(provider.token);
var resolvedProvider = targetProvidersByToken.get(provider.token.reference);
if (isPresent(resolvedProvider) && resolvedProvider.multiProvider !== provider.multi) {
targetErrors.push(new ProviderError(
`Mixing multi and non multi provider is not possible for token ${resolvedProvider.token.name}`,
@ -484,7 +487,7 @@ function _resolveProviders(
resolvedProvider = new ProviderAst(
provider.token, provider.multi, eager || lifecycleHooks.length > 0, [provider],
providerType, lifecycleHooks, sourceSpan);
targetProvidersByToken.add(provider.token, resolvedProvider);
targetProvidersByToken.set(provider.token.reference, resolvedProvider);
} else {
if (!provider.multi) {
ListWrapper.clear(resolvedProvider.providers);
@ -495,9 +498,8 @@ function _resolveProviders(
}
function _getViewQueries(component: CompileDirectiveMetadata):
CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]> {
var viewQueries = new CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]>();
function _getViewQueries(component: CompileDirectiveMetadata): Map<any, CompileQueryMetadata[]> {
var viewQueries = new Map<any, CompileQueryMetadata[]>();
if (isPresent(component.viewQueries)) {
component.viewQueries.forEach((query) => _addQueryToTokenMap(viewQueries, query));
}
@ -510,8 +512,8 @@ function _getViewQueries(component: CompileDirectiveMetadata):
}
function _getContentQueries(directives: CompileDirectiveMetadata[]):
CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]> {
var contentQueries = new CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]>();
Map<any, CompileQueryMetadata[]> {
var contentQueries = new Map<any, CompileQueryMetadata[]>();
directives.forEach(directive => {
if (isPresent(directive.queries)) {
directive.queries.forEach((query) => _addQueryToTokenMap(contentQueries, query));
@ -525,14 +527,12 @@ function _getContentQueries(directives: CompileDirectiveMetadata[]):
return contentQueries;
}
function _addQueryToTokenMap(
map: CompileIdentifierMap<CompileTokenMetadata, CompileQueryMetadata[]>,
query: CompileQueryMetadata) {
function _addQueryToTokenMap(map: Map<any, CompileQueryMetadata[]>, query: CompileQueryMetadata) {
query.selectors.forEach((token: CompileTokenMetadata) => {
var entry = map.get(token);
var entry = map.get(token.reference);
if (isBlank(entry)) {
entry = [];
map.add(token, entry);
map.set(token.reference, entry);
}
entry.push(query);
});

View File

@ -81,7 +81,7 @@ export class RuntimeCompiler implements Compiler {
moduleMeta.transitiveModule.modules.forEach((moduleMeta) => {
moduleMeta.declaredDirectives.forEach((dirMeta) => {
if (dirMeta.isComponent) {
const template = this._createCompiledHostTemplate(dirMeta.type.runtime);
const template = this._createCompiledHostTemplate(dirMeta.type.reference);
templates.add(template);
componentFactories.push(template.proxyComponentFactory);
}
@ -105,11 +105,11 @@ export class RuntimeCompiler implements Compiler {
const moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
// Always provide a bound Compiler
const extraProviders = [this._metadataResolver.getProviderMetadata(new ProviderMeta(
Compiler, {useFactory: () => new ModuleBoundCompiler(this, moduleMeta.type.runtime)}))];
Compiler, {useFactory: () => new ModuleBoundCompiler(this, moduleMeta.type.reference)}))];
var compileResult = this._ngModuleCompiler.compile(moduleMeta, extraProviders);
compileResult.dependencies.forEach((dep) => {
dep.placeholder.runtime =
this._assertComponentKnown(dep.comp.runtime, true).proxyComponentFactory;
dep.placeholder.reference =
this._assertComponentKnown(dep.comp.reference, true).proxyComponentFactory;
dep.placeholder.name = `compFactory_${dep.comp.name}`;
});
if (!this._compilerConfig.useJit) {
@ -120,7 +120,7 @@ export class RuntimeCompiler implements Compiler {
`${moduleMeta.type.name}.ngfactory.js`, compileResult.statements,
compileResult.ngModuleFactoryVar);
}
this._compiledNgModuleCache.set(moduleMeta.type.runtime, ngModuleFactory);
this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
}
return ngModuleFactory;
}
@ -138,21 +138,21 @@ export class RuntimeCompiler implements Compiler {
if (dirMeta.isComponent) {
templates.add(this._createCompiledTemplate(dirMeta, localModuleMeta));
dirMeta.entryComponents.forEach((entryComponentType) => {
templates.add(this._createCompiledHostTemplate(entryComponentType.runtime));
templates.add(this._createCompiledHostTemplate(entryComponentType.reference));
});
// TODO: what about entryComponents of entryComponents? maybe skip here and just do the
// below?
}
});
localModuleMeta.entryComponents.forEach((entryComponentType) => {
templates.add(this._createCompiledHostTemplate(entryComponentType.runtime));
templates.add(this._createCompiledHostTemplate(entryComponentType.reference));
// TODO: what about entryComponents of entryComponents?
});
});
templates.forEach((template) => {
if (template.loading) {
if (isSync) {
throw new ComponentStillLoadingError(template.compType.runtime);
throw new ComponentStillLoadingError(template.compType.reference);
} else {
loadingPromises.push(template.loading);
}
@ -203,14 +203,14 @@ export class RuntimeCompiler implements Compiler {
private _createCompiledTemplate(
compMeta: CompileDirectiveMetadata, ngModule: CompileNgModuleMetadata): CompiledTemplate {
var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.runtime);
var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
if (isBlank(compiledTemplate)) {
assertComponent(compMeta);
compiledTemplate = new CompiledTemplate(
false, compMeta.selector, compMeta.type, ngModule.transitiveModule.directives,
ngModule.transitiveModule.pipes, ngModule.schemas,
this._templateNormalizer.normalizeDirective(compMeta));
this._compiledTemplateCache.set(compMeta.type.runtime, compiledTemplate);
this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
}
return compiledTemplate;
}
@ -262,13 +262,13 @@ export class RuntimeCompiler implements Compiler {
let depTemplate: CompiledTemplate;
if (dep instanceof ViewFactoryDependency) {
let vfd = <ViewFactoryDependency>dep;
depTemplate = this._assertComponentLoaded(vfd.comp.runtime, false);
vfd.placeholder.runtime = depTemplate.proxyViewFactory;
depTemplate = this._assertComponentLoaded(vfd.comp.reference, false);
vfd.placeholder.reference = depTemplate.proxyViewFactory;
vfd.placeholder.name = `viewFactory_${vfd.comp.name}`;
} else if (dep instanceof ComponentFactoryDependency) {
let cfd = <ComponentFactoryDependency>dep;
depTemplate = this._assertComponentLoaded(cfd.comp.runtime, true);
cfd.placeholder.runtime = depTemplate.proxyComponentFactory;
depTemplate = this._assertComponentLoaded(cfd.comp.reference, true);
cfd.placeholder.reference = depTemplate.proxyComponentFactory;
cfd.placeholder.name = `compFactory_${cfd.comp.name}`;
}
});
@ -279,7 +279,8 @@ export class RuntimeCompiler implements Compiler {
factory = interpretStatements(statements, compileResult.viewFactoryVar);
} else {
factory = jitStatements(
`${template.compType.name}.ngfactory.js`, statements, compileResult.viewFactoryVar);
`${template.compType.name}${template.isHost?'_Host':''}.ngfactory.js`, statements,
compileResult.viewFactoryVar);
}
template.compiled(factory);
}
@ -290,7 +291,7 @@ export class RuntimeCompiler implements Compiler {
var nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
var nestedStylesArr = this._resolveAndEvalStylesCompileResult(
nestedCompileResult, externalStylesheetsByModuleUrl);
dep.valuePlaceholder.runtime = nestedStylesArr;
dep.valuePlaceholder.reference = nestedStylesArr;
dep.valuePlaceholder.name = `importedStyles${i}`;
});
}
@ -325,7 +326,7 @@ class CompiledTemplate {
_normalizeResult: SyncAsyncResult<CompileDirectiveMetadata>) {
viewDirectivesAndComponents.forEach((dirMeta) => {
if (dirMeta.isComponent) {
this.viewComponentTypes.push(dirMeta.type.runtime);
this.viewComponentTypes.push(dirMeta.type.reference);
} else {
this.viewDirectives.push(dirMeta);
}
@ -338,7 +339,7 @@ class CompiledTemplate {
return this._viewFactory.apply(null, args);
};
this.proxyComponentFactory = isHost ?
new ComponentFactory<any>(selector, this.proxyViewFactory, compType.runtime) :
new ComponentFactory<any>(selector, this.proxyViewFactory, compType.reference) :
null;
if (_normalizeResult.syncResult) {
this._normalizedCompMeta = _normalizeResult.syncResult;

View File

@ -7,8 +7,8 @@
*/
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper, MapWrapper, StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {Identifiers, identifierToken, resolveIdentifier, resolveIdentifierToken} from '../identifiers';
import * as o from '../output/output_ast';
@ -41,11 +41,11 @@ export class CompileElement extends CompileNode {
public appElement: o.ReadPropExpr;
public elementRef: o.Expression;
public injector: o.Expression;
public instances = new CompileIdentifierMap<CompileTokenMetadata, o.Expression>();
private _resolvedProviders: CompileIdentifierMap<CompileTokenMetadata, ProviderAst>;
public instances = new Map<any, o.Expression>();
private _resolvedProviders: Map<any, ProviderAst>;
private _queryCount = 0;
private _queries = new CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>();
private _queries = new Map<any, CompileQuery[]>();
private _componentConstructorViewQueryLists: o.Expression[] = [];
public contentNodesByNgContentIndex: Array<o.Expression>[] = null;
@ -64,10 +64,11 @@ export class CompileElement extends CompileNode {
this.elementRef =
o.importExpr(resolveIdentifier(Identifiers.ElementRef)).instantiate([this.renderNode]);
this.instances.add(resolveIdentifierToken(Identifiers.ElementRef), this.elementRef);
this.instances.set(resolveIdentifierToken(Identifiers.ElementRef).reference, this.elementRef);
this.injector = o.THIS_EXPR.callMethod('injector', [o.literal(this.nodeIndex)]);
this.instances.add(resolveIdentifierToken(Identifiers.Injector), this.injector);
this.instances.add(resolveIdentifierToken(Identifiers.Renderer), o.THIS_EXPR.prop('renderer'));
this.instances.set(resolveIdentifierToken(Identifiers.Injector).reference, this.injector);
this.instances.set(
resolveIdentifierToken(Identifiers.Renderer).reference, o.THIS_EXPR.prop('renderer'));
if (this.hasViewContainer || this.hasEmbeddedView || isPresent(this.component)) {
this._createAppElement();
}
@ -88,7 +89,7 @@ export class CompileElement extends CompileNode {
.toStmt();
this.view.createMethod.addStmt(statement);
this.appElement = o.THIS_EXPR.prop(fieldName);
this.instances.add(resolveIdentifierToken(Identifiers.AppElement), this.appElement);
this.instances.set(resolveIdentifierToken(Identifiers.AppElement).reference, this.appElement);
}
public createComponentFactoryResolver(entryComponents: CompileIdentifierMetadata[]) {
@ -142,17 +143,18 @@ export class CompileElement extends CompileNode {
beforeChildren(): void {
if (this.hasViewContainer) {
this.instances.add(
resolveIdentifierToken(Identifiers.ViewContainerRef), this.appElement.prop('vcRef'));
this.instances.set(
resolveIdentifierToken(Identifiers.ViewContainerRef).reference,
this.appElement.prop('vcRef'));
}
this._resolvedProviders = new CompileIdentifierMap<CompileTokenMetadata, ProviderAst>();
this._resolvedProviders = new Map<any, ProviderAst>();
this._resolvedProvidersArray.forEach(
provider => this._resolvedProviders.add(provider.token, provider));
provider => this._resolvedProviders.set(provider.token.reference, provider));
// create all the provider instances, some in the view constructor,
// some as getters. We rely on the fact that they are already sorted topologically.
this._resolvedProviders.values().forEach((resolvedProvider) => {
MapWrapper.values(this._resolvedProviders).forEach((resolvedProvider) => {
var providerValueExpressions = resolvedProvider.providers.map((provider) => {
if (isPresent(provider.useExisting)) {
return this._getDependency(
@ -175,16 +177,16 @@ export class CompileElement extends CompileNode {
var instance = createProviderProperty(
propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider,
resolvedProvider.eager, this);
this.instances.add(resolvedProvider.token, instance);
this.instances.set(resolvedProvider.token.reference, instance);
});
for (var i = 0; i < this._directives.length; i++) {
var directive = this._directives[i];
var directiveInstance = this.instances.get(identifierToken(directive.type));
var directiveInstance = this.instances.get(identifierToken(directive.type).reference);
directive.queries.forEach((queryMeta) => { this._addQuery(queryMeta, directiveInstance); });
}
var queriesWithReads: _QueryWithRead[] = [];
this._resolvedProviders.values().forEach((resolvedProvider) => {
MapWrapper.values(this._resolvedProviders).forEach((resolvedProvider) => {
var queriesForProvider = this._getQueriesFor(resolvedProvider.token);
ListWrapper.addAll(
queriesWithReads,
@ -194,7 +196,7 @@ export class CompileElement extends CompileNode {
var token = this.referenceTokens[varName];
var varValue: o.Expression;
if (isPresent(token)) {
varValue = this.instances.get(token);
varValue = this.instances.get(token.reference);
} else {
varValue = this.renderNode;
}
@ -208,12 +210,12 @@ export class CompileElement extends CompileNode {
var value: o.Expression;
if (isPresent(queryWithRead.read.identifier)) {
// query for an identifier
value = this.instances.get(queryWithRead.read);
value = this.instances.get(queryWithRead.read.reference);
} else {
// query for a reference
var token = this.referenceTokens[queryWithRead.read.value];
if (isPresent(token)) {
value = this.instances.get(token);
value = this.instances.get(token.reference);
} else {
value = this.elementRef;
}
@ -238,11 +240,11 @@ export class CompileElement extends CompileNode {
}
afterChildren(childNodeCount: number) {
this._resolvedProviders.values().forEach((resolvedProvider) => {
MapWrapper.values(this._resolvedProviders).forEach((resolvedProvider) => {
// Note: afterChildren is called after recursing into children.
// This is good so that an injector match in an element that is closer to a requesting element
// matches first.
var providerExpr = this.instances.get(resolvedProvider.token);
var providerExpr = this.instances.get(resolvedProvider.token.reference);
// Note: view providers are only visible on the injector of that element.
// This is not fully correct as the rules during codegen don't allow a directive
// to get hold of a view provdier on the same element. We still do this semantic
@ -253,10 +255,11 @@ export class CompileElement extends CompileNode {
this.nodeIndex, providerChildNodeCount, resolvedProvider, providerExpr));
});
this._queries.values().forEach(
(queries) => queries.forEach(
(query) =>
query.afterChildren(this.view.createMethod, this.view.updateContentQueriesMethod)));
MapWrapper.values(this._queries)
.forEach(
(queries) => queries.forEach(
(query) => query.afterChildren(
this.view.createMethod, this.view.updateContentQueriesMethod)));
}
addContentNode(ngContentIndex: number, nodeExpr: o.Expression) {
@ -264,13 +267,14 @@ export class CompileElement extends CompileNode {
}
getComponent(): o.Expression {
return isPresent(this.component) ? this.instances.get(identifierToken(this.component.type)) :
null;
return isPresent(this.component) ?
this.instances.get(identifierToken(this.component.type).reference) :
null;
}
getProviderTokens(): o.Expression[] {
return this._resolvedProviders.values().map(
(resolvedProvider) => createDiTokenExpression(resolvedProvider.token));
return MapWrapper.values(this._resolvedProviders)
.map((resolvedProvider) => createDiTokenExpression(resolvedProvider.token));
}
private _getQueriesFor(token: CompileTokenMetadata): CompileQuery[] {
@ -279,7 +283,7 @@ export class CompileElement extends CompileNode {
var distance = 0;
var queries: CompileQuery[];
while (!currentEl.isNull()) {
queries = currentEl._queries.get(token);
queries = currentEl._queries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(
result, queries.filter((query) => query.meta.descendants || distance <= 1));
@ -289,7 +293,7 @@ export class CompileElement extends CompileNode {
}
currentEl = currentEl.parent;
}
queries = this.view.componentView.viewQueries.get(token);
queries = this.view.componentView.viewQueries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries);
}
@ -325,7 +329,8 @@ export class CompileElement extends CompileNode {
if (isPresent(dep.token)) {
// access builtins with special visibility
if (isBlank(result)) {
if (dep.token.equalsTo(resolveIdentifierToken(Identifiers.ChangeDetectorRef))) {
if (dep.token.reference ===
resolveIdentifierToken(Identifiers.ChangeDetectorRef).reference) {
if (requestingProviderType === ProviderAstType.Component) {
return this._compViewExpr.prop('ref');
} else {
@ -335,7 +340,7 @@ export class CompileElement extends CompileNode {
}
// access regular providers on the element
if (isBlank(result)) {
let resolvedProvider = this._resolvedProviders.get(dep.token);
let resolvedProvider = this._resolvedProviders.get(dep.token.reference);
// don't allow directives / public services to access private services.
// only components and private services can access private services.
if (resolvedProvider && (requestingProviderType === ProviderAstType.Directive ||
@ -343,7 +348,7 @@ export class CompileElement extends CompileNode {
resolvedProvider.providerType === ProviderAstType.PrivateService) {
return null;
}
result = this.instances.get(dep.token);
result = this.instances.get(dep.token.reference);
}
}
return result;

View File

@ -42,7 +42,8 @@ export class CompilePipe {
constructor(public view: CompileView, public meta: CompilePipeMetadata) {
this.instance = o.THIS_EXPR.prop(`_pipe_${meta.name}_${view.pipeCount++}`);
var deps = this.meta.type.diDeps.map((diDep) => {
if (diDep.token.equalsTo(resolveIdentifierToken(Identifiers.ChangeDetectorRef))) {
if (diDep.token.reference ===
resolveIdentifierToken(Identifiers.ChangeDetectorRef).reference) {
return getPropertyInView(o.THIS_EXPR.prop('ref'), this.view, this.view.componentView);
}
return injectFromViewParentInjector(diDep.token, false);

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {CompileIdentifierMap, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {Identifiers, resolveIdentifier} from '../identifiers';
@ -126,13 +126,12 @@ export function createQueryList(
return expr;
}
export function addQueryToTokenMap(
map: CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>, query: CompileQuery) {
export function addQueryToTokenMap(map: Map<any, CompileQuery[]>, query: CompileQuery) {
query.meta.selectors.forEach((selector) => {
var entry = map.get(selector);
var entry = map.get(selector.reference);
if (isBlank(entry)) {
entry = [];
map.add(selector, entry);
map.set(selector.reference, entry);
}
entry.push(query);
});

View File

@ -8,9 +8,9 @@
import {ViewType} from '../../core_private';
import {CompiledAnimationTriggerResult} from '../animation/animation_compiler';
import {CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompilePipeMetadata, CompileTokenMetadata} from '../compile_metadata';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompilePipeMetadata, CompileTokenMetadata} from '../compile_metadata';
import {CompilerConfig} from '../config';
import {ListWrapper} from '../facade/collection';
import {ListWrapper, MapWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {Identifiers, resolveIdentifier} from '../identifiers';
import * as o from '../output/output_ast';
@ -27,7 +27,7 @@ import {createPureProxy, getPropertyInView, getViewFactoryName, injectFromViewPa
export class CompileView implements NameResolver {
public viewType: ViewType;
public viewQueries: CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>;
public viewQueries: Map<any, CompileQuery[]>;
public nodes: CompileNode[] = [];
// root nodes or AppElements for ViewContainers
@ -98,7 +98,7 @@ export class CompileView implements NameResolver {
this.componentContext =
getPropertyInView(o.THIS_EXPR.prop('context'), this, this.componentView);
var viewQueries = new CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>();
var viewQueries = new Map<any, CompileQuery[]>();
if (this.viewType === ViewType.COMPONENT) {
var directiveInstance = o.THIS_EXPR.prop('context');
ListWrapper.forEachWithIndex(this.component.viewQueries, (queryMeta, queryIndex) => {
@ -191,9 +191,10 @@ export class CompileView implements NameResolver {
}
afterNodes() {
this.viewQueries.values().forEach(
(queries) => queries.forEach(
(query) => query.afterChildren(this.createMethod, this.updateViewQueriesMethod)));
MapWrapper.values(this.viewQueries)
.forEach(
(queries) => queries.forEach(
(query) => query.afterChildren(this.createMethod, this.updateViewQueriesMethod)));
}
}

View File

@ -165,7 +165,7 @@ export function collectEventListeners(
});
dirs.forEach((directiveAst) => {
var directiveInstance =
compileElement.instances.get(identifierToken(directiveAst.directive.type));
compileElement.instances.get(identifierToken(directiveAst.directive.type).reference);
directiveAst.hostEvents.forEach((hostEvent) => {
compileElement.view.bindings.push(new CompileBinding(compileElement, hostEvent));
var listener = CompileEventListener.getOrCreate(

View File

@ -67,8 +67,7 @@ class ViewBinderVisitor implements TemplateAstVisitor {
bindRenderInputs(ast.inputs, compileElement);
bindRenderOutputs(eventListeners);
ast.directives.forEach((directiveAst) => {
var directiveInstance =
compileElement.instances.get(identifierToken(directiveAst.directive.type));
var directiveInstance = compileElement.instances.get(directiveAst.directive.type.reference);
bindDirectiveInputs(directiveAst, directiveInstance, compileElement);
bindDirectiveDetectChangesLifecycleCallbacks(directiveAst, directiveInstance, compileElement);
@ -79,15 +78,14 @@ class ViewBinderVisitor implements TemplateAstVisitor {
// afterContent and afterView lifecycles need to be called bottom up
// so that children are notified before parents
ast.directives.forEach((directiveAst) => {
var directiveInstance =
compileElement.instances.get(identifierToken(directiveAst.directive.type));
var directiveInstance = compileElement.instances.get(directiveAst.directive.type.reference);
bindDirectiveAfterContentLifecycleCallbacks(
directiveAst.directive, directiveInstance, compileElement);
bindDirectiveAfterViewLifecycleCallbacks(
directiveAst.directive, directiveInstance, compileElement);
});
ast.providers.forEach((providerAst) => {
var providerInstance = compileElement.instances.get(providerAst.token);
var providerInstance = compileElement.instances.get(providerAst.token.reference);
bindInjectableDestroyLifecycleCallbacks(providerAst, providerInstance, compileElement);
});
return null;
@ -97,8 +95,7 @@ class ViewBinderVisitor implements TemplateAstVisitor {
var compileElement = <CompileElement>this.view.nodes[this._nodeIndex++];
var eventListeners = collectEventListeners(ast.outputs, ast.directives, compileElement);
ast.directives.forEach((directiveAst) => {
var directiveInstance =
compileElement.instances.get(identifierToken(directiveAst.directive.type));
var directiveInstance = compileElement.instances.get(directiveAst.directive.type.reference);
bindDirectiveInputs(directiveAst, directiveInstance, compileElement);
bindDirectiveDetectChangesLifecycleCallbacks(directiveAst, directiveInstance, compileElement);
bindDirectiveOutputs(directiveAst, directiveInstance, eventListeners);
@ -108,7 +105,7 @@ class ViewBinderVisitor implements TemplateAstVisitor {
directiveAst.directive, directiveInstance, compileElement);
});
ast.providers.forEach((providerAst) => {
var providerInstance = compileElement.instances.get(providerAst.token);
var providerInstance = compileElement.instances.get(providerAst.token.reference);
bindInjectableDestroyLifecycleCallbacks(providerAst, providerInstance, compileElement);
});
bindView(compileElement.embeddedView, ast.children, []);

View File

@ -1,34 +0,0 @@
/**
* @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 {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() {
describe('Compiler', () => {
it('should generate the correct output when constructors have the same name', () => {
function ComponentFactory(selector: string, template: string) {
@Component({selector, template})
class MyComponent {
}
return MyComponent;
}
const HeroComponent = ComponentFactory('my-hero', 'my hero');
const VillianComponent = ComponentFactory('a-villian', 'a villian');
const MainComponent = ComponentFactory(
'my-app', 'I was saved by <my-hero></my-hero> from <a-villian></a-villian>.');
TestBed.configureTestingModule(
{declarations: [HeroComponent, VillianComponent, MainComponent]});
const fixture = TestBed.createComponent(MainComponent);
expect(fixture.debugElement.nativeElement)
.toHaveText('I was saved by my hero from a villian.');
});
});
}

View File

@ -27,7 +27,7 @@ export function main() {
expect(meta.selector).toEqual('someSelector');
expect(meta.exportAs).toEqual('someExportAs');
expect(meta.isComponent).toBe(true);
expect(meta.type.runtime).toBe(ComponentWithEverything);
expect(meta.type.reference).toBe(ComponentWithEverything);
expect(meta.type.name).toEqual(stringify(ComponentWithEverything));
expect(meta.type.lifecycleHooks).toEqual(LIFECYCLE_HOOKS_VALUES);
expect(meta.changeDetection).toBe(ChangeDetectionStrategy.Default);

View File

@ -23,20 +23,20 @@ export class ExternalClass {
var testDataIdentifier = new CompileIdentifierMetadata({
name: 'ExternalClass',
moduleUrl: `asset:@angular/lib/compiler/test/output/output_emitter_util`,
runtime: ExternalClass
reference: ExternalClass
});
var eventEmitterIdentifier = new CompileIdentifierMetadata(
{name: 'EventEmitter', moduleUrl: assetUrl('core'), runtime: EventEmitter});
{name: 'EventEmitter', moduleUrl: assetUrl('core'), reference: EventEmitter});
var enumIdentifier = new CompileIdentifierMetadata({
name: 'ViewType.HOST',
moduleUrl: assetUrl('core', 'linker/view_type'),
runtime: ViewType.HOST
reference: ViewType.HOST
});
var baseErrorIdentifier = new CompileIdentifierMetadata(
{name: 'BaseError', moduleUrl: assetUrl('core', 'facade/errors'), runtime: BaseError});
{name: 'BaseError', moduleUrl: assetUrl('core', 'facade/errors'), reference: BaseError});
export var codegenExportsVars = [
'getExpressions',

View File

@ -45,13 +45,13 @@ export function main() {
var component = CompileDirectiveMetadata.create({
selector: 'root',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'Root', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'Root', reference: {} as Type<any>}),
isComponent: true
});
ngIf = CompileDirectiveMetadata.create({
selector: '[ngIf]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'NgIf', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'NgIf', reference: {} as Type<any>}),
inputs: ['ngIf']
});
@ -179,7 +179,7 @@ export function main() {
const component = CompileDirectiveMetadata.create({
selector: 'test',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'Test', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'Test', reference: {} as Type<any>}),
isComponent: true,
template: new CompileTemplateMetadata({interpolation: ['{%', '%}']})
});
@ -309,7 +309,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
host: {'[@prop]': 'expr'}
});
@ -321,7 +321,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'broken',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
host: {'[class.foo]': null}
});
@ -334,7 +334,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'broken',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
host: {'(click)': null}
});
@ -397,7 +397,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
selector: 'template',
outputs: ['e'],
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<template (e)="f"></template>', [dirA]))).toEqual([
[EmbeddedTemplateAst],
@ -434,17 +434,17 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
var dirB = CompileDirectiveMetadata.create({
selector: '[b]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirB', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirB', reference: {} as Type<any>})
});
var dirC = CompileDirectiveMetadata.create({
selector: '[c]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirC', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirC', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div a c b a b>', [dirA, dirB, dirC]))).toEqual([
[ElementAst, 'div'], [AttrAst, 'a', ''], [AttrAst, 'c', ''], [AttrAst, 'b', ''],
@ -457,12 +457,12 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: '[a=b]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
var dirB = CompileDirectiveMetadata.create({
selector: '[b]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirB', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirB', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div [a]="b">', [dirA, dirB]))).toEqual([
[ElementAst, 'div'],
@ -475,7 +475,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirB', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirB', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div (a)="b">', [dirA]))).toEqual([
@ -487,7 +487,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
host: {'[a]': 'expr'}
});
expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([
@ -500,7 +500,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
host: {'(a)': 'expr'}
});
expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([
@ -512,7 +512,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['aProp']
});
expect(humanizeTplAst(parse('<div [aProp]="expr"></div>', [dirA]))).toEqual([
@ -525,7 +525,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['b:a']
});
expect(humanizeTplAst(parse('<div [a]="expr"></div>', [dirA]))).toEqual([
@ -537,7 +537,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['a']
});
expect(humanizeTplAst(parse('<div a="literal"></div>', [dirA]))).toEqual([
@ -550,7 +550,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['a']
});
expect(humanizeTplAst(parse('<div a="literal" [a]="\'literal2\'"></div>', [dirA])))
@ -564,7 +564,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['a']
});
expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([
@ -583,7 +583,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
const name = value.substring(5);
token = new CompileTokenMetadata({
identifier: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name, runtime: name as any as Type<any>})
{moduleUrl: someModuleUrl, name, reference: name as any as Type<any>})
});
} else {
token = new CompileTokenMetadata({value: value});
@ -618,7 +618,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
return new CompileProviderMetadata({
token: createToken(token),
multi: multi,
useClass: new CompileTypeMetadata({name, runtime: name as any as Type<any>}),
useClass: new CompileTypeMetadata({name, reference: name as any as Type<any>}),
deps: deps.map(createDep)
});
}
@ -637,7 +637,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
moduleUrl: someModuleUrl,
name: selector,
diDeps: deps.map(createDep),
runtime: selector as any as Type<any>
reference: selector as any as Type<any>
}),
isComponent: isComponent,
template: new CompileTemplateMetadata({ngContentSelectors: []}),
@ -887,7 +887,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
exportAs: 'dirA'
});
expect(humanizeTplAst(parse('<div a #a="dirA"></div>', [dirA]))).toEqual([
@ -932,7 +932,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
selector: '[a]',
isComponent: true,
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
exportAs: 'dirA',
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
@ -948,7 +948,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div ref-a>', [dirA]))).toEqual([
[ElementAst, 'div'], [ReferenceAst, 'a', null]
@ -995,7 +995,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<template let-a="b"></template>', [dirA]))).toEqual([
[EmbeddedTemplateAst], [VariableAst, 'a', 'b']
@ -1038,13 +1038,13 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
var dirA = CompileDirectiveMetadata.create({
selector: '[a=b]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['a']
});
var dirB = CompileDirectiveMetadata.create({
selector: '[b]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirB', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirB', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div template="a b" b>', [dirA, dirB]))).toEqual([
[EmbeddedTemplateAst], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', 'b'],
@ -1056,7 +1056,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div template="let a=b">', [dirA]))).toEqual([
[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']
@ -1067,7 +1067,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
expect(humanizeTplAst(parse('<div ref-a>', [dirA]))).toEqual([
[ElementAst, 'div'], [ReferenceAst, 'a', null]
@ -1104,7 +1104,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
type: new CompileTypeMetadata({
moduleUrl: someModuleUrl,
name: `SomeComp${compCounter++}`,
runtime: {} as Type<any>
reference: {} as Type<any>
}),
template: new CompileTemplateMetadata({ngContentSelectors: ngContentSelectors})
});
@ -1116,7 +1116,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
type: new CompileTypeMetadata({
moduleUrl: someModuleUrl,
name: `SomeDir${compCounter++}`,
runtime: {} as Type<any>
reference: {} as Type<any>
})
});
}
@ -1285,7 +1285,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'div'. ("<div [ER
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
host: {'[invalidProp]': 'someProp'}
});
expect(() => parse('<div></div>', [dirA])).toThrowError(`Template parse errors:
@ -1302,7 +1302,7 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['invalidProp']
});
expect(() => parse('<div [invalid-prop]></div>', [dirA])).not.toThrow();
@ -1313,14 +1313,14 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [
selector: 'div',
isComponent: true,
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
var dirB = CompileDirectiveMetadata.create({
selector: 'div',
isComponent: true,
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirB', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirB', reference: {} as Type<any>}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
expect(() => parse('<div>', [dirB, dirA])).toThrowError(`Template parse errors:
@ -1333,7 +1333,7 @@ More than one component: DirB,DirA ("[ERROR ->]<div>"): TestComp@0:0`);
selector: '[a]',
isComponent: true,
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
expect(() => parse('<template [a]="b" (e)="f"></template>', [dirA]))
@ -1348,7 +1348,7 @@ Property binding a not used by any directive on an embedded template. Make sure
selector: '[a]',
isComponent: true,
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
expect(() => parse('<div *a="b"></div>', [dirA])).toThrowError(`Template parse errors:
@ -1501,13 +1501,13 @@ Property binding a not used by any directive on an embedded template. Make sure
var dirA = CompileDirectiveMetadata.create({
selector: '[a]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
var comp = CompileDirectiveMetadata.create({
selector: 'div',
isComponent: true,
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'ZComp', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'ZComp', reference: {} as Type<any>}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
expect(humanizeTplAstSourceSpans(parse('<div a>', [dirA, comp]))).toEqual([
@ -1520,12 +1520,12 @@ Property binding a not used by any directive on an embedded template. Make sure
var tagSel = CompileDirectiveMetadata.create({
selector: 'circle',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'elDir', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'elDir', reference: {} as Type<any>})
});
var attrSel = CompileDirectiveMetadata.create({
selector: '[href]',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'attrDir', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'attrDir', reference: {} as Type<any>})
});
expect(humanizeTplAstSourceSpans(
@ -1544,7 +1544,7 @@ Property binding a not used by any directive on an embedded template. Make sure
var dirA = CompileDirectiveMetadata.create({
selector: 'div',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>}),
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>}),
inputs: ['aProp']
});
expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo"></div>', [dirA]))).toEqual([
@ -1560,7 +1560,7 @@ Property binding a not used by any directive on an embedded template. Make sure
var testPipe = new CompilePipeMetadata({
name: 'test',
type: new CompileTypeMetadata(
{moduleUrl: someModuleUrl, name: 'DirA', runtime: {} as Type<any>})
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
});
expect(() => parse('{{a | test}}', [], [testPipe])).not.toThrow();
});

View File

@ -21,6 +21,6 @@ export interface PlatformReflectionCapabilities {
setter(name: string): SetterFn;
method(name: string): MethodFn;
importUri(type: Type<any>): string;
resolveType(name: string, moduleUrl: string): any;
resolveEnum(enumType: any, name: string): any;
resolveIdentifier(name: string, moduleUrl: string, runtime: any): any;
resolveEnum(enumIdentifier: any, name: string): any;
}

View File

@ -173,8 +173,8 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
return `./${stringify(type)}`;
}
resolveType(name: string, moduleUrl: string): any { return null; }
resolveEnum(enumType: any, name: string): any { return null; }
resolveIdentifier(name: string, moduleUrl: string, runtime: any): any { return runtime; }
resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; }
}
function convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {

View File

@ -177,11 +177,11 @@ export class Reflector extends ReflectorReader {
importUri(type: any): string { return this.reflectionCapabilities.importUri(type); }
resolveType(name: string, moduleUrl: string): any {
return this.reflectionCapabilities.resolveType(name, moduleUrl);
resolveIdentifier(name: string, moduleUrl: string, runtime: any): any {
return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, runtime);
}
resolveEnum(type: any, name: string): any {
return this.reflectionCapabilities.resolveEnum(type, name);
resolveEnum(identifier: any, name: string): any {
return this.reflectionCapabilities.resolveEnum(identifier, name);
}
}

View File

@ -15,6 +15,6 @@ export abstract class ReflectorReader {
abstract annotations(typeOrFunc: /*Type*/ any): any[];
abstract propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]};
abstract importUri(typeOrFunc: /*Type*/ any): string;
abstract resolveType(name: string, moduleUrl: string): any;
abstract resolveEnum(type: any, name: string): any;
abstract resolveIdentifier(name: string, moduleUrl: string, runtime: any): any;
abstract resolveEnum(identifier: any, name: string): any;
}

View File

@ -149,6 +149,25 @@ function declareTests({useJit}: {useJit: boolean}) {
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[]');
});
it('should generate the correct output when constructors have the same name', () => {
function ComponentFactory(selector: string, template: string) {
@Component({selector, template})
class MyComponent {
}
return MyComponent;
}
const HeroComponent = ComponentFactory('my-hero', 'my hero');
const VillianComponent = ComponentFactory('a-villian', 'a villian');
const MainComponent = ComponentFactory(
'my-app', 'I was saved by <my-hero></my-hero> from <a-villian></a-villian>.');
TestBed.configureTestingModule(
{declarations: [HeroComponent, VillianComponent, MainComponent]});
const fixture = TestBed.createComponent(MainComponent);
expect(fixture.debugElement.nativeElement)
.toHaveText('I was saved by my hero from a villian.');
});
});
}