diff --git a/packages/common/test/pipes/date_pipe_spec.ts b/packages/common/test/pipes/date_pipe_spec.ts index d45ed67e09..07a009d0dc 100644 --- a/packages/common/test/pipes/date_pipe_spec.ts +++ b/packages/common/test/pipes/date_pipe_spec.ts @@ -7,6 +7,7 @@ */ import {DatePipe} from '@angular/common'; +import {JitReflector} from '@angular/compiler'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {browserDetection} from '@angular/platform-browser/testing/src/browser_util'; @@ -34,8 +35,9 @@ export function main() { pipe = new DatePipe('en-US'); }); - it('should be marked as pure', - () => { expect(new PipeResolver().resolve(DatePipe) !.pure).toEqual(true); }); + it('should be marked as pure', () => { + expect(new PipeResolver(new JitReflector()).resolve(DatePipe) !.pure).toEqual(true); + }); describe('supports', () => { it('should support date', () => { expect(() => pipe.transform(date)).not.toThrow(); }); diff --git a/packages/common/test/pipes/i18n_plural_pipe_spec.ts b/packages/common/test/pipes/i18n_plural_pipe_spec.ts index 974d64fe52..436657b026 100644 --- a/packages/common/test/pipes/i18n_plural_pipe_spec.ts +++ b/packages/common/test/pipes/i18n_plural_pipe_spec.ts @@ -7,6 +7,7 @@ */ import {I18nPluralPipe, NgLocalization} from '@angular/common'; +import {JitReflector} from '@angular/compiler'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {beforeEach, describe, expect, it} from '@angular/core/testing/src/testing_internal'; @@ -27,8 +28,9 @@ export function main() { pipe = new I18nPluralPipe(localization); }); - it('should be marked as pure', - () => { expect(new PipeResolver().resolve(I18nPluralPipe) !.pure).toEqual(true); }); + it('should be marked as pure', () => { + expect(new PipeResolver(new JitReflector()).resolve(I18nPluralPipe) !.pure).toEqual(true); + }); describe('transform', () => { it('should return 0 text if value is 0', () => { diff --git a/packages/common/test/pipes/i18n_select_pipe_spec.ts b/packages/common/test/pipes/i18n_select_pipe_spec.ts index 71fede8bac..d88e4b5c64 100644 --- a/packages/common/test/pipes/i18n_select_pipe_spec.ts +++ b/packages/common/test/pipes/i18n_select_pipe_spec.ts @@ -7,6 +7,7 @@ */ import {I18nSelectPipe} from '@angular/common'; +import {JitReflector} from '@angular/compiler'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; export function main() { @@ -14,8 +15,9 @@ export function main() { const pipe: I18nSelectPipe = new I18nSelectPipe(); const mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'}; - it('should be marked as pure', - () => { expect(new PipeResolver().resolve(I18nSelectPipe) !.pure).toEqual(true); }); + it('should be marked as pure', () => { + expect(new PipeResolver(new JitReflector()).resolve(I18nSelectPipe) !.pure).toEqual(true); + }); describe('transform', () => { it('should return the "male" text if value is "male"', () => { diff --git a/packages/compiler-cli/src/diagnostics/typescript_symbols.ts b/packages/compiler-cli/src/diagnostics/typescript_symbols.ts index d53d6d9f5c..da82db0f18 100644 --- a/packages/compiler-cli/src/diagnostics/typescript_symbols.ts +++ b/packages/compiler-cli/src/diagnostics/typescript_symbols.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AotSummaryResolver, CompileMetadataResolver, CompilePipeSummary, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, InterpolationConfig, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, PipeResolver, ResourceLoader, StaticAndDynamicReflectionCapabilities, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, analyzeNgModules, componentModuleUrl, createOfflineCompileUrlResolver, extractProgramSymbols} from '@angular/compiler'; +import {AotSummaryResolver, CompileMetadataResolver, CompilePipeSummary, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, InterpolationConfig, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, PipeResolver, ResourceLoader, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, analyzeNgModules, createOfflineCompileUrlResolver, extractProgramSymbols} from '@angular/compiler'; import {ViewEncapsulation, ɵConsole as Console} from '@angular/core'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/packages/compiler-cli/test/diagnostics/mocks.ts b/packages/compiler-cli/test/diagnostics/mocks.ts index f269db68d1..68e7f5ccce 100644 --- a/packages/compiler-cli/test/diagnostics/mocks.ts +++ b/packages/compiler-cli/test/diagnostics/mocks.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AotCompilerHost, AotSummaryResolver, CompileMetadataResolver, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, I18NHtmlParser, InterpolationConfig, JitSummaryResolver, Lexer, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, Parser, PipeResolver, ResourceLoader, StaticAndDynamicReflectionCapabilities, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, TemplateParser, analyzeNgModules, createOfflineCompileUrlResolver, extractProgramSymbols} from '@angular/compiler'; +import {AotCompilerHost, AotSummaryResolver, CompileMetadataResolver, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, I18NHtmlParser, InterpolationConfig, JitSummaryResolver, Lexer, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, Parser, PipeResolver, ResourceLoader, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, TemplateParser, analyzeNgModules, createOfflineCompileUrlResolver, extractProgramSymbols} from '@angular/compiler'; import {ViewEncapsulation, ɵConsole as Console} from '@angular/core'; import {CompilerHostContext} from 'compiler-cli'; import * as fs from 'fs'; @@ -134,7 +134,6 @@ export class DiagnosticContext { const ssr = this.staticSymbolResolver; const result = this._reflector = new StaticReflector( summaryResolver, ssr, [], [], (e, filePath) => this.collectError(e, filePath !)); - StaticAndDynamicReflectionCapabilities.install(result); this._reflector = result; return result; } @@ -205,7 +204,8 @@ function compileTemplate(context: DiagnosticContext, type: StaticSymbol, templat const expressionParser = new Parser(new Lexer()); const config = new CompilerConfig(); const parser = new TemplateParser( - config, expressionParser, new DomElementSchemaRegistry(), htmlParser, null !, []); + config, context.reflector, expressionParser, new DomElementSchemaRegistry(), htmlParser, + null !, []); const htmlResult = htmlParser.parse(template, '', true); const analyzedModules = context.analyzedModules; // let errors: Diagnostic[]|undefined = undefined; diff --git a/packages/compiler-cli/test/main_spec.ts b/packages/compiler-cli/test/main_spec.ts index bbb50117be..5d832b73b2 100644 --- a/packages/compiler-cli/test/main_spec.ts +++ b/packages/compiler-cli/test/main_spec.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {ɵReflectionCapabilities, ɵreflector} from '@angular/core'; import {makeTempDir} from '@angular/tsc-wrapped/test/test_support'; import * as fs from 'fs'; import * as path from 'path'; @@ -42,9 +41,6 @@ describe('compiler-cli', () => { fs.symlinkSync(path.resolve(__dirname, '..', '..'), path.resolve(nodeModulesPath, '@angular')); }); - // Restore reflector since AoT compiler will update it with a new static reflector - afterEach(() => { ɵreflector.updateCapabilities(new ɵReflectionCapabilities()); }); - it('should compile without errors', (done) => { write('test.ts', 'export const A = 1;'); diff --git a/packages/compiler/src/aot/compiler.ts b/packages/compiler/src/aot/compiler.ts index 86a471a99d..3aa6234df4 100644 --- a/packages/compiler/src/aot/compiler.ts +++ b/packages/compiler/src/aot/compiler.ts @@ -8,7 +8,7 @@ import {CompileDirectiveMetadata, CompileDirectiveSummary, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileNgModuleSummary, CompilePipeMetadata, CompileProviderMetadata, CompileStylesheetMetadata, CompileSummaryKind, CompileTypeMetadata, CompileTypeSummary, componentFactoryName, createHostComponentMeta, flatten, identifierName, sourceUrl, templateSourceUrl} from '../compile_metadata'; import {CompilerConfig} from '../config'; -import {Identifiers, createIdentifier, createIdentifierToken} from '../identifiers'; +import {Identifiers, createTokenForExternalReference} from '../identifiers'; import {CompileMetadataResolver} from '../metadata_resolver'; import {NgModuleCompiler} from '../ng_module_compiler'; import {OutputEmitter} from '../output/abstract_emitter'; @@ -21,6 +21,7 @@ import {ViewCompileResult, ViewCompiler} from '../view_compiler/view_compiler'; import {AotCompilerHost} from './compiler_host'; import {GeneratedFile} from './generated_file'; +import {StaticReflector} from './static_reflector'; import {StaticSymbol} from './static_symbol'; import {ResolvedStaticSymbol, StaticSymbolResolver} from './static_symbol_resolver'; import {serializeSummaries} from './summary_serializer'; @@ -29,9 +30,10 @@ import {ngfactoryFilePath, splitTypescriptSuffix, summaryFileName, summaryForJit export class AotCompiler { constructor( private _config: CompilerConfig, private _host: AotCompilerHost, - private _metadataResolver: CompileMetadataResolver, private _templateParser: TemplateParser, - private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler, - private _ngModuleCompiler: NgModuleCompiler, private _outputEmitter: OutputEmitter, + private _reflector: StaticReflector, private _metadataResolver: CompileMetadataResolver, + private _templateParser: TemplateParser, private _styleCompiler: StyleCompiler, + private _viewCompiler: ViewCompiler, private _ngModuleCompiler: NgModuleCompiler, + private _outputEmitter: OutputEmitter, private _summaryResolver: SummaryResolver, private _localeId: string|null, private _translationFormat: string|null, private _symbolResolver: StaticSymbolResolver) {} @@ -154,14 +156,14 @@ export class AotCompiler { if (this._localeId) { providers.push({ - token: createIdentifierToken(Identifiers.LOCALE_ID), + token: createTokenForExternalReference(this._reflector, Identifiers.LOCALE_ID), useValue: this._localeId, }); } if (this._translationFormat) { providers.push({ - token: createIdentifierToken(Identifiers.TRANSLATIONS_FORMAT), + token: createTokenForExternalReference(this._reflector, Identifiers.TRANSLATIONS_FORMAT), useValue: this._translationFormat }); } diff --git a/packages/compiler/src/aot/compiler_factory.ts b/packages/compiler/src/aot/compiler_factory.ts index 8e7be5b1ed..ab44366458 100644 --- a/packages/compiler/src/aot/compiler_factory.ts +++ b/packages/compiler/src/aot/compiler_factory.ts @@ -28,7 +28,6 @@ import {ViewCompiler} from '../view_compiler/view_compiler'; import {AotCompiler} from './compiler'; import {AotCompilerHost} from './compiler_host'; import {AotCompilerOptions} from './compiler_options'; -import {StaticAndDynamicReflectionCapabilities} from './static_reflection_capabilities'; import {StaticReflector} from './static_reflector'; import {StaticSymbol, StaticSymbolCache} from './static_symbol'; import {StaticSymbolResolver} from './static_symbol_resolver'; @@ -47,7 +46,6 @@ export function createAotCompiler(compilerHost: AotCompilerHost, options: AotCom const summaryResolver = new AotSummaryResolver(compilerHost, symbolCache); const symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver); const staticReflector = new StaticReflector(summaryResolver, symbolResolver); - StaticAndDynamicReflectionCapabilities.install(staticReflector); const console = new Console(); const htmlParser = new I18NHtmlParser( new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console); @@ -61,17 +59,17 @@ export function createAotCompiler(compilerHost: AotCompilerHost, options: AotCom {get: (url: string) => compilerHost.loadResource(url)}, urlResolver, htmlParser, config); const expressionParser = new Parser(new Lexer()); const elementSchemaRegistry = new DomElementSchemaRegistry(); - const tmplParser = - new TemplateParser(config, expressionParser, elementSchemaRegistry, htmlParser, console, []); + const tmplParser = new TemplateParser( + config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []); const resolver = new CompileMetadataResolver( config, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector); // TODO(vicb): do not pass options.i18nFormat here - const viewCompiler = new ViewCompiler(config, elementSchemaRegistry); + const viewCompiler = new ViewCompiler(config, staticReflector, elementSchemaRegistry); const compiler = new AotCompiler( - config, compilerHost, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, - new NgModuleCompiler(), new TypeScriptEmitter(), summaryResolver, options.locale || null, - options.i18nFormat || null, symbolResolver); + config, compilerHost, staticReflector, resolver, tmplParser, new StyleCompiler(urlResolver), + viewCompiler, new NgModuleCompiler(staticReflector), new TypeScriptEmitter(), summaryResolver, + options.locale || null, options.i18nFormat || null, symbolResolver); return {compiler, reflector: staticReflector}; } diff --git a/packages/compiler/src/aot/static_reflection_capabilities.ts b/packages/compiler/src/aot/static_reflection_capabilities.ts deleted file mode 100644 index 4a11410ee9..0000000000 --- a/packages/compiler/src/aot/static_reflection_capabilities.ts +++ /dev/null @@ -1,60 +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 {ɵGetterFn, ɵMethodFn, ɵReflectionCapabilities, ɵSetterFn, ɵreflector} from '@angular/core'; -import {StaticReflector} from './static_reflector'; -import {StaticSymbol} from './static_symbol'; - -export class StaticAndDynamicReflectionCapabilities { - static install(staticDelegate: StaticReflector) { - ɵreflector.updateCapabilities(new StaticAndDynamicReflectionCapabilities(staticDelegate)); - } - - private dynamicDelegate = new ɵReflectionCapabilities(); - - constructor(private staticDelegate: StaticReflector) {} - - isReflectionEnabled(): boolean { return true; } - factory(type: any): Function { return this.dynamicDelegate.factory(type); } - - hasLifecycleHook(type: any, lcProperty: string): boolean { - return isStaticType(type) ? this.staticDelegate.hasLifecycleHook(type, lcProperty) : - this.dynamicDelegate.hasLifecycleHook(type, lcProperty); - } - parameters(type: any): any[][] { - return isStaticType(type) ? this.staticDelegate.parameters(type) : - this.dynamicDelegate.parameters(type); - } - annotations(type: any): any[] { - return isStaticType(type) ? this.staticDelegate.annotations(type) : - this.dynamicDelegate.annotations(type); - } - propMetadata(typeOrFunc: any): {[key: string]: any[]} { - return isStaticType(typeOrFunc) ? this.staticDelegate.propMetadata(typeOrFunc) : - this.dynamicDelegate.propMetadata(typeOrFunc); - } - getter(name: string): ɵGetterFn { return this.dynamicDelegate.getter(name); } - setter(name: string): ɵSetterFn { return this.dynamicDelegate.setter(name); } - method(name: string): ɵMethodFn { return this.dynamicDelegate.method(name); } - importUri(type: any): string { return this.staticDelegate.importUri(type) !; } - resourceUri(type: any): string { return this.staticDelegate.resourceUri(type); } - resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any) { - return this.staticDelegate.resolveIdentifier(name, moduleUrl, members); - } - resolveEnum(enumIdentifier: any, name: string): any { - if (isStaticType(enumIdentifier)) { - return this.staticDelegate.resolveEnum(enumIdentifier, name); - } else { - return null; - } - } -} - -function isStaticType(type: any): boolean { - return typeof type === 'object' && type.name && type.filePath; -} diff --git a/packages/compiler/src/aot/static_reflector.ts b/packages/compiler/src/aot/static_reflector.ts index 9eb7134836..cf6f796635 100644 --- a/packages/compiler/src/aot/static_reflector.ts +++ b/packages/compiler/src/aot/static_reflector.ts @@ -6,9 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {Attribute, Component, ContentChild, ContentChildren, Directive, Host, HostBinding, HostListener, Inject, Injectable, Input, NgModule, Optional, Output, Pipe, Self, SkipSelf, ViewChild, ViewChildren, animate, group, keyframes, sequence, state, style, transition, trigger, ɵReflectorReader} from '@angular/core'; +import {Attribute, Component, ContentChild, ContentChildren, Directive, Host, HostBinding, HostListener, Inject, Injectable, Input, NgModule, Optional, Output, Pipe, Self, SkipSelf, ViewChild, ViewChildren, animate, group, keyframes, sequence, state, style, transition, trigger} from '@angular/core'; import {CompileSummaryKind} from '../compile_metadata'; +import {CompileReflector} from '../compile_reflector'; +import * as o from '../output/output_ast'; import {SummaryResolver} from '../summary_resolver'; import {syntaxError} from '../util'; @@ -31,7 +33,7 @@ function shouldIgnore(value: any): boolean { * A static reflector implements enough of the Reflector API that is necessary to compile * templates statically. */ -export class StaticReflector implements ɵReflectorReader { +export class StaticReflector implements CompileReflector { private annotationCache = new Map(); private propertyCache = new Map(); private parameterCache = new Map(); @@ -67,25 +69,17 @@ export class StaticReflector implements ɵReflectorReader { this.annotationNames.set(Injectable, 'Injectable'); } - importUri(typeOrFunc: StaticSymbol): string|null { - const staticSymbol = this.findSymbolDeclaration(typeOrFunc); - return staticSymbol ? staticSymbol.filePath : null; - } - - resourceUri(typeOrFunc: StaticSymbol): string { + componentModuleUrl(typeOrFunc: StaticSymbol): string { const staticSymbol = this.findSymbolDeclaration(typeOrFunc); return this.symbolResolver.getResourcePath(staticSymbol); } - resolveIdentifier(name: string, moduleUrl: string, members: string[]): StaticSymbol { - const importSymbol = this.getStaticSymbol(moduleUrl, name); - const rootSymbol = this.findDeclaration(moduleUrl, name); + resolveExternalReference(ref: o.ExternalReference): StaticSymbol { + const importSymbol = this.getStaticSymbol(ref.moduleName !, ref.name !); + const rootSymbol = this.findDeclaration(ref.moduleName !, ref.name !); if (importSymbol != rootSymbol) { this.symbolResolver.recordImportAs(rootSymbol, importSymbol); } - if (members && members.length) { - return this.getStaticSymbol(rootSymbol.filePath, rootSymbol.name, members); - } return rootSymbol; } @@ -103,12 +97,6 @@ export class StaticReflector implements ɵReflectorReader { } } - resolveEnum(enumIdentifier: any, name: string): any { - const staticSymbol: StaticSymbol = enumIdentifier; - const members = (staticSymbol.members || []).concat(name); - return this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name, members); - } - public annotations(type: StaticSymbol): any[] { let annotations = this.annotationCache.get(type); if (!annotations) { diff --git a/packages/compiler/src/compile_metadata.ts b/packages/compiler/src/compile_metadata.ts index ea0d1f4ea2..1e305fd879 100644 --- a/packages/compiler/src/compile_metadata.ts +++ b/packages/compiler/src/compile_metadata.ts @@ -6,9 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ -import {ChangeDetectionStrategy, ComponentFactory, RendererType2, SchemaMetadata, Type, ViewEncapsulation, ɵLifecycleHooks, ɵreflector, ɵstringify as stringify} from '@angular/core'; +import {ChangeDetectionStrategy, ComponentFactory, RendererType2, SchemaMetadata, Type, ViewEncapsulation, ɵstringify as stringify} from '@angular/core'; import {StaticSymbol} from './aot/static_symbol'; +import {LifecycleHooks} from './lifecycle_reflector'; import {CssSelector} from './selector'; import {splitAtColon} from './util'; @@ -111,7 +112,8 @@ export function identifierModuleUrl(compileIdentifier: CompileIdentifierMetadata if (ref instanceof StaticSymbol) { return ref.filePath; } - return ɵreflector.importUri(ref); + // Runtime type + return `./${stringify(ref)}`; } export function viewClassName(compType: any, embeddedTemplateIndex: number): string { @@ -203,7 +205,7 @@ export interface CompileTokenMetadata { */ export interface CompileTypeMetadata extends CompileIdentifierMetadata { diDeps: CompileDiDependencyMetadata[]; - lifecycleHooks: ɵLifecycleHooks[]; + lifecycleHooks: LifecycleHooks[]; reference: any; } diff --git a/packages/compiler/src/compile_reflector.ts b/packages/compiler/src/compile_reflector.ts new file mode 100644 index 0000000000..67eec55e54 --- /dev/null +++ b/packages/compiler/src/compile_reflector.ts @@ -0,0 +1,22 @@ +/** + * @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 * as o from './output/output_ast'; + +/** + * Provides access to reflection data about symbols that the compiler needs. + */ +export abstract class CompileReflector { + abstract parameters(typeOrFunc: /*Type*/ any): any[][]; + abstract annotations(typeOrFunc: /*Type*/ any): any[]; + abstract propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]}; + abstract hasLifecycleHook(type: any, lcProperty: string): boolean; + abstract componentModuleUrl(type: /*Type*/ any, cmpMetadata: Component): string; + abstract resolveExternalReference(ref: o.ExternalReference): any; +} diff --git a/packages/compiler/src/compiler.ts b/packages/compiler/src/compiler.ts index 9f0b536da6..af7c9e79bf 100644 --- a/packages/compiler/src/compiler.ts +++ b/packages/compiler/src/compiler.ts @@ -32,7 +32,6 @@ export * from './aot/generated_file'; export * from './aot/compiler_options'; export * from './aot/compiler_host'; export * from './aot/static_reflector'; -export * from './aot/static_reflection_capabilities'; export * from './aot/static_symbol'; export * from './aot/static_symbol_resolver'; export * from './aot/summary_resolver'; @@ -40,6 +39,8 @@ export * from './ast_path'; export * from './summary_resolver'; export {JitCompiler} from './jit/compiler'; export * from './jit/compiler_factory'; +export * from './jit/jit_reflector'; +export * from './compile_reflector'; export * from './url_resolver'; export * from './resource_loader'; export {DirectiveResolver} from './directive_resolver'; diff --git a/packages/compiler/src/compiler_util/expression_converter.ts b/packages/compiler/src/compiler_util/expression_converter.ts index 4439433684..61e976a573 100644 --- a/packages/compiler/src/compiler_util/expression_converter.ts +++ b/packages/compiler/src/compiler_util/expression_converter.ts @@ -8,7 +8,7 @@ import * as cdAst from '../expression_parser/ast'; -import {Identifiers, createIdentifier} from '../identifiers'; +import {Identifiers} from '../identifiers'; import * as o from '../output/output_ast'; export class EventHandlerVars { static event = o.variable('$event'); } diff --git a/packages/compiler/src/config.ts b/packages/compiler/src/config.ts index 52c4fad95e..75be193731 100644 --- a/packages/compiler/src/config.ts +++ b/packages/compiler/src/config.ts @@ -9,7 +9,7 @@ import {InjectionToken, MissingTranslationStrategy, ViewEncapsulation, isDevMode} from '@angular/core'; import {CompileIdentifierMetadata} from './compile_metadata'; -import {Identifiers, createIdentifier} from './identifiers'; +import {Identifiers} from './identifiers'; export class CompilerConfig { diff --git a/packages/compiler/src/directive_resolver.ts b/packages/compiler/src/directive_resolver.ts index 8648bbf65f..2b1790305f 100644 --- a/packages/compiler/src/directive_resolver.ts +++ b/packages/compiler/src/directive_resolver.ts @@ -6,11 +6,14 @@ * found in the LICENSE file at https://angular.io/license */ -import {Component, Directive, HostBinding, HostListener, Input, Output, Query, Type, resolveForwardRef, ɵReflectorReader, ɵreflector, ɵstringify as stringify} from '@angular/core'; +import {Component, Directive, HostBinding, HostListener, Input, Output, Query, Type, resolveForwardRef, ɵstringify as stringify} from '@angular/core'; + +import {CompileReflector} from './compile_reflector'; import {CompilerInjectable} from './injectable'; import {splitAtColon} from './util'; + /* * Resolve a `Type` for {@link Directive}. * @@ -20,7 +23,7 @@ import {splitAtColon} from './util'; */ @CompilerInjectable() export class DirectiveResolver { - constructor(private _reflector: ɵReflectorReader = ɵreflector) {} + constructor(private _reflector: CompileReflector) {} isDirective(type: Type) { const typeMetadata = this._reflector.annotations(resolveForwardRef(type)); diff --git a/packages/compiler/src/i18n/extractor.ts b/packages/compiler/src/i18n/extractor.ts index aa69200bed..5b4c2922ef 100644 --- a/packages/compiler/src/i18n/extractor.ts +++ b/packages/compiler/src/i18n/extractor.ts @@ -13,7 +13,6 @@ import {ViewEncapsulation, ɵConsole as Console} from '@angular/core'; import {analyzeAndValidateNgModules, extractProgramSymbols} from '../aot/compiler'; -import {StaticAndDynamicReflectionCapabilities} from '../aot/static_reflection_capabilities'; import {StaticReflector} from '../aot/static_reflector'; import {StaticSymbolCache} from '../aot/static_symbol'; import {StaticSymbolResolver, StaticSymbolResolverHost} from '../aot/static_symbol_resolver'; @@ -95,7 +94,6 @@ export class Extractor { const summaryResolver = new AotSummaryResolver(host, symbolCache); const staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver); const staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver); - StaticAndDynamicReflectionCapabilities.install(staticReflector); const config = new CompilerConfig({defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false}); diff --git a/packages/compiler/src/identifiers.ts b/packages/compiler/src/identifiers.ts index cf7069b650..b2c1d179eb 100644 --- a/packages/compiler/src/identifiers.ts +++ b/packages/compiler/src/identifiers.ts @@ -6,12 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {ANALYZE_FOR_ENTRY_COMPONENTS, ChangeDetectionStrategy, ChangeDetectorRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, ElementRef, Injector, LOCALE_ID, NgModuleFactory, NgModuleRef, QueryList, Renderer, SecurityContext, TRANSLATIONS_FORMAT, TemplateRef, ViewContainerRef, ViewEncapsulation, ɵCodegenComponentFactoryResolver, ɵEMPTY_ARRAY, ɵEMPTY_MAP, ɵand, ɵccf, ɵcmf, ɵcrt, ɵdid, ɵeld, ɵinlineInterpolate, ɵinterpolate, ɵmod, ɵmpd, ɵncd, ɵnov, ɵpad, ɵpid, ɵpod, ɵppd, ɵprd, ɵqud, ɵreflector, ɵregisterModuleFactory, ɵted, ɵunv, ɵvid} from '@angular/core'; +import {ANALYZE_FOR_ENTRY_COMPONENTS, ChangeDetectionStrategy, ChangeDetectorRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, ElementRef, Injector, LOCALE_ID, NgModuleFactory, NgModuleRef, QueryList, Renderer, SecurityContext, TRANSLATIONS_FORMAT, TemplateRef, ViewContainerRef, ViewEncapsulation, ɵCodegenComponentFactoryResolver, ɵEMPTY_ARRAY, ɵEMPTY_MAP, ɵand, ɵccf, ɵcmf, ɵcrt, ɵdid, ɵeld, ɵinlineInterpolate, ɵinterpolate, ɵmod, ɵmpd, ɵncd, ɵnov, ɵpad, ɵpid, ɵpod, ɵppd, ɵprd, ɵqud, ɵregisterModuleFactory, ɵted, ɵunv, ɵvid} from '@angular/core'; import {CompileIdentifierMetadata, CompileTokenMetadata} from './compile_metadata'; +import {CompileReflector} from './compile_reflector'; import * as o from './output/output_ast'; -const CORE = assetUrl('core'); +const CORE = '@angular/core'; export class Identifiers { static ANALYZE_FOR_ENTRY_COMPONENTS: o.ExternalReference = { @@ -134,33 +135,11 @@ export class Identifiers { o.ExternalReference = {name: 'ɵccf', moduleName: CORE, runtime: ɵccf}; } -export function assetUrl(pkg: string, path: string | null = null, type: string = 'src'): string { - if (path == null) { - return `@angular/${pkg}`; - } else { - return `@angular/${pkg}/${type}/${path}`; - } +export function createTokenForReference(reference: any): CompileTokenMetadata { + return {identifier: {reference: reference}}; } -export function resolveIdentifier(identifier: o.ExternalReference) { - let name = identifier.name; - return ɵreflector.resolveIdentifier(name !, identifier.moduleName !, null, identifier.runtime); -} - -export function createIdentifier(identifier: o.ExternalReference): CompileIdentifierMetadata { - return {reference: resolveIdentifier(identifier)}; -} - -export function identifierToken(identifier: CompileIdentifierMetadata): CompileTokenMetadata { - return {identifier: identifier}; -} - -export function createIdentifierToken(identifier: o.ExternalReference): CompileTokenMetadata { - return identifierToken(createIdentifier(identifier)); -} - -export function createEnumIdentifier( - enumType: o.ExternalReference, name: string): CompileIdentifierMetadata { - const resolvedEnum = ɵreflector.resolveEnum(resolveIdentifier(enumType), name); - return {reference: resolvedEnum}; +export function createTokenForExternalReference( + reflector: CompileReflector, reference: o.ExternalReference): CompileTokenMetadata { + return createTokenForReference(reflector.resolveExternalReference(reference)); } diff --git a/packages/compiler/src/jit/compiler_factory.ts b/packages/compiler/src/jit/compiler_factory.ts index 0060bc51a2..50f8115a56 100644 --- a/packages/compiler/src/jit/compiler_factory.ts +++ b/packages/compiler/src/jit/compiler_factory.ts @@ -6,8 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ -import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, InjectionToken, MissingTranslationStrategy, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore, ɵConsole as Console, ɵReflectionCapabilities as ReflectionCapabilities, ɵReflector as Reflector, ɵReflectorReader as ReflectorReader, ɵreflector as reflector} from '@angular/core'; +import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, InjectionToken, MissingTranslationStrategy, Optional, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore, ɵConsole as Console} from '@angular/core'; +import {CompileReflector} from '../compile_reflector'; import {CompilerConfig} from '../config'; import {DirectiveNormalizer} from '../directive_normalizer'; import {DirectiveResolver} from '../directive_resolver'; @@ -30,6 +31,7 @@ import {DEFAULT_PACKAGE_URL_PROVIDER, UrlResolver} from '../url_resolver'; import {ViewCompiler} from '../view_compiler/view_compiler'; import {JitCompiler} from './compiler'; +import {JitReflector} from './jit_reflector'; const _NO_RESOURCE_LOADER: ResourceLoader = { get(url: string): Promise{ @@ -44,8 +46,7 @@ const baseHtmlParser = new InjectionToken('HtmlParser'); * template compilation. */ export const COMPILER_PROVIDERS: Array|{[k: string]: any}|any[]> = [ - {provide: Reflector, useValue: reflector}, - {provide: ReflectorReader, useExisting: Reflector}, + {provide: CompileReflector, useValue: new JitReflector()}, {provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER}, JitSummaryResolver, {provide: SummaryResolver, useExisting: JitSummaryResolver}, @@ -131,10 +132,6 @@ export class JitCompilerFactory implements CompilerFactory { } } -function _initReflector() { - reflector.reflectionCapabilities = new ReflectionCapabilities(); -} - /** * A platform that included corePlatform and the compiler. * @@ -143,7 +140,6 @@ function _initReflector() { export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [ {provide: COMPILER_OPTIONS, useValue: {}, multi: true}, {provide: CompilerFactory, useClass: JitCompilerFactory}, - {provide: PLATFORM_INITIALIZER, useValue: _initReflector, multi: true}, ]); function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions { diff --git a/packages/compiler/src/jit/jit_reflector.ts b/packages/compiler/src/jit/jit_reflector.ts new file mode 100644 index 0000000000..2fd8a31c01 --- /dev/null +++ b/packages/compiler/src/jit/jit_reflector.ts @@ -0,0 +1,46 @@ +/** + * @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, ɵReflectionCapabilities as ReflectionCapabilities, ɵstringify as stringify} from '@angular/core'; + +import {CompileReflector} from '../compile_reflector'; +import * as o from '../output/output_ast'; +import {getUrlScheme} from '../url_resolver'; +import {MODULE_SUFFIX, ValueTransformer, noUndefined, syntaxError, visitValue} from '../util'; + +export class JitReflector implements CompileReflector { + private reflectionCapabilities: ReflectionCapabilities; + constructor() { this.reflectionCapabilities = new ReflectionCapabilities(); } + componentModuleUrl(type: any, cmpMetadata: Component): string { + const moduleId = cmpMetadata.moduleId; + + if (typeof moduleId === 'string') { + const scheme = getUrlScheme(moduleId); + return scheme ? moduleId : `package:${moduleId}${MODULE_SUFFIX}`; + } else if (moduleId !== null && moduleId !== void 0) { + throw syntaxError( + `moduleId should be a string in "${stringify(type)}". See https://goo.gl/wIDDiL for more information.\n` + + `If you're using Webpack you should inline the template and the styles, see https://goo.gl/X2J8zc.`); + } + + return `./${stringify(type)}`; + } + parameters(typeOrFunc: /*Type*/ any): any[][] { + return this.reflectionCapabilities.parameters(typeOrFunc); + } + annotations(typeOrFunc: /*Type*/ any): any[] { + return this.reflectionCapabilities.annotations(typeOrFunc); + } + propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]} { + return this.reflectionCapabilities.propMetadata(typeOrFunc); + } + hasLifecycleHook(type: any, lcProperty: string): boolean { + return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty); + } + resolveExternalReference(ref: o.ExternalReference): any { return ref.runtime; } +} \ No newline at end of file diff --git a/packages/compiler/src/lifecycle_reflector.ts b/packages/compiler/src/lifecycle_reflector.ts index 00decb2c51..738e699176 100644 --- a/packages/compiler/src/lifecycle_reflector.ts +++ b/packages/compiler/src/lifecycle_reflector.ts @@ -6,30 +6,51 @@ * found in the LICENSE file at https://angular.io/license */ -import {ɵLifecycleHooks, ɵreflector} from '@angular/core'; +import {CompileReflector} from './compile_reflector'; - -export function hasLifecycleHook(hook: ɵLifecycleHooks, token: any): boolean { - return ɵreflector.hasLifecycleHook(token, getHookName(hook)); +export enum LifecycleHooks { + OnInit, + OnDestroy, + DoCheck, + OnChanges, + AfterContentInit, + AfterContentChecked, + AfterViewInit, + AfterViewChecked } -function getHookName(hook: ɵLifecycleHooks): string { +export const LIFECYCLE_HOOKS_VALUES = [ + LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges, + LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit, + LifecycleHooks.AfterViewChecked +]; + +export function hasLifecycleHook( + reflector: CompileReflector, hook: LifecycleHooks, token: any): boolean { + return reflector.hasLifecycleHook(token, getHookName(hook)); +} + +export function getAllLifecycleHooks(reflector: CompileReflector, token: any): LifecycleHooks[] { + return LIFECYCLE_HOOKS_VALUES.filter(hook => hasLifecycleHook(reflector, hook, token)); +} + +function getHookName(hook: LifecycleHooks): string { switch (hook) { - case ɵLifecycleHooks.OnInit: + case LifecycleHooks.OnInit: return 'ngOnInit'; - case ɵLifecycleHooks.OnDestroy: + case LifecycleHooks.OnDestroy: return 'ngOnDestroy'; - case ɵLifecycleHooks.DoCheck: + case LifecycleHooks.DoCheck: return 'ngDoCheck'; - case ɵLifecycleHooks.OnChanges: + case LifecycleHooks.OnChanges: return 'ngOnChanges'; - case ɵLifecycleHooks.AfterContentInit: + case LifecycleHooks.AfterContentInit: return 'ngAfterContentInit'; - case ɵLifecycleHooks.AfterContentChecked: + case LifecycleHooks.AfterContentChecked: return 'ngAfterContentChecked'; - case ɵLifecycleHooks.AfterViewInit: + case LifecycleHooks.AfterViewInit: return 'ngAfterViewInit'; - case ɵLifecycleHooks.AfterViewChecked: + case LifecycleHooks.AfterViewChecked: return 'ngAfterViewChecked'; } } diff --git a/packages/compiler/src/metadata_resolver.ts b/packages/compiler/src/metadata_resolver.ts index b308d64126..b5f05651e2 100644 --- a/packages/compiler/src/metadata_resolver.ts +++ b/packages/compiler/src/metadata_resolver.ts @@ -6,18 +6,19 @@ * found in the LICENSE file at https://angular.io/license */ -import {Attribute, ChangeDetectionStrategy, Component, ComponentFactory, Directive, Host, Inject, Injectable, InjectionToken, ModuleWithProviders, Optional, Provider, Query, RendererType2, SchemaMetadata, Self, SkipSelf, Type, resolveForwardRef, ɵConsole as Console, ɵERROR_COMPONENT_TYPE, ɵLIFECYCLE_HOOKS_VALUES, ɵReflectorReader, ɵccf as createComponentFactory, ɵreflector, ɵstringify as stringify} from '@angular/core'; +import {Attribute, ChangeDetectionStrategy, Component, ComponentFactory, Directive, Host, Inject, Injectable, InjectionToken, ModuleWithProviders, Optional, Provider, Query, RendererType2, SchemaMetadata, Self, SkipSelf, Type, resolveForwardRef, ɵConsole as Console, ɵERROR_COMPONENT_TYPE, ɵccf as createComponentFactory, ɵstringify as stringify} from '@angular/core'; import {StaticSymbol, StaticSymbolCache} from './aot/static_symbol'; import {ngfactoryFilePath} from './aot/util'; import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions'; import * as cpl from './compile_metadata'; +import {CompileReflector} from './compile_reflector'; import {CompilerConfig} from './config'; import {DirectiveNormalizer} from './directive_normalizer'; import {DirectiveResolver} from './directive_resolver'; -import {Identifiers, resolveIdentifier} from './identifiers'; +import {Identifiers} from './identifiers'; import {CompilerInjectable} from './injectable'; -import {hasLifecycleHook} from './lifecycle_reflector'; +import {getAllLifecycleHooks} from './lifecycle_reflector'; import {NgModuleResolver} from './ng_module_resolver'; import {PipeResolver} from './pipe_resolver'; import {ElementSchemaRegistry} from './schema/element_schema_registry'; @@ -52,9 +53,11 @@ export class CompileMetadataResolver { private _schemaRegistry: ElementSchemaRegistry, private _directiveNormalizer: DirectiveNormalizer, private _console: Console, @Optional() private _staticSymbolCache: StaticSymbolCache, - private _reflector: ɵReflectorReader = ɵreflector, + private _reflector: CompileReflector, @Optional() @Inject(ERROR_COLLECTOR_TOKEN) private _errorCollector?: ErrorCollector) {} + getReflector(): CompileReflector { return this._reflector; } + clearCacheFor(type: Type) { const dirMeta = this._directiveCache.get(type); this._directiveCache.delete(type); @@ -210,7 +213,7 @@ export class CompileMetadataResolver { const templateMeta = this._directiveNormalizer.normalizeTemplate({ ngModuleType, componentType: directiveType, - moduleUrl: componentModuleUrl(this._reflector, directiveType, annotation), + moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation), encapsulation: template.encapsulation, template: template.template, templateUrl: template.templateUrl, @@ -721,8 +724,7 @@ export class CompileMetadataResolver { return { reference: identifier.reference, diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps), - lifecycleHooks: - ɵLIFECYCLE_HOOKS_VALUES.filter(hook => hasLifecycleHook(hook, identifier.reference)), + lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference), }; } @@ -900,7 +902,8 @@ export class CompileMetadataResolver { type); return; } - if (providerMeta.token === resolveIdentifier(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) { + if (providerMeta.token === + this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) { targetEntryComponents.push(...this._getEntryComponentsFromProvider(providerMeta, type)); } else { compileProviders.push(this.getProviderMetadata(providerMeta)); @@ -1078,26 +1081,6 @@ function isValidType(value: any): boolean { return (value instanceof StaticSymbol) || (value instanceof Type); } -export function componentModuleUrl( - reflector: ɵReflectorReader, type: Type, cmpMetadata: Component): string { - if (type instanceof StaticSymbol) { - return reflector.resourceUri(type); - } - - const moduleId = cmpMetadata.moduleId; - - if (typeof moduleId === 'string') { - const scheme = getUrlScheme(moduleId); - return scheme ? moduleId : `package:${moduleId}${MODULE_SUFFIX}`; - } else if (moduleId !== null && moduleId !== void 0) { - throw syntaxError( - `moduleId should be a string in "${stringifyType(type)}". See https://goo.gl/wIDDiL for more information.\n` + - `If you're using Webpack you should inline the template and the styles, see https://goo.gl/X2J8zc.`); - } - - return reflector.importUri(type) !; -} - function extractIdentifiers(value: any, targetIdentifiers: cpl.CompileIdentifierMetadata[]) { visitValue(value, new _CompileValueConverter(), targetIdentifiers); } diff --git a/packages/compiler/src/ng_module_compiler.ts b/packages/compiler/src/ng_module_compiler.ts index ad787efb1c..3f9f7ae1ce 100644 --- a/packages/compiler/src/ng_module_compiler.ts +++ b/packages/compiler/src/ng_module_compiler.ts @@ -9,7 +9,8 @@ import {ɵNodeFlags as NodeFlags} from '@angular/core'; import {CompileNgModuleMetadata, CompileProviderMetadata, identifierName} from './compile_metadata'; -import {Identifiers, createIdentifier} from './identifiers'; +import {CompileReflector} from './compile_reflector'; +import {Identifiers} from './identifiers'; import {CompilerInjectable} from './injectable'; import * as o from './output/output_ast'; import {typeSourceSpan} from './parse_util'; @@ -25,15 +26,18 @@ const LOG_VAR = o.variable('_l'); @CompilerInjectable() export class NgModuleCompiler { + constructor(private reflector: CompileReflector) {} compile( ctx: OutputContext, ngModuleMeta: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[]): NgModuleCompileResult { const sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type); const entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents; const bootstrapComponents = ngModuleMeta.bootstrapComponents; - const providerParser = new NgModuleProviderAnalyzer(ngModuleMeta, extraProviders, sourceSpan); + const providerParser = + new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan); const providerDefs = - [componentFactoryResolverProviderDef(ctx, NodeFlags.None, entryComponentFactories)] + [componentFactoryResolverProviderDef( + this.reflector, ctx, NodeFlags.None, entryComponentFactories)] .concat(providerParser.parse().map((provider) => providerDef(ctx, provider))) .map(({providerExpr, depsExpr, flags, tokenExpr}) => { return o.importExpr(Identifiers.moduleProviderDef).callFn([ diff --git a/packages/compiler/src/ng_module_resolver.ts b/packages/compiler/src/ng_module_resolver.ts index 5c820f606d..59472eeaf7 100644 --- a/packages/compiler/src/ng_module_resolver.ts +++ b/packages/compiler/src/ng_module_resolver.ts @@ -6,7 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ -import {NgModule, Type, ɵReflectorReader, ɵreflector, ɵstringify as stringify} from '@angular/core'; +import {NgModule, Type, ɵstringify as stringify} from '@angular/core'; + +import {CompileReflector} from './compile_reflector'; import {findLast} from './directive_resolver'; import {CompilerInjectable} from './injectable'; @@ -19,7 +21,7 @@ function _isNgModuleMetadata(obj: any): obj is NgModule { */ @CompilerInjectable() export class NgModuleResolver { - constructor(private _reflector: ɵReflectorReader = ɵreflector) {} + constructor(private _reflector: CompileReflector) {} isNgModule(type: any) { return this._reflector.annotations(type).some(_isNgModuleMetadata); } diff --git a/packages/compiler/src/pipe_resolver.ts b/packages/compiler/src/pipe_resolver.ts index a9f17cae09..a7f36ee129 100644 --- a/packages/compiler/src/pipe_resolver.ts +++ b/packages/compiler/src/pipe_resolver.ts @@ -6,7 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ -import {Pipe, Type, resolveForwardRef, ɵReflectorReader, ɵreflector, ɵstringify as stringify} from '@angular/core'; +import {Pipe, Type, resolveForwardRef, ɵstringify as stringify} from '@angular/core'; + +import {CompileReflector} from './compile_reflector'; import {findLast} from './directive_resolver'; import {CompilerInjectable} from './injectable'; @@ -23,7 +25,7 @@ function _isPipeMetadata(type: any): boolean { */ @CompilerInjectable() export class PipeResolver { - constructor(private _reflector: ɵReflectorReader = ɵreflector) {} + constructor(private _reflector: CompileReflector) {} isPipe(type: Type) { const typeMetadata = this._reflector.annotations(resolveForwardRef(type)); diff --git a/packages/compiler/src/provider_analyzer.ts b/packages/compiler/src/provider_analyzer.ts index 067fda08f3..f3a1ca4d26 100644 --- a/packages/compiler/src/provider_analyzer.ts +++ b/packages/compiler/src/provider_analyzer.ts @@ -8,7 +8,8 @@ import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata, tokenName, tokenReference} from './compile_metadata'; -import {Identifiers, createIdentifierToken, resolveIdentifier} from './identifiers'; +import {CompileReflector} from './compile_reflector'; +import {Identifiers, createTokenForExternalReference} from './identifiers'; import {ParseError, ParseSourceSpan} from './parse_util'; import {AttrAst, DirectiveAst, ProviderAst, ProviderAstType, QueryMatch, ReferenceAst} from './template_parser/template_ast'; @@ -32,7 +33,7 @@ export class ProviderViewContext { viewProviders: Map; errors: ProviderError[] = []; - constructor(public component: CompileDirectiveMetadata) { + constructor(public reflector: CompileReflector, public component: CompileDirectiveMetadata) { this.viewQueries = _getViewQueries(component); this.viewProviders = new Map(); component.viewProviders.forEach((provider) => { @@ -68,14 +69,17 @@ export class ProviderElementContext { this._addQueryReadsTo(provider.token, provider.token, this._queriedTokens); }); if (isTemplate) { - const templateRefId = createIdentifierToken(Identifiers.TemplateRef); + const templateRefId = + createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef); this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens); } refs.forEach((refAst) => { - let defaultQueryValue = refAst.value || createIdentifierToken(Identifiers.ElementRef); + let defaultQueryValue = refAst.value || + createTokenForExternalReference(this.viewContext.reflector, Identifiers.ElementRef); this._addQueryReadsTo({value: refAst.name}, defaultQueryValue, this._queriedTokens); }); - if (this._queriedTokens.get(resolveIdentifier(Identifiers.ViewContainerRef))) { + if (this._queriedTokens.get( + this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) { this._hasViewContainer = true; } @@ -232,18 +236,25 @@ export class ProviderElementContext { // access builtints if ((requestingProviderType === ProviderAstType.Directive || requestingProviderType === ProviderAstType.Component)) { - if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Renderer) || - tokenReference(dep.token) === resolveIdentifier(Identifiers.ElementRef) || - tokenReference(dep.token) === resolveIdentifier(Identifiers.ChangeDetectorRef) || - tokenReference(dep.token) === resolveIdentifier(Identifiers.TemplateRef)) { + if (tokenReference(dep.token) === + this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) || + tokenReference(dep.token) === + this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) || + tokenReference(dep.token) === + this.viewContext.reflector.resolveExternalReference( + Identifiers.ChangeDetectorRef) || + tokenReference(dep.token) === + this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) { return dep; } - if (tokenReference(dep.token) === resolveIdentifier(Identifiers.ViewContainerRef)) { + if (tokenReference(dep.token) === + this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) { this._hasViewContainer = true; } } // access the injector - if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Injector)) { + if (tokenReference(dep.token) === + this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) { return dep; } // access providers @@ -304,8 +315,8 @@ export class NgModuleProviderAnalyzer { private _errors: ProviderError[] = []; constructor( - ngModule: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[], - sourceSpan: ParseSourceSpan) { + private reflector: CompileReflector, ngModule: CompileNgModuleMetadata, + extraProviders: CompileProviderMetadata[], sourceSpan: ParseSourceSpan) { this._allProviders = new Map(); ngModule.transitiveModule.modules.forEach((ngModuleType: CompileTypeMetadata) => { const ngModuleProvider = {token: {identifier: ngModuleType}, useClass: ngModuleType}; @@ -395,8 +406,10 @@ export class NgModuleProviderAnalyzer { let foundLocal = false; if (!dep.isSkipSelf && dep.token != null) { // access the injector - if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Injector) || - tokenReference(dep.token) === resolveIdentifier(Identifiers.ComponentFactoryResolver)) { + if (tokenReference(dep.token) === + this.reflector.resolveExternalReference(Identifiers.Injector) || + tokenReference(dep.token) === + this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) { foundLocal = true; // access providers } else if (this._getOrCreateLocalProvider(dep.token, eager) != null) { diff --git a/packages/compiler/src/template_parser/template_ast.ts b/packages/compiler/src/template_parser/template_ast.ts index 6d3b80e215..f0710f7a13 100644 --- a/packages/compiler/src/template_parser/template_ast.ts +++ b/packages/compiler/src/template_parser/template_ast.ts @@ -6,14 +6,16 @@ * found in the LICENSE file at https://angular.io/license */ -import {SecurityContext, ɵLifecycleHooks as LifecycleHooks} from '@angular/core'; +import {SecurityContext} from '@angular/core'; import {AstPath} from '../ast_path'; import {CompileDirectiveSummary, CompileProviderMetadata, CompileTokenMetadata} from '../compile_metadata'; import {AST} from '../expression_parser/ast'; +import {LifecycleHooks} from '../lifecycle_reflector'; import {ParseSourceSpan} from '../parse_util'; + /** * An Abstract Syntax Tree node representing part of a parsed Angular template. */ diff --git a/packages/compiler/src/template_parser/template_parser.ts b/packages/compiler/src/template_parser/template_parser.ts index 6a7f86c266..a6a7559e1c 100644 --- a/packages/compiler/src/template_parser/template_parser.ts +++ b/packages/compiler/src/template_parser/template_parser.ts @@ -9,11 +9,12 @@ import {Inject, InjectionToken, Optional, SchemaMetadata, ɵConsole as Console} from '@angular/core'; import {CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeSummary, CompileTokenMetadata, CompileTypeMetadata, identifierName} from '../compile_metadata'; +import {CompileReflector} from '../compile_reflector'; import {CompilerConfig} from '../config'; import {AST, ASTWithSource, EmptyExpr} from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; import {I18NHtmlParser} from '../i18n/i18n_html_parser'; -import {Identifiers, createIdentifierToken, identifierToken} from '../identifiers'; +import {Identifiers, createTokenForExternalReference, createTokenForReference} from '../identifiers'; import {CompilerInjectable} from '../injectable'; import * as html from '../ml_parser/ast'; import {ParseTreeResult} from '../ml_parser/html_parser'; @@ -105,9 +106,9 @@ export class TemplateParseResult { @CompilerInjectable() export class TemplateParser { constructor( - private _config: CompilerConfig, private _exprParser: Parser, - private _schemaRegistry: ElementSchemaRegistry, private _htmlParser: I18NHtmlParser, - private _console: Console, + private _config: CompilerConfig, private _reflector: CompileReflector, + private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, + private _htmlParser: I18NHtmlParser, private _console: Console, @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} parse( @@ -154,7 +155,7 @@ export class TemplateParser { if (htmlAstWithErrors.rootNodes.length > 0) { const uniqDirectives = removeSummaryDuplicates(directives); const uniqPipes = removeSummaryDuplicates(pipes); - const providerViewContext = new ProviderViewContext(component); + const providerViewContext = new ProviderViewContext(this._reflector, component); let interpolationConfig: InterpolationConfig = undefined !; if (component.template && component.template.interpolation) { interpolationConfig = { @@ -165,8 +166,8 @@ export class TemplateParser { const bindingParser = new BindingParser( this._exprParser, interpolationConfig !, this._schemaRegistry, uniqPipes, errors); const parseVisitor = new TemplateParseVisitor( - this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, - schemas, errors); + this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, + this._schemaRegistry, schemas, errors); result = html.visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push(...providerViewContext.errors); usedPipes.push(...bindingParser.getUsedPipes()); @@ -233,10 +234,10 @@ class TemplateParseVisitor implements html.Visitor { contentQueryStartId: number; constructor( - private config: CompilerConfig, public providerViewContext: ProviderViewContext, - directives: CompileDirectiveSummary[], private _bindingParser: BindingParser, - private _schemaRegistry: ElementSchemaRegistry, private _schemas: SchemaMetadata[], - private _targetErrors: TemplateParseError[]) { + private reflector: CompileReflector, private config: CompilerConfig, + public providerViewContext: ProviderViewContext, directives: CompileDirectiveSummary[], + private _bindingParser: BindingParser, private _schemaRegistry: ElementSchemaRegistry, + private _schemas: SchemaMetadata[], private _targetErrors: TemplateParseError[]) { // Note: queries start with id 1 so we can use the number in a Bloom filter! this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1; directives.forEach((directive, index) => { @@ -574,7 +575,8 @@ class TemplateParseVisitor implements html.Visitor { if ((elOrDirRef.value.length === 0 && directive.isComponent) || (directive.exportAs == elOrDirRef.value)) { targetReferences.push(new ReferenceAst( - elOrDirRef.name, identifierToken(directive.type), elOrDirRef.sourceSpan)); + elOrDirRef.name, createTokenForReference(directive.type.reference), + elOrDirRef.sourceSpan)); matchedReferences.add(elOrDirRef.name); } }); @@ -595,7 +597,7 @@ class TemplateParseVisitor implements html.Visitor { } else if (!component) { let refToken: CompileTokenMetadata = null !; if (isTemplateElement) { - refToken = createIdentifierToken(Identifiers.TemplateRef); + refToken = createTokenForExternalReference(this.reflector, Identifiers.TemplateRef); } targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.sourceSpan)); } diff --git a/packages/compiler/src/view_compiler/provider_compiler.ts b/packages/compiler/src/view_compiler/provider_compiler.ts index cc821ec742..e99578b712 100644 --- a/packages/compiler/src/view_compiler/provider_compiler.ts +++ b/packages/compiler/src/view_compiler/provider_compiler.ts @@ -6,10 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {ɵDepFlags as DepFlags, ɵLifecycleHooks as LifecycleHooks, ɵNodeFlags as NodeFlags} from '@angular/core'; +import {ɵDepFlags as DepFlags, ɵNodeFlags as NodeFlags} from '@angular/core'; import {CompileDiDependencyMetadata, CompileEntryComponentMetadata, CompileProviderMetadata, CompileTokenMetadata} from '../compile_metadata'; -import {Identifiers, createIdentifier, createIdentifierToken, resolveIdentifier} from '../identifiers'; +import {CompileReflector} from '../compile_reflector'; +import {Identifiers, createTokenForExternalReference} from '../identifiers'; +import {LifecycleHooks} from '../lifecycle_reflector'; import * as o from '../output/output_ast'; import {convertValueToOutputAst} from '../output/value_util'; import {ProviderAst, ProviderAstType} from '../template_parser/template_ast'; @@ -172,7 +174,8 @@ export function lifecycleHookToNodeFlag(lifecycleHook: LifecycleHooks): NodeFlag } export function componentFactoryResolverProviderDef( - ctx: OutputContext, flags: NodeFlags, entryComponents: CompileEntryComponentMetadata[]): { + reflector: CompileReflector, ctx: OutputContext, flags: NodeFlags, + entryComponents: CompileEntryComponentMetadata[]): { providerExpr: o.Expression, flags: NodeFlags, depsExpr: o.Expression, @@ -180,15 +183,15 @@ export function componentFactoryResolverProviderDef( } { const entryComponentFactories = entryComponents.map((entryComponent) => ctx.importExpr(entryComponent.componentFactory)); - const token = createIdentifierToken(Identifiers.ComponentFactoryResolver); + const token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver); const classMeta = { diDeps: [ {isValue: true, value: o.literalArr(entryComponentFactories)}, {token: token, isSkipSelf: true, isOptional: true}, - {token: createIdentifierToken(Identifiers.NgModuleRef)}, + {token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef)}, ], lifecycleHooks: [], - reference: resolveIdentifier(Identifiers.CodegenComponentFactoryResolver) + reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver) }; const {providerExpr, flags: providerFlags, depsExpr} = singleProviderDef(ctx, flags, ProviderAstType.PrivateService, { diff --git a/packages/compiler/src/view_compiler/view_compiler.ts b/packages/compiler/src/view_compiler/view_compiler.ts index 5701204806..c95985e014 100644 --- a/packages/compiler/src/view_compiler/view_compiler.ts +++ b/packages/compiler/src/view_compiler/view_compiler.ts @@ -6,14 +6,16 @@ * found in the LICENSE file at https://angular.io/license */ -import {ChangeDetectionStrategy, ɵArgumentType as ArgumentType, ɵBindingFlags as BindingFlags, ɵDepFlags as DepFlags, ɵLifecycleHooks as LifecycleHooks, ɵNodeFlags as NodeFlags, ɵQueryBindingType as QueryBindingType, ɵQueryValueType as QueryValueType, ɵViewFlags as ViewFlags, ɵelementEventFullName as elementEventFullName} from '@angular/core'; +import {ChangeDetectionStrategy, ɵArgumentType as ArgumentType, ɵBindingFlags as BindingFlags, ɵDepFlags as DepFlags, ɵNodeFlags as NodeFlags, ɵQueryBindingType as QueryBindingType, ɵQueryValueType as QueryValueType, ɵViewFlags as ViewFlags, ɵelementEventFullName as elementEventFullName} from '@angular/core'; import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompilePipeSummary, CompileProviderMetadata, CompileTokenMetadata, CompileTypeMetadata, rendererTypeName, tokenReference, viewClassName} from '../compile_metadata'; +import {CompileReflector} from '../compile_reflector'; import {BuiltinConverter, EventHandlerVars, LocalResolver, convertActionBinding, convertPropertyBinding, convertPropertyBindingBuiltins} from '../compiler_util/expression_converter'; import {CompilerConfig} from '../config'; import {AST, ASTWithSource, Interpolation} from '../expression_parser/ast'; -import {Identifiers, createIdentifier, createIdentifierToken, resolveIdentifier} from '../identifiers'; +import {Identifiers} from '../identifiers'; import {CompilerInjectable} from '../injectable'; +import {LifecycleHooks} from '../lifecycle_reflector'; import {isNgContainer} from '../ml_parser/tags'; import * as o from '../output/output_ast'; import {convertValueToOutputAst} from '../output/value_util'; @@ -36,7 +38,8 @@ export class ViewCompileResult { @CompilerInjectable() export class ViewCompiler { constructor( - private _genConfigNext: CompilerConfig, private _schemaRegistry: ElementSchemaRegistry) {} + private _config: CompilerConfig, private _reflector: CompileReflector, + private _schemaRegistry: ElementSchemaRegistry) {} compileComponent( outputCtx: OutputContext, component: CompileDirectiveMetadata, template: TemplateAst[], @@ -70,8 +73,8 @@ export class ViewCompiler { const viewBuilderFactory = (parent: ViewBuilder | null): ViewBuilder => { const embeddedViewIndex = embeddedViewCount++; return new ViewBuilder( - outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, - viewBuilderFactory); + this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, + staticQueryIds, viewBuilderFactory); }; const visitor = viewBuilderFactory(null); @@ -116,9 +119,9 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver { private children: ViewBuilder[] = []; constructor( - private outputCtx: OutputContext, private parent: ViewBuilder|null, - private component: CompileDirectiveMetadata, private embeddedViewIndex: number, - private usedPipes: CompilePipeSummary[], + private reflector: CompileReflector, private outputCtx: OutputContext, + private parent: ViewBuilder|null, private component: CompileDirectiveMetadata, + private embeddedViewIndex: number, private usedPipes: CompilePipeSummary[], private staticQueryIds: Map, private viewBuilderFactory: ViewBuilderFactory) { // TODO(tbosch): The old view compiler used to use an `any` type @@ -436,11 +439,16 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver { let queryMatchExprs: o.Expression[] = []; ast.queryMatches.forEach((match) => { let valueType: QueryValueType = undefined !; - if (tokenReference(match.value) === resolveIdentifier(Identifiers.ElementRef)) { + if (tokenReference(match.value) === + this.reflector.resolveExternalReference(Identifiers.ElementRef)) { valueType = QueryValueType.ElementRef; - } else if (tokenReference(match.value) === resolveIdentifier(Identifiers.ViewContainerRef)) { + } else if ( + tokenReference(match.value) === + this.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) { valueType = QueryValueType.ViewContainerRef; - } else if (tokenReference(match.value) === resolveIdentifier(Identifiers.TemplateRef)) { + } else if ( + tokenReference(match.value) === + this.reflector.resolveExternalReference(Identifiers.TemplateRef)) { valueType = QueryValueType.TemplateRef; } if (valueType != null) { @@ -451,7 +459,9 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver { let valueType: QueryValueType = undefined !; if (!ref.value) { valueType = QueryValueType.RenderElement; - } else if (tokenReference(ref.value) === resolveIdentifier(Identifiers.TemplateRef)) { + } else if ( + tokenReference(ref.value) === + this.reflector.resolveExternalReference(Identifiers.TemplateRef)) { valueType = QueryValueType.TemplateRef; } if (valueType != null) { @@ -590,7 +600,8 @@ class ViewBuilder implements TemplateAstVisitor, LocalResolver { const componentDirMeta = directives.find(dirAst => dirAst.directive.isComponent); if (componentDirMeta && componentDirMeta.directive.entryComponents.length) { const {providerExpr, depsExpr, flags, tokenExpr} = componentFactoryResolverProviderDef( - this.outputCtx, NodeFlags.PrivateProvider, componentDirMeta.directive.entryComponents); + this.reflector, this.outputCtx, NodeFlags.PrivateProvider, + componentDirMeta.directive.entryComponents); this._addProviderNode({ providerExpr, depsExpr, diff --git a/packages/compiler/test/aot/test_util.ts b/packages/compiler/test/aot/test_util.ts index d51c05efc9..3bfd29620d 100644 --- a/packages/compiler/test/aot/test_util.ts +++ b/packages/compiler/test/aot/test_util.ts @@ -7,7 +7,6 @@ */ import {AotCompilerHost, AotCompilerOptions, GeneratedFile, createAotCompiler, toTypeScript} from '@angular/compiler'; -import {ɵReflectionCapabilities as ReflectionCapabilities, ɵreflector as reflector} from '@angular/core'; import {MetadataBundlerHost, MetadataCollector, ModuleMetadata} from '@angular/tsc-wrapped'; import * as fs from 'fs'; import * as path from 'path'; @@ -537,8 +536,6 @@ export function setup(options: {compileAngular: boolean} = { emittingHost.writtenAngularFiles(angularFiles); } }); - // Restore reflector since AoT compiler will update it with a new static reflector - afterEach(() => { reflector.updateCapabilities(new ReflectionCapabilities()); }); return angularFiles; } diff --git a/packages/compiler/test/directive_lifecycle_spec.ts b/packages/compiler/test/directive_lifecycle_spec.ts index 65354c0e91..a4b35f4bf3 100644 --- a/packages/compiler/test/directive_lifecycle_spec.ts +++ b/packages/compiler/test/directive_lifecycle_spec.ts @@ -6,9 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {hasLifecycleHook} from '@angular/compiler/src/lifecycle_reflector'; +import {JitReflector} from '@angular/compiler'; +import {LifecycleHooks as Hooks, hasLifecycleHook as hasLifecycleHookImpl} from '@angular/compiler/src/lifecycle_reflector'; import {SimpleChanges} from '@angular/core'; -import {LifecycleHooks as Hooks} from '@angular/core/src/metadata/lifecycle_hooks'; + +function hasLifecycleHook(hook: Hooks, directive: any): boolean { + return hasLifecycleHookImpl(new JitReflector(), hook, directive); +} export function main() { describe('Create Directive', () => { diff --git a/packages/compiler/test/directive_resolver_mock_spec.ts b/packages/compiler/test/directive_resolver_mock_spec.ts index e74d4e06ca..926bbc018c 100644 --- a/packages/compiler/test/directive_resolver_mock_spec.ts +++ b/packages/compiler/test/directive_resolver_mock_spec.ts @@ -6,8 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ +import {JitReflector} from '@angular/compiler'; import {Component, Directive, Injector, ɵViewMetadata as ViewMetadata} from '@angular/core'; import {TestBed, inject} from '@angular/core/testing'; + import {MockDirectiveResolver} from '../testing'; export function main() { @@ -20,7 +22,7 @@ export function main() { }); beforeEach(inject([Injector], (injector: Injector) => { - dirResolver = new MockDirectiveResolver(injector); + dirResolver = new MockDirectiveResolver(injector, new JitReflector()); })); describe('Directive overriding', () => { diff --git a/packages/compiler/test/directive_resolver_spec.ts b/packages/compiler/test/directive_resolver_spec.ts index 804bee7fa6..b80b65b79f 100644 --- a/packages/compiler/test/directive_resolver_spec.ts +++ b/packages/compiler/test/directive_resolver_spec.ts @@ -6,9 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ +import {JitReflector} from '@angular/compiler'; import {DirectiveResolver} from '@angular/compiler/src/directive_resolver'; import {Component, ContentChild, ContentChildren, Directive, HostBinding, HostListener, Input, Output, ViewChild, ViewChildren} from '@angular/core/src/metadata'; -import {reflector} from '@angular/core/src/reflection/reflection'; @Directive({selector: 'someDirective'}) class SomeDirective { @@ -110,7 +110,7 @@ export function main() { describe('DirectiveResolver', () => { let resolver: DirectiveResolver; - beforeEach(() => { resolver = new DirectiveResolver(); }); + beforeEach(() => { resolver = new DirectiveResolver(new JitReflector()); }); it('should read out the Directive metadata', () => { const directiveMetadata = resolver.resolve(SomeDirective); diff --git a/packages/compiler/test/metadata_resolver_spec.ts b/packages/compiler/test/metadata_resolver_spec.ts index 8a540c25fa..9c16f77099 100644 --- a/packages/compiler/test/metadata_resolver_spec.ts +++ b/packages/compiler/test/metadata_resolver_spec.ts @@ -6,14 +6,16 @@ * found in the LICENSE file at https://angular.io/license */ +import {LIFECYCLE_HOOKS_VALUES, LifecycleHooks} from '@angular/compiler/src/lifecycle_reflector'; import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/testing/src/test_bindings'; import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, Directive, DoCheck, Injectable, NgModule, OnChanges, OnDestroy, OnInit, Pipe, SimpleChanges, ViewEncapsulation, ɵstringify as stringify} from '@angular/core'; -import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks'; import {TestBed, async, inject} from '@angular/core/testing'; + import {identifierName} from '../src/compile_metadata'; import {CompileMetadataResolver} from '../src/metadata_resolver'; import {ResourceLoader} from '../src/resource_loader'; import {MockResourceLoader} from '../testing/src/resource_loader_mock'; + import {MalformedStylesComponent} from './metadata_resolver_fixture'; export function main() { diff --git a/packages/compiler/test/ng_module_resolver_mock_spec.ts b/packages/compiler/test/ng_module_resolver_mock_spec.ts index a0131eb350..81ebf312c2 100644 --- a/packages/compiler/test/ng_module_resolver_mock_spec.ts +++ b/packages/compiler/test/ng_module_resolver_mock_spec.ts @@ -6,8 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ +import {JitReflector} from '@angular/compiler'; import {Injector, NgModule} from '@angular/core'; import {beforeEach, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal'; + import {MockNgModuleResolver} from '../testing'; export function main() { @@ -15,7 +17,7 @@ export function main() { let ngModuleResolver: MockNgModuleResolver; beforeEach(inject([Injector], (injector: Injector) => { - ngModuleResolver = new MockNgModuleResolver(injector); + ngModuleResolver = new MockNgModuleResolver(injector, new JitReflector()); })); describe('NgModule overriding', () => { diff --git a/packages/compiler/test/ng_module_resolver_spec.ts b/packages/compiler/test/ng_module_resolver_spec.ts index c9a67ea959..91d6a466cd 100644 --- a/packages/compiler/test/ng_module_resolver_spec.ts +++ b/packages/compiler/test/ng_module_resolver_spec.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ +import {JitReflector} from '@angular/compiler'; import {NgModuleResolver} from '@angular/compiler/src/ng_module_resolver'; import {ɵstringify as stringify} from '@angular/core'; import {NgModule} from '@angular/core/src/metadata'; @@ -32,7 +33,7 @@ export function main() { describe('NgModuleResolver', () => { let resolver: NgModuleResolver; - beforeEach(() => { resolver = new NgModuleResolver(); }); + beforeEach(() => { resolver = new NgModuleResolver(new JitReflector()); }); it('should read out the metadata from the class', () => { const moduleMetadata = resolver.resolve(SomeModule); diff --git a/packages/compiler/test/pipe_resolver_mock_spec.ts b/packages/compiler/test/pipe_resolver_mock_spec.ts index 141afb2285..d52b1b494b 100644 --- a/packages/compiler/test/pipe_resolver_mock_spec.ts +++ b/packages/compiler/test/pipe_resolver_mock_spec.ts @@ -6,16 +6,19 @@ * found in the LICENSE file at https://angular.io/license */ +import {JitReflector} from '@angular/compiler'; import {Injector, Pipe} from '@angular/core'; -import {beforeEach, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal'; +import {inject} from '@angular/core/testing'; + import {MockPipeResolver} from '../testing'; export function main() { describe('MockPipeResolver', () => { let pipeResolver: MockPipeResolver; - beforeEach(inject( - [Injector], (injector: Injector) => { pipeResolver = new MockPipeResolver(injector); })); + beforeEach(inject([Injector], (injector: Injector) => { + pipeResolver = new MockPipeResolver(injector, new JitReflector()); + })); describe('Pipe overriding', () => { it('should fallback to the default PipeResolver when templates are not overridden', () => { diff --git a/packages/compiler/test/pipe_resolver_spec.ts b/packages/compiler/test/pipe_resolver_spec.ts index 6b7a6b810a..2fd5cf7c23 100644 --- a/packages/compiler/test/pipe_resolver_spec.ts +++ b/packages/compiler/test/pipe_resolver_spec.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ +import {JitReflector} from '@angular/compiler'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {ɵstringify as stringify} from '@angular/core'; import {Pipe} from '@angular/core/src/metadata'; @@ -20,7 +21,7 @@ export function main() { describe('PipeResolver', () => { let resolver: PipeResolver; - beforeEach(() => { resolver = new PipeResolver(); }); + beforeEach(() => { resolver = new PipeResolver(new JitReflector()); }); it('should read out the metadata from the class', () => { const moduleMetadata = resolver.resolve(SomePipe); diff --git a/packages/compiler/test/template_parser/template_parser_spec.ts b/packages/compiler/test/template_parser/template_parser_spec.ts index 2d031bbb1a..c0a2fe8335 100644 --- a/packages/compiler/test/template_parser/template_parser_spec.ts +++ b/packages/compiler/test/template_parser/template_parser_spec.ts @@ -5,7 +5,7 @@ * 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 {CompileQueryMetadata, CompilerConfig, ProxyClass, StaticSymbol} from '@angular/compiler'; +import {CompileQueryMetadata, CompilerConfig, JitReflector, ProxyClass, StaticSymbol} from '@angular/compiler'; import {CompileAnimationEntryMetadata, CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeMetadata, CompilePipeSummary, CompileProviderMetadata, CompileTemplateMetadata, CompileTokenMetadata, CompileTypeMetadata, tokenReference} from '@angular/compiler/src/compile_metadata'; import {DomElementSchemaRegistry} from '@angular/compiler/src/schema/dom_element_schema_registry'; import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry'; @@ -17,7 +17,7 @@ import {Console} from '@angular/core/src/console'; import {TestBed, inject} from '@angular/core/testing'; import {CompileEntryComponentMetadata, CompileStylesheetMetadata} from '../../src/compile_metadata'; -import {Identifiers, createIdentifierToken, identifierToken} from '../../src/identifiers'; +import {Identifiers, createTokenForExternalReference, createTokenForReference} from '../../src/identifiers'; import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../src/ml_parser/interpolation_config'; import {noUndefined} from '../../src/util'; import {MockSchemaRegistry} from '../../testing'; @@ -1198,7 +1198,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("', [dirA]))).toEqual([ [ElementAst, 'div'], [AttrAst, 'a', ''], - [ReferenceAst, 'a', identifierToken(dirA.type)], + [ReferenceAst, 'a', createTokenForReference(dirA.type.reference)], [DirectiveAst, dirA], ]); }); @@ -1244,7 +1244,7 @@ Reference "#a" is defined several times ("
]#a>
expect(humanizeTplAst(parse('
', [dirA]))).toEqual([ [ElementAst, 'div'], [AttrAst, 'a', ''], - [ReferenceAst, 'a', identifierToken(dirA.type)], + [ReferenceAst, 'a', createTokenForReference(dirA.type.reference)], [DirectiveAst, dirA], ]); }); @@ -1262,6 +1262,10 @@ Reference "#a" is defined several times ("
]#a>
}); describe('explicit templates', () => { + let reflector: JitReflector; + + beforeEach(() => { reflector = new JitReflector(); }); + it('should create embedded templates for elements', () => { expect(humanizeTplAst(parse('', [ ]))).toEqual([[EmbeddedTemplateAst]]); @@ -1286,22 +1290,30 @@ Reference "#a" is defined several times ("
]#a>
it('should support references via #...', () => { expect(humanizeTplAst(parse('