feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking of services which are never injected. Ordinarily, this tree-shaking is prevented by the existence of a hard dependency on the service by the module in which it is declared. Firstly, @Injectable() is modified to accept a 'scope' parameter, which points to an @NgModule(). This reverses the dependency edge, permitting the module to not depend on the service which it "provides". Secondly, the runtime is modified to understand the new relationship created above. When a module receives a request to inject a token, and cannot find that token in its list of providers, it will then look at the token for a special ngInjectableDef field which indicates which module the token is scoped to. If that module happens to be in the injector, it will behave as if the token itself was in the injector to begin with. Thirdly, the compiler is modified to read the @Injectable() metadata and to generate the special ngInjectableDef field as part of TS compilation, using the PartialModules system. Additionally, this commit adds several unit and integration tests of various flavors to test this change. PR Close #22005
This commit is contained in:

committed by
Miško Hevery

parent
2d5e7d1b52
commit
235a235fab
@ -6,12 +6,13 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {CompileDirectiveMetadata, CompileDirectiveSummary, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileNgModuleSummary, CompilePipeMetadata, CompilePipeSummary, CompileProviderMetadata, CompileStylesheetMetadata, CompileSummaryKind, CompileTypeMetadata, CompileTypeSummary, componentFactoryName, flatten, identifierName, templateSourceUrl, tokenReference} from '../compile_metadata';
|
||||
import {CompileDirectiveMetadata, CompileDirectiveSummary, CompileIdentifierMetadata, CompileInjectableMetadata, CompileNgModuleMetadata, CompileNgModuleSummary, CompilePipeMetadata, CompilePipeSummary, CompileProviderMetadata, CompileStylesheetMetadata, CompileSummaryKind, CompileTypeMetadata, CompileTypeSummary, componentFactoryName, flatten, identifierName, templateSourceUrl, tokenReference} from '../compile_metadata';
|
||||
import {CompilerConfig} from '../config';
|
||||
import {ConstantPool} from '../constant_pool';
|
||||
import {ViewEncapsulation} from '../core';
|
||||
import {MessageBundle} from '../i18n/message_bundle';
|
||||
import {Identifiers, createTokenForExternalReference} from '../identifiers';
|
||||
import {InjectableCompiler} from '../injectable_compiler';
|
||||
import {CompileMetadataResolver} from '../metadata_resolver';
|
||||
import {HtmlParser} from '../ml_parser/html_parser';
|
||||
import {InterpolationConfig} from '../ml_parser/interpolation_config';
|
||||
@ -49,6 +50,7 @@ export class AotCompiler {
|
||||
private _templateAstCache =
|
||||
new Map<StaticSymbol, {template: TemplateAst[], pipes: CompilePipeSummary[]}>();
|
||||
private _analyzedFiles = new Map<string, NgAnalyzedFile>();
|
||||
private _analyzedFilesForInjectables = new Map<string, NgAnalyzedFileWithInjectables>();
|
||||
|
||||
constructor(
|
||||
private _config: CompilerConfig, private _options: AotCompilerOptions,
|
||||
@ -56,7 +58,7 @@ export class AotCompiler {
|
||||
private _metadataResolver: CompileMetadataResolver, private _templateParser: TemplateParser,
|
||||
private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler,
|
||||
private _typeCheckCompiler: TypeCheckCompiler, private _ngModuleCompiler: NgModuleCompiler,
|
||||
private _outputEmitter: OutputEmitter,
|
||||
private _injectableCompiler: InjectableCompiler, private _outputEmitter: OutputEmitter,
|
||||
private _summaryResolver: SummaryResolver<StaticSymbol>,
|
||||
private _symbolResolver: StaticSymbolResolver) {}
|
||||
|
||||
@ -91,6 +93,16 @@ export class AotCompiler {
|
||||
return analyzedFile;
|
||||
}
|
||||
|
||||
private _analyzeFileForInjectables(fileName: string): NgAnalyzedFileWithInjectables {
|
||||
let analyzedFile = this._analyzedFilesForInjectables.get(fileName);
|
||||
if (!analyzedFile) {
|
||||
analyzedFile = analyzeFileForInjectables(
|
||||
this._host, this._symbolResolver, this._metadataResolver, fileName);
|
||||
this._analyzedFilesForInjectables.set(fileName, analyzedFile);
|
||||
}
|
||||
return analyzedFile;
|
||||
}
|
||||
|
||||
findGeneratedFileNames(fileName: string): string[] {
|
||||
const genFileNames: string[] = [];
|
||||
const file = this._analyzeFile(fileName);
|
||||
@ -174,7 +186,8 @@ export class AotCompiler {
|
||||
null;
|
||||
}
|
||||
|
||||
loadFilesAsync(fileNames: string[]): Promise<NgAnalyzedModules> {
|
||||
loadFilesAsync(fileNames: string[], tsFiles: string[]): Promise<
|
||||
{analyzedModules: NgAnalyzedModules, analyzedInjectables: NgAnalyzedFileWithInjectables[]}> {
|
||||
const files = fileNames.map(fileName => this._analyzeFile(fileName));
|
||||
const loadingPromises: Promise<NgAnalyzedModules>[] = [];
|
||||
files.forEach(
|
||||
@ -182,16 +195,25 @@ export class AotCompiler {
|
||||
ngModule =>
|
||||
loadingPromises.push(this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(
|
||||
ngModule.type.reference, false))));
|
||||
return Promise.all(loadingPromises).then(_ => mergeAndValidateNgFiles(files));
|
||||
const analyzedInjectables = tsFiles.map(tsFile => this._analyzeFileForInjectables(tsFile));
|
||||
return Promise.all(loadingPromises).then(_ => ({
|
||||
analyzedModules: mergeAndValidateNgFiles(files),
|
||||
analyzedInjectables: analyzedInjectables,
|
||||
}));
|
||||
}
|
||||
|
||||
loadFilesSync(fileNames: string[]): NgAnalyzedModules {
|
||||
loadFilesSync(fileNames: string[], tsFiles: string[]):
|
||||
{analyzedModules: NgAnalyzedModules, analyzedInjectables: NgAnalyzedFileWithInjectables[]} {
|
||||
const files = fileNames.map(fileName => this._analyzeFile(fileName));
|
||||
files.forEach(
|
||||
file => file.ngModules.forEach(
|
||||
ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(
|
||||
ngModule.type.reference, true)));
|
||||
return mergeAndValidateNgFiles(files);
|
||||
const analyzedInjectables = tsFiles.map(tsFile => this._analyzeFileForInjectables(tsFile));
|
||||
return {
|
||||
analyzedModules: mergeAndValidateNgFiles(files),
|
||||
analyzedInjectables: analyzedInjectables,
|
||||
};
|
||||
}
|
||||
|
||||
private _createNgFactoryStub(
|
||||
@ -320,7 +342,7 @@ export class AotCompiler {
|
||||
private _emitPartialModule(
|
||||
fileName: string, ngModuleByPipeOrDirective: Map<StaticSymbol, CompileNgModuleMetadata>,
|
||||
directives: StaticSymbol[], pipes: StaticSymbol[], ngModules: CompileNgModuleMetadata[],
|
||||
injectables: StaticSymbol[]): PartialModule[] {
|
||||
injectables: CompileInjectableMetadata[]): PartialModule[] {
|
||||
const classes: o.ClassStmt[] = [];
|
||||
|
||||
const context = this._createOutputContext(fileName);
|
||||
@ -342,7 +364,29 @@ export class AotCompiler {
|
||||
}
|
||||
});
|
||||
|
||||
if (context.statements) {
|
||||
injectables.forEach(injectable => this._injectableCompiler.compile(injectable, context));
|
||||
|
||||
if (context.statements && context.statements.length > 0) {
|
||||
return [{fileName, statements: [...context.constantPool.statements, ...context.statements]}];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
emitAllPartialModules2(files: NgAnalyzedFileWithInjectables[]): PartialModule[] {
|
||||
// Using reduce like this is a select many pattern (where map is a select pattern)
|
||||
return files.reduce<PartialModule[]>((r, file) => {
|
||||
r.push(...this._emitPartialModule2(file.fileName, file.injectables));
|
||||
return r;
|
||||
}, []);
|
||||
}
|
||||
|
||||
private _emitPartialModule2(fileName: string, injectables: CompileInjectableMetadata[]):
|
||||
PartialModule[] {
|
||||
const context = this._createOutputContext(fileName);
|
||||
|
||||
injectables.forEach(injectable => this._injectableCompiler.compile(injectable, context));
|
||||
|
||||
if (context.statements && context.statements.length > 0) {
|
||||
return [{fileName, statements: [...context.constantPool.statements, ...context.statements]}];
|
||||
}
|
||||
return [];
|
||||
@ -360,7 +404,7 @@ export class AotCompiler {
|
||||
private _compileImplFile(
|
||||
srcFileUrl: string, ngModuleByPipeOrDirective: Map<StaticSymbol, CompileNgModuleMetadata>,
|
||||
directives: StaticSymbol[], pipes: StaticSymbol[], ngModules: CompileNgModuleMetadata[],
|
||||
injectables: StaticSymbol[]): GeneratedFile[] {
|
||||
injectables: CompileInjectableMetadata[]): GeneratedFile[] {
|
||||
const fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
|
||||
const generatedFiles: GeneratedFile[] = [];
|
||||
|
||||
@ -414,7 +458,7 @@ export class AotCompiler {
|
||||
|
||||
private _createSummary(
|
||||
srcFileName: string, directives: StaticSymbol[], pipes: StaticSymbol[],
|
||||
ngModules: CompileNgModuleMetadata[], injectables: StaticSymbol[],
|
||||
ngModules: CompileNgModuleMetadata[], injectables: CompileInjectableMetadata[],
|
||||
ngFactoryCtx: OutputContext): GeneratedFile[] {
|
||||
const symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
|
||||
.map(symbol => this._symbolResolver.resolveSymbol(symbol));
|
||||
@ -437,10 +481,11 @@ export class AotCompiler {
|
||||
summary: this._metadataResolver.getPipeSummary(ref) !,
|
||||
metadata: this._metadataResolver.getPipeMetadata(ref) !
|
||||
})),
|
||||
...injectables.map(ref => ({
|
||||
summary: this._metadataResolver.getInjectableSummary(ref) !,
|
||||
metadata: this._metadataResolver.getInjectableSummary(ref) !.type
|
||||
}))
|
||||
...injectables.map(
|
||||
ref => ({
|
||||
summary: this._metadataResolver.getInjectableSummary(ref.symbol) !,
|
||||
metadata: this._metadataResolver.getInjectableSummary(ref.symbol) !.type
|
||||
}))
|
||||
];
|
||||
const forJitOutputCtx = this._options.enableSummariesForJit ?
|
||||
this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
|
||||
@ -682,12 +727,17 @@ export interface NgAnalyzedModules {
|
||||
symbolsMissingModule?: StaticSymbol[];
|
||||
}
|
||||
|
||||
export interface NgAnalyzedFileWithInjectables {
|
||||
fileName: string;
|
||||
injectables: CompileInjectableMetadata[];
|
||||
}
|
||||
|
||||
export interface NgAnalyzedFile {
|
||||
fileName: string;
|
||||
directives: StaticSymbol[];
|
||||
pipes: StaticSymbol[];
|
||||
ngModules: CompileNgModuleMetadata[];
|
||||
injectables: StaticSymbol[];
|
||||
injectables: CompileInjectableMetadata[];
|
||||
exportsNonSourceFiles: boolean;
|
||||
}
|
||||
|
||||
@ -747,7 +797,7 @@ export function analyzeFile(
|
||||
metadataResolver: CompileMetadataResolver, fileName: string): NgAnalyzedFile {
|
||||
const directives: StaticSymbol[] = [];
|
||||
const pipes: StaticSymbol[] = [];
|
||||
const injectables: StaticSymbol[] = [];
|
||||
const injectables: CompileInjectableMetadata[] = [];
|
||||
const ngModules: CompileNgModuleMetadata[] = [];
|
||||
const hasDecorators = staticSymbolResolver.hasDecorators(fileName);
|
||||
let exportsNonSourceFiles = false;
|
||||
@ -779,7 +829,10 @@ export function analyzeFile(
|
||||
}
|
||||
} else if (metadataResolver.isInjectable(symbol)) {
|
||||
isNgSymbol = true;
|
||||
injectables.push(symbol);
|
||||
const injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
|
||||
if (injectable) {
|
||||
injectables.push(injectable);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isNgSymbol) {
|
||||
@ -793,6 +846,32 @@ export function analyzeFile(
|
||||
};
|
||||
}
|
||||
|
||||
export function analyzeFileForInjectables(
|
||||
host: NgAnalyzeModulesHost, staticSymbolResolver: StaticSymbolResolver,
|
||||
metadataResolver: CompileMetadataResolver, fileName: string): NgAnalyzedFileWithInjectables {
|
||||
const injectables: CompileInjectableMetadata[] = [];
|
||||
if (staticSymbolResolver.hasDecorators(fileName)) {
|
||||
staticSymbolResolver.getSymbolsOf(fileName).forEach((symbol) => {
|
||||
const resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
|
||||
const symbolMeta = resolvedSymbol.metadata;
|
||||
if (!symbolMeta || symbolMeta.__symbolic === 'error') {
|
||||
return;
|
||||
}
|
||||
let isNgSymbol = false;
|
||||
if (symbolMeta.__symbolic === 'class') {
|
||||
if (metadataResolver.isInjectable(symbol)) {
|
||||
isNgSymbol = true;
|
||||
const injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
|
||||
if (injectable) {
|
||||
injectables.push(injectable);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return {fileName, injectables};
|
||||
}
|
||||
|
||||
function isValueExportingNonSourceFile(host: NgAnalyzeModulesHost, metadata: any): boolean {
|
||||
let exportsNonSourceFiles = false;
|
||||
|
||||
|
@ -13,6 +13,7 @@ import {DirectiveResolver} from '../directive_resolver';
|
||||
import {Lexer} from '../expression_parser/lexer';
|
||||
import {Parser} from '../expression_parser/parser';
|
||||
import {I18NHtmlParser} from '../i18n/i18n_html_parser';
|
||||
import {InjectableCompiler} from '../injectable_compiler';
|
||||
import {CompileMetadataResolver} from '../metadata_resolver';
|
||||
import {HtmlParser} from '../ml_parser/html_parser';
|
||||
import {NgModuleCompiler} from '../ng_module_compiler';
|
||||
@ -90,7 +91,7 @@ export function createAotCompiler(
|
||||
const compiler = new AotCompiler(
|
||||
config, options, compilerHost, staticReflector, resolver, tmplParser,
|
||||
new StyleCompiler(urlResolver), viewCompiler, typeCheckCompiler,
|
||||
new NgModuleCompiler(staticReflector), new TypeScriptEmitter(), summaryResolver,
|
||||
symbolResolver);
|
||||
new NgModuleCompiler(staticReflector), new InjectableCompiler(staticReflector),
|
||||
new TypeScriptEmitter(), summaryResolver, symbolResolver);
|
||||
return {compiler, reflector: staticReflector};
|
||||
}
|
||||
|
@ -124,6 +124,16 @@ export class StaticReflector implements CompileReflector {
|
||||
return symbol;
|
||||
}
|
||||
|
||||
public tryAnnotations(type: StaticSymbol): any[] {
|
||||
const originalRecorder = this.errorRecorder;
|
||||
this.errorRecorder = (error: any, fileName: string) => {};
|
||||
try {
|
||||
return this.annotations(type);
|
||||
} finally {
|
||||
this.errorRecorder = originalRecorder;
|
||||
}
|
||||
}
|
||||
|
||||
public annotations(type: StaticSymbol): any[] {
|
||||
let annotations = this.annotationCache.get(type);
|
||||
if (!annotations) {
|
||||
@ -331,6 +341,8 @@ export class StaticReflector implements CompileReflector {
|
||||
}
|
||||
|
||||
private initializeConversionMap(): void {
|
||||
this._registerDecoratorOrConstructor(
|
||||
this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
|
||||
this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
|
||||
this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
|
||||
this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
|
||||
@ -338,8 +350,6 @@ export class StaticReflector implements CompileReflector {
|
||||
this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
|
||||
|
||||
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
|
||||
this._registerDecoratorOrConstructor(
|
||||
this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
|
||||
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
|
||||
this._registerDecoratorOrConstructor(
|
||||
this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
|
||||
|
@ -12,6 +12,9 @@ import {ValueTransformer, visitValue} from '../util';
|
||||
import {StaticSymbol, StaticSymbolCache} from './static_symbol';
|
||||
import {isGeneratedFile, stripSummaryForJitFileSuffix, stripSummaryForJitNameSuffix, summaryForJitFileName, summaryForJitName} from './util';
|
||||
|
||||
const DTS = /\.d\.ts$/;
|
||||
const TS = /^(?!.*\.d\.ts$).*\.ts$/;
|
||||
|
||||
export class ResolvedStaticSymbol {
|
||||
constructor(public symbol: StaticSymbol, public metadata: any) {}
|
||||
}
|
||||
@ -374,7 +377,8 @@ export class StaticSymbolResolver {
|
||||
// (e.g. their constructor parameters).
|
||||
// We do this to prevent introducing deep imports
|
||||
// as we didn't generate .ngfactory.ts files with proper reexports.
|
||||
if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && metadata &&
|
||||
const isTsFile = TS.test(sourceSymbol.filePath);
|
||||
if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
|
||||
metadata['__symbolic'] === 'class') {
|
||||
const transformedMeta = {__symbolic: 'class', arity: metadata.arity};
|
||||
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
|
||||
|
@ -136,6 +136,19 @@ export interface CompileTokenMetadata {
|
||||
identifier?: CompileIdentifierMetadata|CompileTypeMetadata;
|
||||
}
|
||||
|
||||
export interface CompileInjectableMetadata {
|
||||
symbol: StaticSymbol;
|
||||
type: CompileTypeMetadata;
|
||||
|
||||
module?: StaticSymbol;
|
||||
|
||||
useValue?: any;
|
||||
useClass?: StaticSymbol;
|
||||
useExisting?: StaticSymbol;
|
||||
useFactory?: StaticSymbol;
|
||||
deps?: any[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata regarding compilation of a type.
|
||||
*/
|
||||
|
@ -15,6 +15,7 @@ import * as o from './output/output_ast';
|
||||
export abstract class CompileReflector {
|
||||
abstract parameters(typeOrFunc: /*Type*/ any): any[][];
|
||||
abstract annotations(typeOrFunc: /*Type*/ any): any[];
|
||||
abstract tryAnnotations(typeOrFunc: /*Type*/ any): any[];
|
||||
abstract propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]};
|
||||
abstract hasLifecycleHook(type: any, lcProperty: string): boolean;
|
||||
abstract guards(typeOrFunc: /* Type */ any): {[key: string]: any};
|
||||
|
@ -14,8 +14,8 @@
|
||||
|
||||
export interface Inject { token: any; }
|
||||
export const createInject = makeMetadataFactory<Inject>('Inject', (token: any) => ({token}));
|
||||
export const createInjectionToken =
|
||||
makeMetadataFactory<object>('InjectionToken', (desc: string) => ({_desc: desc}));
|
||||
export const createInjectionToken = makeMetadataFactory<object>(
|
||||
'InjectionToken', (desc: string) => ({_desc: desc, ngInjectableDef: undefined}));
|
||||
|
||||
export interface Attribute { attributeName?: string; }
|
||||
export const createAttribute =
|
||||
@ -126,7 +126,16 @@ export interface ModuleWithProviders {
|
||||
ngModule: Type;
|
||||
providers?: Provider[];
|
||||
}
|
||||
|
||||
export interface Injectable {
|
||||
scope?: Type|any;
|
||||
useClass?: Type|any;
|
||||
useExisting?: Type|any;
|
||||
useValue?: any;
|
||||
useFactory?: Type|any;
|
||||
deps?: Array<Type|any[]>;
|
||||
}
|
||||
export const createInjectable =
|
||||
makeMetadataFactory('Injectable', (injectable: Injectable = {}) => injectable);
|
||||
export interface SchemaMetadata { name: string; }
|
||||
|
||||
export const CUSTOM_ELEMENTS_SCHEMA: SchemaMetadata = {
|
||||
@ -138,7 +147,6 @@ export const NO_ERRORS_SCHEMA: SchemaMetadata = {
|
||||
};
|
||||
|
||||
export const createOptional = makeMetadataFactory('Optional');
|
||||
export const createInjectable = makeMetadataFactory('Injectable');
|
||||
export const createSelf = makeMetadataFactory('Self');
|
||||
export const createSkipSelf = makeMetadataFactory('SkipSelf');
|
||||
export const createHost = makeMetadataFactory('Host');
|
||||
@ -205,7 +213,18 @@ export const enum DepFlags {
|
||||
None = 0,
|
||||
SkipSelf = 1 << 0,
|
||||
Optional = 1 << 1,
|
||||
Value = 2 << 2,
|
||||
Self = 1 << 2,
|
||||
Value = 1 << 3,
|
||||
}
|
||||
|
||||
/** Injection flags for DI. */
|
||||
export const enum InjectFlags {
|
||||
Default = 0,
|
||||
|
||||
/** Skip the node that is requesting injection. */
|
||||
SkipSelf = 1 << 0,
|
||||
/** Don't descend into ancestors of the node requesting injection. */
|
||||
Self = 1 << 1,
|
||||
}
|
||||
|
||||
export const enum ArgumentType {Inline = 0, Dynamic = 1}
|
||||
|
@ -61,7 +61,9 @@ export class Identifiers {
|
||||
moduleName: CORE,
|
||||
|
||||
};
|
||||
static inject: o.ExternalReference = {name: 'inject', moduleName: CORE};
|
||||
static Injector: o.ExternalReference = {name: 'Injector', moduleName: CORE};
|
||||
static defineInjectable: o.ExternalReference = {name: 'defineInjectable', moduleName: CORE};
|
||||
static ViewEncapsulation: o.ExternalReference = {
|
||||
name: 'ViewEncapsulation',
|
||||
moduleName: CORE,
|
||||
|
111
packages/compiler/src/injectable_compiler.ts
Normal file
111
packages/compiler/src/injectable_compiler.ts
Normal file
@ -0,0 +1,111 @@
|
||||
/**
|
||||
* @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 {CompileInjectableMetadata, CompileNgModuleMetadata, CompileProviderMetadata, identifierName} from './compile_metadata';
|
||||
import {CompileReflector} from './compile_reflector';
|
||||
import {InjectFlags, NodeFlags} from './core';
|
||||
import {Identifiers} from './identifiers';
|
||||
import * as o from './output/output_ast';
|
||||
import {convertValueToOutputAst} from './output/value_util';
|
||||
import {typeSourceSpan} from './parse_util';
|
||||
import {NgModuleProviderAnalyzer} from './provider_analyzer';
|
||||
import {OutputContext} from './util';
|
||||
import {componentFactoryResolverProviderDef, depDef, providerDef} from './view_compiler/provider_compiler';
|
||||
|
||||
type MapEntry = {
|
||||
key: string,
|
||||
quoted: boolean,
|
||||
value: o.Expression
|
||||
};
|
||||
type MapLiteral = MapEntry[];
|
||||
|
||||
function mapEntry(key: string, value: o.Expression): MapEntry {
|
||||
return {key, value, quoted: false};
|
||||
}
|
||||
|
||||
export class InjectableCompiler {
|
||||
constructor(private reflector: CompileReflector) {}
|
||||
|
||||
private depsArray(deps: any[], ctx: OutputContext): o.Expression[] {
|
||||
return deps.map(dep => {
|
||||
let token = dep;
|
||||
let defaultValue = undefined;
|
||||
let args = [token];
|
||||
let flags: InjectFlags = InjectFlags.Default;
|
||||
if (Array.isArray(dep)) {
|
||||
for (let i = 0; i < dep.length; i++) {
|
||||
const v = dep[i];
|
||||
if (v) {
|
||||
if (v.ngMetadataName === 'Optional') {
|
||||
defaultValue = null;
|
||||
} else if (v.ngMetadataName === 'SkipSelf') {
|
||||
flags |= InjectFlags.SkipSelf;
|
||||
} else if (v.ngMetadataName === 'Self') {
|
||||
flags |= InjectFlags.Self;
|
||||
} else if (v.ngMetadataName === 'Inject') {
|
||||
throw new Error('@Inject() is not implemented');
|
||||
} else {
|
||||
token = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
args = [ctx.importExpr(token), o.literal(defaultValue), o.literal(flags)];
|
||||
} else {
|
||||
args = [ctx.importExpr(token)];
|
||||
}
|
||||
return o.importExpr(Identifiers.inject).callFn(args);
|
||||
});
|
||||
}
|
||||
|
||||
private factoryFor(injectable: CompileInjectableMetadata, ctx: OutputContext): o.Expression {
|
||||
let retValue: o.Expression;
|
||||
if (injectable.useExisting) {
|
||||
retValue = o.importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
|
||||
} else if (injectable.useFactory) {
|
||||
const deps = injectable.deps || [];
|
||||
if (deps.length > 0) {
|
||||
retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
|
||||
} else {
|
||||
return ctx.importExpr(injectable.useFactory);
|
||||
}
|
||||
} else if (injectable.useValue) {
|
||||
retValue = convertValueToOutputAst(ctx, injectable.useValue);
|
||||
} else {
|
||||
const clazz = injectable.useClass || injectable.symbol;
|
||||
const depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
|
||||
retValue = new o.InstantiateExpr(ctx.importExpr(clazz), depArgs);
|
||||
}
|
||||
return o.fn(
|
||||
[], [new o.ReturnStatement(retValue)], undefined, undefined,
|
||||
injectable.symbol.name + '_Factory');
|
||||
}
|
||||
|
||||
injectableDef(injectable: CompileInjectableMetadata, ctx: OutputContext): o.Expression {
|
||||
const def: MapLiteral = [
|
||||
mapEntry('factory', this.factoryFor(injectable, ctx)),
|
||||
mapEntry('token', ctx.importExpr(injectable.type.reference)),
|
||||
mapEntry('scope', ctx.importExpr(injectable.module !)),
|
||||
];
|
||||
return o.importExpr(Identifiers.defineInjectable).callFn([o.literalMap(def)]);
|
||||
}
|
||||
|
||||
compile(injectable: CompileInjectableMetadata, ctx: OutputContext): void {
|
||||
if (injectable.module) {
|
||||
const className = identifierName(injectable.type) !;
|
||||
const clazz = new o.ClassStmt(
|
||||
className, null,
|
||||
[
|
||||
new o.ClassField(
|
||||
'ngInjectableDef', o.INFERRED_TYPE, [o.StmtModifier.Static],
|
||||
this.injectableDef(injectable, ctx)),
|
||||
],
|
||||
[], new o.ClassMethod(null, [], []), []);
|
||||
ctx.statements.push(clazz);
|
||||
}
|
||||
}
|
||||
}
|
@ -12,7 +12,7 @@ import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions';
|
||||
import * as cpl from './compile_metadata';
|
||||
import {CompileReflector} from './compile_reflector';
|
||||
import {CompilerConfig} from './config';
|
||||
import {ChangeDetectionStrategy, Component, Directive, ModuleWithProviders, Provider, Query, SchemaMetadata, Type, ViewEncapsulation, createAttribute, createComponent, createHost, createInject, createInjectable, createInjectionToken, createOptional, createSelf, createSkipSelf} from './core';
|
||||
import {ChangeDetectionStrategy, Component, Directive, Injectable, ModuleWithProviders, Provider, Query, SchemaMetadata, Type, ViewEncapsulation, createAttribute, createComponent, createHost, createInject, createInjectable, createInjectionToken, createOptional, createSelf, createSkipSelf} from './core';
|
||||
import {DirectiveNormalizer} from './directive_normalizer';
|
||||
import {DirectiveResolver} from './directive_resolver';
|
||||
import {Identifiers} from './identifiers';
|
||||
@ -771,7 +771,7 @@ export class CompileMetadataResolver {
|
||||
}
|
||||
|
||||
isInjectable(type: any): boolean {
|
||||
const annotations = this._reflector.annotations(type);
|
||||
const annotations = this._reflector.tryAnnotations(type);
|
||||
return annotations.some(ann => createInjectable.isTypeOf(ann));
|
||||
}
|
||||
|
||||
@ -782,13 +782,32 @@ export class CompileMetadataResolver {
|
||||
};
|
||||
}
|
||||
|
||||
private _getInjectableMetadata(type: Type, dependencies: any[]|null = null):
|
||||
cpl.CompileTypeMetadata {
|
||||
getInjectableMetadata(
|
||||
type: any, dependencies: any[]|null = null,
|
||||
throwOnUnknownDeps: boolean = true): cpl.CompileInjectableMetadata|null {
|
||||
const typeSummary = this._loadSummary(type, cpl.CompileSummaryKind.Injectable);
|
||||
if (typeSummary) {
|
||||
return typeSummary.type;
|
||||
const typeMetadata = typeSummary ?
|
||||
typeSummary.type :
|
||||
this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
|
||||
|
||||
const annotations: Injectable[] =
|
||||
this._reflector.annotations(type).filter(ann => createInjectable.isTypeOf(ann));
|
||||
|
||||
if (annotations.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this._getTypeMetadata(type, dependencies);
|
||||
|
||||
const meta = annotations[annotations.length - 1];
|
||||
return {
|
||||
symbol: type,
|
||||
type: typeMetadata,
|
||||
module: meta.scope || undefined,
|
||||
useValue: meta.useValue,
|
||||
useClass: meta.useClass,
|
||||
useExisting: meta.useExisting,
|
||||
useFactory: meta.useFactory,
|
||||
deps: meta.deps,
|
||||
};
|
||||
}
|
||||
|
||||
private _getTypeMetadata(type: Type, dependencies: any[]|null = null, throwOnUnknownDeps = true):
|
||||
@ -1042,6 +1061,15 @@ export class CompileMetadataResolver {
|
||||
return null;
|
||||
}
|
||||
|
||||
private _getInjectableTypeMetadata(type: Type, dependencies: any[]|null = null):
|
||||
cpl.CompileTypeMetadata {
|
||||
const typeSummary = this._loadSummary(type, cpl.CompileSummaryKind.Injectable);
|
||||
if (typeSummary) {
|
||||
return typeSummary.type;
|
||||
}
|
||||
return this._getTypeMetadata(type, dependencies);
|
||||
}
|
||||
|
||||
getProviderMetadata(provider: cpl.ProviderMeta): cpl.CompileProviderMetadata {
|
||||
let compileDeps: cpl.CompileDiDependencyMetadata[] = undefined !;
|
||||
let compileTypeMetadata: cpl.CompileTypeMetadata = null !;
|
||||
@ -1049,7 +1077,8 @@ export class CompileMetadataResolver {
|
||||
let token: cpl.CompileTokenMetadata = this._getTokenMetadata(provider.token);
|
||||
|
||||
if (provider.useClass) {
|
||||
compileTypeMetadata = this._getInjectableMetadata(provider.useClass, provider.dependencies);
|
||||
compileTypeMetadata =
|
||||
this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
|
||||
compileDeps = compileTypeMetadata.diDeps;
|
||||
if (provider.token === provider.useClass) {
|
||||
// use the compileTypeMetadata as it contains information about lifecycleHooks...
|
||||
|
@ -294,7 +294,7 @@ export class ProviderElementContext {
|
||||
this.viewContext.viewProviders.get(tokenReference(dep.token !)) != null) {
|
||||
result = dep;
|
||||
} else {
|
||||
result = dep.isOptional ? result = {isValue: true, value: null} : null;
|
||||
result = dep.isOptional ? {isValue: true, value: null} : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -321,11 +321,12 @@ export class NgModuleProviderAnalyzer {
|
||||
const ngModuleProvider = {token: {identifier: ngModuleType}, useClass: ngModuleType};
|
||||
_resolveProviders(
|
||||
[ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, this._errors,
|
||||
this._allProviders, true);
|
||||
this._allProviders, /* isModule */ true);
|
||||
});
|
||||
_resolveProviders(
|
||||
ngModule.transitiveModule.providers.map(entry => entry.provider).concat(extraProviders),
|
||||
ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders, false);
|
||||
ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
|
||||
/* isModule */ false);
|
||||
}
|
||||
|
||||
parse(): ProviderAst[] {
|
||||
@ -415,16 +416,7 @@ export class NgModuleProviderAnalyzer {
|
||||
foundLocal = true;
|
||||
}
|
||||
}
|
||||
let result: CompileDiDependencyMetadata = dep;
|
||||
if (dep.isSelf && !foundLocal) {
|
||||
if (dep.isOptional) {
|
||||
result = {isValue: true, value: null};
|
||||
} else {
|
||||
this._errors.push(
|
||||
new ProviderError(`No provider for ${tokenName(dep.token!)}`, requestorSourceSpan));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return dep;
|
||||
}
|
||||
}
|
||||
|
||||
@ -461,7 +453,7 @@ function _resolveProvidersFromDirectives(
|
||||
_resolveProviders(
|
||||
[dirProvider],
|
||||
directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true,
|
||||
sourceSpan, targetErrors, providersByToken, false);
|
||||
sourceSpan, targetErrors, providersByToken, /* isModule */ false);
|
||||
});
|
||||
|
||||
// Note: directives need to be able to overwrite providers of a component!
|
||||
@ -470,10 +462,10 @@ function _resolveProvidersFromDirectives(
|
||||
directivesWithComponentFirst.forEach((directive) => {
|
||||
_resolveProviders(
|
||||
directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors,
|
||||
providersByToken, false);
|
||||
providersByToken, /* isModule */ false);
|
||||
_resolveProviders(
|
||||
directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors,
|
||||
providersByToken, false);
|
||||
providersByToken, /* isModule */ false);
|
||||
});
|
||||
return providersByToken;
|
||||
}
|
||||
|
@ -129,7 +129,7 @@ function tokenExpr(ctx: OutputContext, tokenMeta: CompileTokenMetadata): o.Expre
|
||||
|
||||
export function depDef(ctx: OutputContext, dep: CompileDiDependencyMetadata): o.Expression {
|
||||
// Note: the following fields have already been normalized out by provider_analyzer:
|
||||
// - isAttribute, isSelf, isHost
|
||||
// - isAttribute, isHost
|
||||
const expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token !);
|
||||
let flags = DepFlags.None;
|
||||
if (dep.isSkipSelf) {
|
||||
@ -138,6 +138,9 @@ export function depDef(ctx: OutputContext, dep: CompileDiDependencyMetadata): o.
|
||||
if (dep.isOptional) {
|
||||
flags |= DepFlags.Optional;
|
||||
}
|
||||
if (dep.isSelf) {
|
||||
flags |= DepFlags.Self;
|
||||
}
|
||||
if (dep.isValue) {
|
||||
flags |= DepFlags.Value;
|
||||
}
|
||||
|
@ -531,6 +531,7 @@ const minCoreIndex = `
|
||||
export * from './src/change_detection';
|
||||
export * from './src/metadata';
|
||||
export * from './src/di/metadata';
|
||||
export * from './src/di/injectable';
|
||||
export * from './src/di/injector';
|
||||
export * from './src/di/injection_token';
|
||||
export * from './src/linker';
|
||||
|
@ -148,6 +148,10 @@ import * as core from '@angular/core';
|
||||
expect(compilerCore.DepFlags.Optional).toBe(core.ɵDepFlags.Optional);
|
||||
expect(compilerCore.DepFlags.Value).toBe(core.ɵDepFlags.Value);
|
||||
|
||||
expect(compilerCore.InjectFlags.Default).toBe(core.InjectFlags.Default);
|
||||
expect(compilerCore.InjectFlags.SkipSelf).toBe(core.InjectFlags.SkipSelf);
|
||||
expect(compilerCore.InjectFlags.Self).toBe(core.InjectFlags.Self);
|
||||
|
||||
expect(compilerCore.ArgumentType.Inline).toBe(core.ɵArgumentType.Inline);
|
||||
expect(compilerCore.ArgumentType.Dynamic).toBe(core.ɵArgumentType.Dynamic);
|
||||
|
||||
|
Reference in New Issue
Block a user