feat(compiler-cli): support for partial compilation of components (#39707)

This commit implements partial compilation of components, together with
linking the partial declaration into its full AOT output.

This commit does not yet enable accurate source maps into external
templates. This requires additional work to account for escape sequences
which is non-trivial. Inline templates that were represented using a
string or template literal are transplated into the partial declaration
output, so their source maps should be accurate. Note, however, that
the accuracy of source maps is not currently verified in tests; this is
also left as future work.

The golden files of partial compilation output have been updated to
reflect the generated code for components. Please note that the current
output should not yet be considered stable.

PR Close #39707
This commit is contained in:
JoostK
2020-11-16 18:24:37 +01:00
committed by Andrew Kushnir
parent f6be161a3c
commit e75244ec00
23 changed files with 583 additions and 135 deletions
@@ -18,7 +18,7 @@ export const NO_STATEMENTS: Readonly<any[]> = [] as const;
* This class is responsible for linking all the partial declarations found in a single file.
*/
export class FileLinker<TConstantScope, TStatement, TExpression> {
private linkerSelector = new PartialLinkerSelector<TExpression>();
private linkerSelector = new PartialLinkerSelector<TExpression>(this.linkerEnvironment.options);
private emitScopes = new Map<TConstantScope, EmitScope<TStatement, TExpression>>();
constructor(
@@ -5,20 +5,182 @@
* 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 {ConstantPool} from '@angular/compiler';
import {compileComponentFromMetadata, ConstantPool, DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig, makeBindingParser, parseTemplate, R3ComponentMetadata, R3UsedDirectiveMetadata} from '@angular/compiler';
import {ChangeDetectionStrategy, ViewEncapsulation} from '@angular/compiler/src/core';
import * as o from '@angular/compiler/src/output/output_ast';
import {AstObject} from '../../ast/ast_value';
import {Range} from '../../ast/ast_host';
import {AstObject, AstValue} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkerOptions} from '../linker_options';
import {toR3DirectiveMeta} from './partial_directive_linker_1';
import {PartialLinker} from './partial_linker';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareComponent()` call expressions.
*/
export class PartialComponentLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
constructor(private readonly options: LinkerOptions) {}
linkPartialDeclaration(
sourceUrl: string, code: string, constantPool: ConstantPool,
metaObj: AstObject<TExpression>): o.Expression {
throw new Error('Not implemented.');
const meta = toR3ComponentMeta(metaObj, code, sourceUrl, this.options);
const def = compileComponentFromMetadata(meta, constantPool, makeBindingParser());
return def.expression;
}
}
/**
* This function derives the `R3ComponentMetadata` from the provided AST object.
*/
export function toR3ComponentMeta<TExpression>(
metaObj: AstObject<TExpression>, code: string, sourceUrl: string,
options: LinkerOptions): R3ComponentMetadata {
let interpolation = DEFAULT_INTERPOLATION_CONFIG;
if (metaObj.has('interpolation')) {
interpolation = InterpolationConfig.fromArray(
metaObj.getArray('interpolation').map(entry => entry.getString()) as [string, string]);
}
const templateObj = metaObj.getObject('template');
const templateSource = templateObj.getValue('source');
const range = getTemplateRange(templateSource, code);
const isInline = templateObj.getBoolean('isInline');
// We always normalize line endings if the template is inline.
const i18nNormalizeLineEndingsInICUs = isInline || options.i18nNormalizeLineEndingsInICUs;
const template = parseTemplate(code, sourceUrl, {
escapedString: true,
interpolationConfig: interpolation,
range,
enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat,
preserveWhitespaces:
metaObj.has('preserveWhitespaces') ? metaObj.getBoolean('preserveWhitespaces') : false,
i18nNormalizeLineEndingsInICUs,
isInline,
});
if (template.errors !== null) {
const errors = template.errors.map(err => err.toString()).join('\n');
throw new FatalLinkerError(
templateSource.expression, `Errors found in the template:\n${errors}`);
}
let wrapDirectivesAndPipesInClosure = false;
const directives: R3UsedDirectiveMetadata[] = metaObj.has('directives') ?
metaObj.getArray('directives').map(directive => {
const directiveExpr = directive.getObject();
const type = directiveExpr.getValue('type');
const selector = directiveExpr.getString('selector');
let typeExpr = type.getOpaque();
if (type.isFunction()) {
typeExpr = type.getFunctionReturnValue().getOpaque();
wrapDirectivesAndPipesInClosure = true;
}
return {
type: typeExpr,
selector: selector,
inputs: directiveExpr.has('inputs') ?
directiveExpr.getArray('inputs').map(input => input.getString()) :
[],
outputs: directiveExpr.has('outputs') ?
directiveExpr.getArray('outputs').map(input => input.getString()) :
[],
exportAs: directiveExpr.has('exportAs') ?
directiveExpr.getArray('exportAs').map(exportAs => exportAs.getString()) :
null,
};
}) :
[];
const pipes = metaObj.has('pipes') ? metaObj.getObject('pipes').toMap(value => {
if (value.isFunction()) {
wrapDirectivesAndPipesInClosure = true;
return value.getFunctionReturnValue().getOpaque();
} else {
return value.getOpaque();
}
}) :
new Map<string, o.Expression>();
return {
...toR3DirectiveMeta(metaObj, code, sourceUrl),
viewProviders: metaObj.has('viewProviders') ? metaObj.getOpaque('viewProviders') : null,
template: {
nodes: template.nodes,
ngContentSelectors: template.ngContentSelectors,
},
wrapDirectivesAndPipesInClosure,
styles: metaObj.has('styles') ? metaObj.getArray('styles').map(entry => entry.getString()) : [],
encapsulation: metaObj.has('encapsulation') ?
parseEncapsulation(metaObj.getValue('encapsulation')) :
ViewEncapsulation.Emulated,
interpolation,
changeDetection: metaObj.has('changeDetection') ?
parseChangeDetectionStrategy(metaObj.getValue('changeDetection')) :
ChangeDetectionStrategy.Default,
animations: metaObj.has('animations') ? metaObj.getOpaque('animations') : null,
relativeContextFilePath: sourceUrl,
i18nUseExternalIds: options.i18nUseExternalIds,
pipes,
directives,
};
}
/**
* Determines the `ViewEncapsulation` mode from the AST value's symbol name.
*/
function parseEncapsulation<TExpression>(encapsulation: AstValue<TExpression>): ViewEncapsulation {
const symbolName = encapsulation.getSymbolName();
if (symbolName === null) {
throw new FatalLinkerError(
encapsulation.expression, 'Expected encapsulation to have a symbol name');
}
const enumValue = ViewEncapsulation[symbolName as keyof typeof ViewEncapsulation];
if (enumValue === undefined) {
throw new FatalLinkerError(encapsulation.expression, 'Unsupported encapsulation');
}
return enumValue;
}
/**
* Determines the `ChangeDetectionStrategy` from the AST value's symbol name.
*/
function parseChangeDetectionStrategy<TExpression>(changeDetectionStrategy: AstValue<TExpression>):
ChangeDetectionStrategy {
const symbolName = changeDetectionStrategy.getSymbolName();
if (symbolName === null) {
throw new FatalLinkerError(
changeDetectionStrategy.expression,
'Expected change detection strategy to have a symbol name');
}
const enumValue = ChangeDetectionStrategy[symbolName as keyof typeof ChangeDetectionStrategy];
if (enumValue === undefined) {
throw new FatalLinkerError(
changeDetectionStrategy.expression, 'Unsupported change detection strategy');
}
return enumValue;
}
/**
* Update the range to remove the start and end chars, which should be quotes around the template.
*/
function getTemplateRange<TExpression>(templateNode: AstValue<TExpression>, code: string): Range {
const {startPos, endPos, startLine, startCol} = templateNode.getRange();
if (!/["'`]/.test(code[startPos]) || code[startPos] !== code[endPos - 1]) {
throw new FatalLinkerError(
templateNode.expression,
`Expected the template string to be wrapped in quotes but got: ${
code.substring(startPos, endPos)}`);
}
return {
startPos: startPos + 1,
endPos: endPos - 1,
startLine,
startCol: startCol + 1,
};
}
@@ -5,6 +5,8 @@
* 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 {LinkerOptions} from '../linker_options';
import {PartialComponentLinkerVersion1} from './partial_component_linker_1';
import {PartialDirectiveLinkerVersion1} from './partial_directive_linker_1';
import {PartialLinker} from './partial_linker';
@@ -15,10 +17,12 @@ export class PartialLinkerSelector<TExpression> {
1: new PartialDirectiveLinkerVersion1(),
},
'ɵɵngDeclareComponent': {
1: new PartialComponentLinkerVersion1(),
1: new PartialComponentLinkerVersion1(this.options),
},
};
constructor(private options: LinkerOptions) {}
/**
* Returns true if there are `PartialLinker` classes that can handle functions with this name.
*/
@@ -6,15 +6,22 @@
* found in the LICENSE file at https://angular.io/license
*/
import {LinkerOptions} from '../../..';
import {PartialComponentLinkerVersion1} from '../../../src/file_linker/partial_linkers/partial_component_linker_1';
import {PartialDirectiveLinkerVersion1} from '../../../src/file_linker/partial_linkers/partial_directive_linker_1';
import {PartialLinkerSelector} from '../../../src/file_linker/partial_linkers/partial_linker_selector';
describe('PartialLinkerSelector', () => {
const options: LinkerOptions = {
i18nNormalizeLineEndingsInICUs: true,
enableI18nLegacyMessageIdFormat: false,
i18nUseExternalIds: false,
};
describe('supportsDeclaration()', () => {
it('should return true if there is at least one linker that matches the given function name',
() => {
const selector = new PartialLinkerSelector();
const selector = new PartialLinkerSelector(options);
expect(selector.supportsDeclaration('ɵɵngDeclareDirective')).toBe(true);
expect(selector.supportsDeclaration('ɵɵngDeclareComponent')).toBe(true);
expect(selector.supportsDeclaration('$foo')).toBe(false);
@@ -23,7 +30,7 @@ describe('PartialLinkerSelector', () => {
describe('getLinker()', () => {
it('should return the linker that matches the name and version number', () => {
const selector = new PartialLinkerSelector();
const selector = new PartialLinkerSelector(options);
expect(selector.getLinker('ɵɵngDeclareDirective', 1))
.toBeInstanceOf(PartialDirectiveLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclareComponent', 1))
@@ -31,7 +38,7 @@ describe('PartialLinkerSelector', () => {
});
it('should throw an error if there is no linker that matches the given name or version', () => {
const selector = new PartialLinkerSelector();
const selector = new PartialLinkerSelector(options);
expect(() => selector.getLinker('$foo', 1))
.toThrowError('Unknown partial declaration function $foo.');
expect(() => selector.getLinker('ɵɵngDeclareDirective', 2))