refactor(compiler): don’t rely on global reflector (#16832)

Using the global reflector made it impossible
to compile multiple programs at the same time.
This commit is contained in:
Tobias Bosch 2017-05-18 13:46:51 -07:00 committed by Chuck Jazdzewski
parent de8d7c65f2
commit 50abca4583
52 changed files with 333 additions and 338 deletions

View File

@ -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(); });

View File

@ -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', () => {

View File

@ -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"', () => {

View File

@ -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';

View File

@ -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;

View File

@ -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;');

View File

@ -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<StaticSymbol>, 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
});
}

View File

@ -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};
}

View File

@ -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;
}

View File

@ -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<StaticSymbol, any[]>();
private propertyCache = new Map<StaticSymbol, {[key: string]: any[]}>();
private parameterCache = new Map<StaticSymbol, any[]>();
@ -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) {

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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';

View File

@ -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'); }

View File

@ -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 {

View File

@ -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<any>) {
const typeMetadata = this._reflector.annotations(resolveForwardRef(type));

View File

@ -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});

View File

@ -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));
}

View File

@ -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<string>{
@ -44,8 +46,7 @@ const baseHtmlParser = new InjectionToken('HtmlParser');
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[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 {

View File

@ -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; }
}

View File

@ -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';
}
}

View File

@ -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<any>) {
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<any>, 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);
}

View File

@ -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([

View File

@ -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); }

View File

@ -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<any>) {
const typeMetadata = this._reflector.annotations(resolveForwardRef(type));

View File

@ -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<any, boolean>;
errors: ProviderError[] = [];
constructor(public component: CompileDirectiveMetadata) {
constructor(public reflector: CompileReflector, public component: CompileDirectiveMetadata) {
this.viewQueries = _getViewQueries(component);
this.viewProviders = new Map<any, boolean>();
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<any, ProviderAst>();
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) {

View File

@ -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.
*/

View File

@ -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));
}

View File

@ -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, {

View File

@ -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<TemplateAst, StaticAndDynamicQueryIds>,
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,

View File

@ -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;
}

View File

@ -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', () => {

View File

@ -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', () => {

View File

@ -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);

View File

@ -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() {

View File

@ -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', () => {

View File

@ -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);

View File

@ -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', () => {

View File

@ -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);

View File

@ -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 ("<my-componen
expect(humanizeTplAst(parse('<div a #a="dirA"></div>', [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 ("<div #a></div><div [ERROR ->]#a></div>
expect(humanizeTplAst(parse('<div a #a></div>', [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 ("<div #a></div><div [ERROR ->]#a></div>
});
describe('explicit templates', () => {
let reflector: JitReflector;
beforeEach(() => { reflector = new JitReflector(); });
it('should create embedded templates for <ng-template> elements', () => {
expect(humanizeTplAst(parse('<template></template>', [
]))).toEqual([[EmbeddedTemplateAst]]);
@ -1286,22 +1290,30 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
it('should support references via #...', () => {
expect(humanizeTplAst(parse('<template #a>', []))).toEqual([
[EmbeddedTemplateAst],
[ReferenceAst, 'a', createIdentifierToken(Identifiers.TemplateRef)],
[
ReferenceAst, 'a', createTokenForExternalReference(reflector, Identifiers.TemplateRef)
],
]);
expect(humanizeTplAst(parse('<ng-template #a>', []))).toEqual([
[EmbeddedTemplateAst],
[ReferenceAst, 'a', createIdentifierToken(Identifiers.TemplateRef)],
[
ReferenceAst, 'a', createTokenForExternalReference(reflector, Identifiers.TemplateRef)
],
]);
});
it('should support references via ref-...', () => {
expect(humanizeTplAst(parse('<template ref-a>', []))).toEqual([
[EmbeddedTemplateAst],
[ReferenceAst, 'a', createIdentifierToken(Identifiers.TemplateRef)]
[
ReferenceAst, 'a', createTokenForExternalReference(reflector, Identifiers.TemplateRef)
]
]);
expect(humanizeTplAst(parse('<ng-template ref-a>', []))).toEqual([
[EmbeddedTemplateAst],
[ReferenceAst, 'a', createIdentifierToken(Identifiers.TemplateRef)]
[
ReferenceAst, 'a', createTokenForExternalReference(reflector, Identifiers.TemplateRef)
]
]);
});

View File

@ -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 {DirectiveResolver} from '@angular/compiler';
import {CompileReflector, DirectiveResolver} from '@angular/compiler';
import {Compiler, Component, Directive, Injectable, Injector, Provider, Type, resolveForwardRef, ɵViewMetadata as ViewMetadata} from '@angular/core';
@ -22,7 +22,7 @@ export class MockDirectiveResolver extends DirectiveResolver {
private _views = new Map<Type<any>, ViewMetadata>();
private _inlineTemplates = new Map<Type<any>, string>();
constructor(private _injector: Injector) { super(); }
constructor(private _injector: Injector, reflector: CompileReflector) { super(reflector); }
private get _compiler(): Compiler { return this._injector.get(Compiler); }

View File

@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/
import {NgModuleResolver} from '@angular/compiler';
import {CompileReflector, NgModuleResolver} from '@angular/compiler';
import {Compiler, Injectable, Injector, NgModule, Type} from '@angular/core';
@Injectable()
export class MockNgModuleResolver extends NgModuleResolver {
private _ngModules = new Map<Type<any>, NgModule>();
constructor(private _injector: Injector) { super(); }
constructor(private _injector: Injector, reflector: CompileReflector) { super(reflector); }
/**
* Overrides the {@link NgModule} for a module.

View File

@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/
import {PipeResolver} from '@angular/compiler';
import {CompileReflector, PipeResolver} from '@angular/compiler';
import {Compiler, Injectable, Injector, Pipe, Type} from '@angular/core';
@Injectable()
export class MockPipeResolver extends PipeResolver {
private _pipes = new Map<Type<any>, Pipe>();
constructor(private _injector: Injector) { super(); }
constructor(private _injector: Injector, refector: CompileReflector) { super(refector); }
private get _compiler(): Compiler { return this._injector.get(Compiler); }

View File

@ -8,5 +8,4 @@
export {CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver} from './linker/component_factory_resolver';
export {registerModuleFactory as ɵregisterModuleFactory} from './linker/ng_module_factory_loader';
export {reflector as ɵreflector} from './reflection/reflection';
export {ArgumentType as ɵArgumentType, BindingFlags as ɵBindingFlags, DepFlags as ɵDepFlags, EMPTY_ARRAY as ɵEMPTY_ARRAY, EMPTY_MAP as ɵEMPTY_MAP, NodeFlags as ɵNodeFlags, QueryBindingType as ɵQueryBindingType, QueryValueType as ɵQueryValueType, ViewDefinition as ɵViewDefinition, ViewFlags as ɵViewFlags, anchorDef as ɵand, createComponentFactory as ɵccf, createNgModuleFactory as ɵcmf, createRendererType2 as ɵcrt, directiveDef as ɵdid, elementDef as ɵeld, elementEventFullName as ɵelementEventFullName, getComponentViewDefinitionFactory as ɵgetComponentViewDefinitionFactory, inlineInterpolate as ɵinlineInterpolate, interpolate as ɵinterpolate, moduleDef as ɵmod, moduleProvideDef as ɵmpd, ngContentDef as ɵncd, nodeValue as ɵnov, pipeDef as ɵpid, providerDef as ɵprd, pureArrayDef as ɵpad, pureObjectDef as ɵpod, purePipeDef as ɵppd, queryDef as ɵqud, textDef as ɵted, unwrapValue as ɵunv, viewDef as ɵvid} from './view/index';

View File

@ -15,12 +15,8 @@ export {Console as ɵConsole} from './console';
export {ERROR_COMPONENT_TYPE as ɵERROR_COMPONENT_TYPE} from './errors';
export {ComponentFactory as ɵComponentFactory} from './linker/component_factory';
export {CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver} from './linker/component_factory_resolver';
export {LIFECYCLE_HOOKS_VALUES as ɵLIFECYCLE_HOOKS_VALUES, LifecycleHooks as ɵLifecycleHooks} from './metadata/lifecycle_hooks';
export {ViewMetadata as ɵViewMetadata} from './metadata/view';
export {Reflector as ɵReflector, reflector as ɵreflector} from './reflection/reflection';
// We need to import this name separately from the above wildcard, because this symbol is exposed.
export {ReflectionCapabilities as ɵReflectionCapabilities} from './reflection/reflection_capabilities';
export {ReflectorReader as ɵReflectorReader} from './reflection/reflector_reader';
export {GetterFn as ɵGetterFn, MethodFn as ɵMethodFn, SetterFn as ɵSetterFn} from './reflection/types';
export {DirectRenderer as ɵDirectRenderer, RenderDebugInfo as ɵRenderDebugInfo} from './render/api';
export {global as ɵglobal, looseIdentical as ɵlooseIdentical, stringify as ɵstringify} from './util';

View File

@ -8,19 +8,6 @@
import {SimpleChange} from '../change_detection/change_detection_util';
/**
* @stable
*/
export enum LifecycleHooks {
OnInit,
OnDestroy,
DoCheck,
OnChanges,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked
}
/**
* A `changes` object whose keys are property names and
@ -29,12 +16,6 @@ export enum LifecycleHooks {
*/
export interface SimpleChanges { [propName: string]: SimpleChange; }
export const LIFECYCLE_HOOKS_VALUES = [
LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
LifecycleHooks.AfterViewChecked
];
/**
* @whatItDoes Lifecycle hook that is called when any data-bound property of a directive changes.
* @howToUse

View File

@ -11,7 +11,6 @@ import {PLATFORM_ID} from './application_tokens';
import {Console} from './console';
import {Provider} from './di';
import {Reflector, reflector} from './reflection/reflection';
import {ReflectorReader} from './reflection/reflector_reader';
import {TestabilityRegistry} from './testability/testability';
function _reflector(): Reflector {
@ -24,7 +23,6 @@ const _CORE_PLATFORM_PROVIDERS: Provider[] = [
PlatformRef_,
{provide: PlatformRef, useExisting: PlatformRef_},
{provide: Reflector, useFactory: _reflector, deps: []},
{provide: ReflectorReader, useExisting: Reflector},
TestabilityRegistry,
Console,
];

View File

@ -21,6 +21,6 @@ export interface PlatformReflectionCapabilities {
method(name: string): MethodFn;
importUri(type: Type<any>): string;
resourceUri(type: Type<any>): string;
resolveIdentifier(name: string, moduleUrl: string, members: string[]|null, runtime: any): any;
resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any;
resolveEnum(enumIdentifier: any, name: string): any;
}

View File

@ -8,7 +8,6 @@
import {Type} from '../type';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
import {ReflectorReader} from './reflector_reader';
import {GetterFn, MethodFn, SetterFn} from './types';
export {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
@ -18,8 +17,8 @@ export {GetterFn, MethodFn, SetterFn} from './types';
* Provides access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
*/
export class Reflector extends ReflectorReader {
constructor(public reflectionCapabilities: PlatformReflectionCapabilities) { super(); }
export class Reflector {
constructor(public reflectionCapabilities: PlatformReflectionCapabilities) {}
updateCapabilities(caps: PlatformReflectionCapabilities) { this.reflectionCapabilities = caps; }
@ -51,7 +50,7 @@ export class Reflector extends ReflectorReader {
resourceUri(type: any): string { return this.reflectionCapabilities.resourceUri(type); }
resolveIdentifier(name: string, moduleUrl: string, members: string[]|null, runtime: any): any {
resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any {
return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime);
}

View File

@ -1,21 +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
*/
/**
* Provides read-only access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
*/
export abstract class ReflectorReader {
abstract parameters(typeOrFunc: /*Type*/ any): any[][];
abstract annotations(typeOrFunc: /*Type*/ any): any[];
abstract propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]};
abstract importUri(typeOrFunc: /*Type*/ any): string|null;
abstract resourceUri(typeOrFunc: /*Type*/ any): string;
abstract resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any;
abstract resolveEnum(identifier: any, name: string): any;
}

View File

@ -110,7 +110,8 @@ class LanguageServiceImpl implements LanguageService {
const expressionParser = new Parser(new Lexer());
const config = new CompilerConfig();
const parser = new TemplateParser(
config, expressionParser, new DomElementSchemaRegistry(), htmlParser, null !, []);
config, this.host.resolver.getReflector(), expressionParser,
new DomElementSchemaRegistry(), htmlParser, null !, []);
const htmlResult = htmlParser.parse(template.source, '', true);
const analyzedModules = this.host.getAnalyzedModules();
let errors: Diagnostic[]|undefined = undefined;

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {AotSummaryResolver, CompileMetadataResolver, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, InterpolationConfig, JitSummaryResolver, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, PipeResolver, ResourceLoader, StaticAndDynamicReflectionCapabilities, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, analyzeNgModules, componentModuleUrl, createOfflineCompileUrlResolver, extractProgramSymbols} from '@angular/compiler';
import {AotSummaryResolver, CompileMetadataResolver, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, InterpolationConfig, JitSummaryResolver, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, PipeResolver, ResourceLoader, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, analyzeNgModules, createOfflineCompileUrlResolver, extractProgramSymbols} from '@angular/compiler';
import {AngularCompilerOptions, getClassMembersFromDeclaration, getPipesTable, getSymbolQuery} from '@angular/compiler-cli';
import {ViewEncapsulation, ɵConsole as Console} from '@angular/core';
import * as fs from 'fs';
@ -274,11 +274,10 @@ export class TypeScriptServiceHost implements LanguageServiceHost {
const urlResolver = createOfflineCompileUrlResolver();
for (const module of ngModuleSummary.ngModules) {
for (const directive of module.declaredDirectives) {
const {metadata, annotation} =
this.resolver.getNonNormalizedDirectiveMetadata(directive.reference) !;
const {metadata} = this.resolver.getNonNormalizedDirectiveMetadata(directive.reference) !;
if (metadata.isComponent && metadata.template && metadata.template.templateUrl) {
const templateName = urlResolver.resolve(
componentModuleUrl(this.reflector, directive.reference, annotation),
this.reflector.componentModuleUrl(directive.reference),
metadata.template.templateUrl);
fileToComponent.set(templateName, directive.reference);
templateReference.push(templateName);
@ -422,7 +421,6 @@ export class TypeScriptServiceHost implements LanguageServiceHost {
const ssr = this.staticSymbolResolver;
result = this._reflector = new StaticReflector(
this._summaryResolver, ssr, [], [], (e, filePath) => this.collectError(e, filePath !));
StaticAndDynamicReflectionCapabilities.install(result);
}
return result;
}