diff --git a/packages/compiler/src/aot/compiler.ts b/packages/compiler/src/aot/compiler.ts index 1a123791e1..47db67073a 100644 --- a/packages/compiler/src/aot/compiler.ts +++ b/packages/compiler/src/aot/compiler.ts @@ -15,23 +15,16 @@ import {createTokenForExternalReference, Identifiers} from '../identifiers'; import {InjectableCompiler} from '../injectable_compiler'; import {CompileMetadataResolver} from '../metadata_resolver'; import {HtmlParser} from '../ml_parser/html_parser'; -import {removeWhitespaces} from '../ml_parser/html_whitespaces'; -import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../ml_parser/interpolation_config'; +import {InterpolationConfig} from '../ml_parser/interpolation_config'; import {NgModuleCompiler} from '../ng_module_compiler'; import {OutputEmitter} from '../output/abstract_emitter'; import * as o from '../output/output_ast'; import {ParseError} from '../parse_util'; -import {compileNgModuleFromRender2 as compileR3Module} from '../render3/r3_module_compiler'; -import {compilePipeFromRender2 as compileR3Pipe} from '../render3/r3_pipe_compiler'; -import {htmlAstToRender3Ast} from '../render3/r3_template_transform'; -import {compileComponentFromRender2 as compileR3Component, compileDirectiveFromRender2 as compileR3Directive} from '../render3/view/compiler'; -import {DomElementSchemaRegistry} from '../schema/dom_element_schema_registry'; import {CompiledStylesheet, StyleCompiler} from '../style_compiler'; import {SummaryResolver} from '../summary_resolver'; -import {BindingParser} from '../template_parser/binding_parser'; import {TemplateAst} from '../template_parser/template_ast'; import {TemplateParser} from '../template_parser/template_parser'; -import {error, newArray, OutputContext, syntaxError, ValueVisitor, visitValue} from '../util'; +import {newArray, OutputContext, syntaxError, ValueVisitor, visitValue} from '../util'; import {TypeCheckCompiler} from '../view_compiler/type_check_compiler'; import {ViewCompiler, ViewCompileResult} from '../view_compiler/view_compiler'; @@ -341,107 +334,6 @@ export class AotCompiler { return messageBundle; } - emitAllPartialModules( - {ngModuleByPipeOrDirective, files}: NgAnalyzedModules, - r3Files: NgAnalyzedFileWithInjectables[]): PartialModule[] { - const contextMap = new Map(); - - const getContext = (fileName: string): OutputContext => { - if (!contextMap.has(fileName)) { - contextMap.set(fileName, this._createOutputContext(fileName)); - } - return contextMap.get(fileName)!; - }; - - files.forEach( - file => this._compilePartialModule( - file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, - file.injectables, getContext(file.fileName))); - r3Files.forEach( - file => this._compileShallowModules( - file.fileName, file.shallowModules, getContext(file.fileName))); - - return Array.from(contextMap.values()) - .map(context => ({ - fileName: context.genFilePath, - statements: [...context.constantPool.statements, ...context.statements], - })); - } - - private _compileShallowModules( - fileName: string, shallowModules: CompileShallowModuleMetadata[], - context: OutputContext): void { - shallowModules.forEach(module => compileR3Module(context, module, this._injectableCompiler)); - } - - private _compilePartialModule( - fileName: string, ngModuleByPipeOrDirective: Map, - directives: StaticSymbol[], pipes: StaticSymbol[], ngModules: CompileNgModuleMetadata[], - injectables: CompileInjectableMetadata[], context: OutputContext): void { - const errors: ParseError[] = []; - - const schemaRegistry = new DomElementSchemaRegistry(); - const hostBindingParser = new BindingParser( - this._templateParser.expressionParser, DEFAULT_INTERPOLATION_CONFIG, schemaRegistry, [], - errors); - - // Process all components and directives - directives.forEach(directiveType => { - const directiveMetadata = this._metadataResolver.getDirectiveMetadata(directiveType); - if (directiveMetadata.isComponent) { - const module = ngModuleByPipeOrDirective.get(directiveType)!; - module || - error(`Cannot determine the module for component '${ - identifierName(directiveMetadata.type)}'`); - - let htmlAst = directiveMetadata.template !.htmlAst!; - const preserveWhitespaces = directiveMetadata!.template !.preserveWhitespaces; - - if (!preserveWhitespaces) { - htmlAst = removeWhitespaces(htmlAst); - } - const render3Ast = htmlAstToRender3Ast(htmlAst.rootNodes, hostBindingParser); - - // Map of StaticType by directive selectors - const directiveTypeBySel = new Map(); - - const directives = module.transitiveModule.directives.map( - dir => this._metadataResolver.getDirectiveSummary(dir.reference)); - - directives.forEach(directive => { - if (directive.selector) { - directiveTypeBySel.set(directive.selector, directive.type.reference); - } - }); - - // Map of StaticType by pipe names - const pipeTypeByName = new Map(); - - const pipes = module.transitiveModule.pipes.map( - pipe => this._metadataResolver.getPipeSummary(pipe.reference)); - - pipes.forEach(pipe => { - pipeTypeByName.set(pipe.name, pipe.type.reference); - }); - - compileR3Component( - context, directiveMetadata, render3Ast, this.reflector, hostBindingParser, - directiveTypeBySel, pipeTypeByName); - } else { - compileR3Directive(context, directiveMetadata, this.reflector, hostBindingParser); - } - }); - - pipes.forEach(pipeType => { - const pipeMetadata = this._metadataResolver.getPipeMetadata(pipeType); - if (pipeMetadata) { - compileR3Pipe(context, pipeMetadata, this.reflector); - } - }); - - injectables.forEach(injectable => this._injectableCompiler.compile(injectable, context)); - } - emitAllPartialModules2(files: NgAnalyzedFileWithInjectables[]): PartialModule[] { // Using reduce like this is a select many pattern (where map is a select pattern) return files.reduce((r, file) => { diff --git a/packages/compiler/src/render3/r3_module_compiler.ts b/packages/compiler/src/render3/r3_module_compiler.ts index 981737b078..7bf066338a 100644 --- a/packages/compiler/src/render3/r3_module_compiler.ts +++ b/packages/compiler/src/render3/r3_module_compiler.ts @@ -6,15 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {CompileShallowModuleMetadata, identifierName} from '../compile_metadata'; -import {InjectableCompiler} from '../injectable_compiler'; -import {mapLiteral} from '../output/map_util'; import * as o from '../output/output_ast'; -import {OutputContext} from '../util'; import {compileFactoryFunction, R3DependencyMetadata, R3FactoryTarget} from './r3_factory'; import {Identifiers as R3} from './r3_identifiers'; -import {convertMetaToOutput, jitOnlyGuardedExpression, mapToMapExpression, R3Reference} from './util'; +import {jitOnlyGuardedExpression, mapToMapExpression, R3Reference} from './util'; export interface R3NgModuleDef { expression: o.Expression; @@ -261,38 +257,6 @@ export function compileInjector(meta: R3InjectorMetadata): R3InjectorDef { return {expression, type, statements: result.statements}; } -// TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations. -export function compileNgModuleFromRender2( - ctx: OutputContext, ngModule: CompileShallowModuleMetadata, - injectableCompiler: InjectableCompiler): void { - const className = identifierName(ngModule.type)!; - - const rawImports = ngModule.rawImports ? [ngModule.rawImports] : []; - const rawExports = ngModule.rawExports ? [ngModule.rawExports] : []; - - const injectorDefArg = mapLiteral({ - 'factory': - injectableCompiler.factoryFor({type: ngModule.type, symbol: ngModule.type.reference}, ctx), - 'providers': convertMetaToOutput(ngModule.rawProviders, ctx), - 'imports': convertMetaToOutput([...rawImports, ...rawExports], ctx), - }); - - const injectorDef = o.importExpr(R3.defineInjector).callFn([injectorDefArg]); - - ctx.statements.push(new o.ClassStmt( - /* name */ className, - /* parent */ null, - /* fields */[new o.ClassField( - /* name */ 'ɵinj', - /* type */ o.INFERRED_TYPE, - /* modifiers */[o.StmtModifier.Static], - /* initializer */ injectorDef, - )], - /* getters */[], - /* constructorMethod */ new o.ClassMethod(null, [], []), - /* methods */[])); -} - function tupleTypeOf(exp: R3Reference[]): o.Type { const types = exp.map(ref => o.typeofExpr(ref.type)); return exp.length > 0 ? o.expressionType(o.literalArr(types)) : o.NONE_TYPE; diff --git a/packages/compiler/src/render3/r3_pipe_compiler.ts b/packages/compiler/src/render3/r3_pipe_compiler.ts index a677d1fec5..6a9e25ef1c 100644 --- a/packages/compiler/src/render3/r3_pipe_compiler.ts +++ b/packages/compiler/src/render3/r3_pipe_compiler.ts @@ -5,16 +5,11 @@ * 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 {CompilePipeMetadata, identifierName} from '../compile_metadata'; -import {CompileReflector} from '../compile_reflector'; -import {DefinitionKind} from '../constant_pool'; import * as o from '../output/output_ast'; -import {error, OutputContext} from '../util'; -import {compileFactoryFunction, dependenciesFromGlobalMetadata, R3DependencyMetadata, R3FactoryTarget} from './r3_factory'; +import {R3DependencyMetadata} from './r3_factory'; import {Identifiers as R3} from './r3_identifiers'; -import {R3Reference, typeWithParameters, wrapReference} from './util'; +import {R3Reference, typeWithParameters} from './util'; import {R3PipeDef} from './view/api'; export interface R3PipeMetadata { @@ -82,55 +77,3 @@ export function createPipeType(metadata: R3PipeMetadata): o.Type { new o.ExpressionType(new o.LiteralExpr(metadata.pipeName)), ])); } - -/** - * Write a pipe definition to the output context. - */ -export function compilePipeFromRender2( - outputCtx: OutputContext, pipe: CompilePipeMetadata, reflector: CompileReflector) { - const name = identifierName(pipe.type); - - if (!name) { - return error(`Cannot resolve the name of ${pipe.type}`); - } - - const type = outputCtx.importExpr(pipe.type.reference); - const metadata: R3PipeMetadata = { - name, - type: wrapReference(type), - internalType: type, - pipeName: pipe.name, - typeArgumentCount: 0, - deps: dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector), - pure: pipe.pure, - }; - const res = compilePipeFromMetadata(metadata); - const factoryRes = compileFactoryFunction( - {...metadata, injectFn: R3.directiveInject, target: R3FactoryTarget.Pipe}); - const definitionField = outputCtx.constantPool.propertyNameOf(DefinitionKind.Pipe); - const ngFactoryDefStatement = new o.ClassStmt( - /* name */ name, - /* parent */ null, - /* fields */ - [new o.ClassField( - /* name */ 'ɵfac', - /* type */ o.INFERRED_TYPE, - /* modifiers */[o.StmtModifier.Static], - /* initializer */ factoryRes.factory)], - /* getters */[], - /* constructorMethod */ new o.ClassMethod(null, [], []), - /* methods */[]); - const pipeDefStatement = new o.ClassStmt( - /* name */ name, - /* parent */ null, - /* fields */[new o.ClassField( - /* name */ definitionField, - /* type */ o.INFERRED_TYPE, - /* modifiers */[o.StmtModifier.Static], - /* initializer */ res.expression)], - /* getters */[], - /* constructorMethod */ new o.ClassMethod(null, [], []), - /* methods */[]); - - outputCtx.statements.push(ngFactoryDefStatement, pipeDefStatement); -} diff --git a/packages/compiler/src/render3/view/compiler.ts b/packages/compiler/src/render3/view/compiler.ts index a2aebdb9c8..6bc916d572 100644 --- a/packages/compiler/src/render3/view/compiler.ts +++ b/packages/compiler/src/render3/view/compiler.ts @@ -6,25 +6,20 @@ * found in the LICENSE file at https://angular.io/license */ -import {StaticSymbol} from '../../aot/static_symbol'; -import {CompileDirectiveMetadata, CompileDirectiveSummary, CompileQueryMetadata, CompileTokenMetadata, identifierName, sanitizeIdentifier} from '../../compile_metadata'; -import {CompileReflector} from '../../compile_reflector'; +import {CompileDirectiveSummary, sanitizeIdentifier} from '../../compile_metadata'; import {BindingForm, convertPropertyBinding} from '../../compiler_util/expression_converter'; -import {ConstantPool, DefinitionKind} from '../../constant_pool'; +import {ConstantPool} from '../../constant_pool'; import * as core from '../../core'; import {AST, ParsedEvent, ParsedEventType, ParsedProperty} from '../../expression_parser/ast'; -import {DEFAULT_INTERPOLATION_CONFIG} from '../../ml_parser/interpolation_config'; import * as o from '../../output/output_ast'; import {ParseError, ParseSourceSpan} from '../../parse_util'; import {CssSelector, SelectorMatcher} from '../../selector'; import {ShadowCss} from '../../shadow_css'; import {CONTENT_ATTR, HOST_ATTR} from '../../style_compiler'; import {BindingParser} from '../../template_parser/binding_parser'; -import {error, OutputContext} from '../../util'; +import {error} from '../../util'; import {BoundEvent} from '../r3_ast'; -import {compileFactoryFunction, R3FactoryTarget} from '../r3_factory'; import {Identifiers as R3} from '../r3_identifiers'; -import {Render3ParseResult} from '../r3_template_transform'; import {prepareSyntheticListenerFunctionName, prepareSyntheticPropertyName, typeWithParameters} from '../util'; import {DeclarationListEmitMode, R3ComponentDef, R3ComponentMetadata, R3DirectiveDef, R3DirectiveMetadata, R3HostMetadata, R3QueryMetadata} from './api'; @@ -32,7 +27,6 @@ import {MIN_STYLING_BINDING_SLOTS_REQUIRED, StylingBuilder, StylingInstructionCa import {BindingScope, makeBindingParser, prepareEventListenerParameters, renderFlagCheckIfStmt, resolveSanitizationFn, TemplateDefinitionBuilder, ValueConverter} from './template'; import {asLiteral, chainedInstruction, conditionallyCreateMapObjectLiteral, CONTEXT_NAME, DefinitionMap, getQueryPredicate, RENDER_FLAGS, TEMPORARY_NAME, temporaryAllocator} from './util'; -const EMPTY_ARRAY: any[] = []; // This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required" // If there is a match, the first matching group will contain the attribute name to bind. @@ -293,147 +287,6 @@ function compileDeclarationList( } } -/** - * A wrapper around `compileDirective` which depends on render2 global analysis data as its input - * instead of the `R3DirectiveMetadata`. - * - * `R3DirectiveMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected - * information. - */ -export function compileDirectiveFromRender2( - outputCtx: OutputContext, directive: CompileDirectiveMetadata, reflector: CompileReflector, - bindingParser: BindingParser) { - const name = identifierName(directive.type)!; - name || error(`Cannot resolver the name of ${directive.type}`); - - const definitionField = outputCtx.constantPool.propertyNameOf(DefinitionKind.Directive); - - const meta = directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector); - const res = compileDirectiveFromMetadata(meta, outputCtx.constantPool, bindingParser); - const factoryRes = compileFactoryFunction( - {...meta, injectFn: R3.directiveInject, target: R3FactoryTarget.Directive}); - const ngFactoryDefStatement = new o.ClassStmt( - name, null, - [new o.ClassField('ɵfac', o.INFERRED_TYPE, [o.StmtModifier.Static], factoryRes.factory)], [], - new o.ClassMethod(null, [], []), []); - const directiveDefStatement = new o.ClassStmt( - name, null, - [new o.ClassField(definitionField, o.INFERRED_TYPE, [o.StmtModifier.Static], res.expression)], - [], new o.ClassMethod(null, [], []), []); - - // Create the partial class to be merged with the actual class. - outputCtx.statements.push(ngFactoryDefStatement, directiveDefStatement); -} - -/** - * A wrapper around `compileComponent` which depends on render2 global analysis data as its input - * instead of the `R3DirectiveMetadata`. - * - * `R3ComponentMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected - * information. - */ -export function compileComponentFromRender2( - outputCtx: OutputContext, component: CompileDirectiveMetadata, render3Ast: Render3ParseResult, - reflector: CompileReflector, bindingParser: BindingParser, directiveTypeBySel: Map, - pipeTypeByName: Map) { - const name = identifierName(component.type)!; - name || error(`Cannot resolver the name of ${component.type}`); - - const definitionField = outputCtx.constantPool.propertyNameOf(DefinitionKind.Component); - - const summary = component.toSummary(); - - // Compute the R3ComponentMetadata from the CompileDirectiveMetadata - const meta: R3ComponentMetadata = { - ...directiveMetadataFromGlobalMetadata(component, outputCtx, reflector), - selector: component.selector, - template: {nodes: render3Ast.nodes, ngContentSelectors: render3Ast.ngContentSelectors}, - directives: [], - pipes: typeMapToExpressionMap(pipeTypeByName, outputCtx), - viewQueries: queriesFromGlobalMetadata(component.viewQueries, outputCtx), - declarationListEmitMode: DeclarationListEmitMode.Direct, - styles: (summary.template && summary.template.styles) || EMPTY_ARRAY, - encapsulation: - (summary.template && summary.template.encapsulation) || core.ViewEncapsulation.Emulated, - interpolation: DEFAULT_INTERPOLATION_CONFIG, - animations: null, - viewProviders: - component.viewProviders.length > 0 ? new o.WrappedNodeExpr(component.viewProviders) : null, - relativeContextFilePath: '', - i18nUseExternalIds: true, - }; - const res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser); - const factoryRes = compileFactoryFunction( - {...meta, injectFn: R3.directiveInject, target: R3FactoryTarget.Directive}); - const ngFactoryDefStatement = new o.ClassStmt( - name, null, - [new o.ClassField('ɵfac', o.INFERRED_TYPE, [o.StmtModifier.Static], factoryRes.factory)], [], - new o.ClassMethod(null, [], []), []); - const componentDefStatement = new o.ClassStmt( - name, null, - [new o.ClassField(definitionField, o.INFERRED_TYPE, [o.StmtModifier.Static], res.expression)], - [], new o.ClassMethod(null, [], []), []); - - // Create the partial class to be merged with the actual class. - outputCtx.statements.push(ngFactoryDefStatement, componentDefStatement); -} - -/** - * Compute `R3DirectiveMetadata` given `CompileDirectiveMetadata` and a `CompileReflector`. - */ -function directiveMetadataFromGlobalMetadata( - directive: CompileDirectiveMetadata, outputCtx: OutputContext, - reflector: CompileReflector): R3DirectiveMetadata { - // The global-analysis based Ivy mode in ngc is no longer utilized/supported. - throw new Error('unsupported'); -} - -/** - * Convert `CompileQueryMetadata` into `R3QueryMetadata`. - */ -function queriesFromGlobalMetadata( - queries: CompileQueryMetadata[], outputCtx: OutputContext): R3QueryMetadata[] { - return queries.map(query => { - let read: o.Expression|null = null; - if (query.read && query.read.identifier) { - read = outputCtx.importExpr(query.read.identifier.reference); - } - return { - propertyName: query.propertyName, - first: query.first, - predicate: selectorsFromGlobalMetadata(query.selectors, outputCtx), - descendants: query.descendants, - read, - emitDistinctChangesOnly: !!query.emitDistinctChangesOnly, - static: !!query.static - }; - }); -} - -/** - * Convert `CompileTokenMetadata` for query selectors into either an expression for a predicate - * type, or a list of string predicates. - */ -function selectorsFromGlobalMetadata( - selectors: CompileTokenMetadata[], outputCtx: OutputContext): o.Expression|string[] { - if (selectors.length > 1 || (selectors.length == 1 && selectors[0].value)) { - const selectorStrings = selectors.map(value => value.value as string); - selectorStrings.some(value => !value) && - error('Found a type among the string selectors expected'); - return outputCtx.constantPool.getConstLiteral( - o.literalArr(selectorStrings.map(value => o.literal(value)))); - } - - if (selectors.length == 1) { - const first = selectors[0]; - if (first.identifier) { - return outputCtx.importExpr(first.identifier.reference); - } - } - - error('Unexpected query form'); -} - function prepareQueryParams(query: R3QueryMetadata, constantPool: ConstantPool): o.Expression[] { const parameters = [getQueryPredicate(query, constantPool), o.literal(toQueryFlags(query))]; if (query.read) { @@ -865,13 +718,6 @@ function metadataAsSummary(meta: R3HostMetadata): CompileDirectiveSummary { } -function typeMapToExpressionMap( - map: Map, outputCtx: OutputContext): Map { - // Convert each map entry into another entry where the value is an expression importing the type. - const entries = Array.from(map).map( - ([key, type]): [string, o.Expression] => [key, outputCtx.importExpr(type)]); - return new Map(entries); -} const HOST_REG_EXP = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/; // Represents the groups in the above regex.