Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions goldens/public-api/core/core.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -694,9 +694,6 @@ export declare interface ɵɵInjectableDef<T> {
/** @codeGenApi */
export declare function ɵɵinjectAttribute(attrNameToInject: string): string | null;

/** @codeGenApi */
export declare function ɵɵinjectPipeChangeDetectorRef(flags?: InjectFlags): ChangeDetectorRef | null;

export declare const PACKAGE_ROOT_URL: InjectionToken<string>;

export declare interface Pipe {
Expand Down
6 changes: 3 additions & 3 deletions goldens/size-tracking/aio-payloads.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
"master": {
"uncompressed": {
"runtime-es2015": 3033,
"main-es2015": 452165,
"polyfills-es2015": 52493
"main-es2015": 451600,
"polyfills-es2015": 52215
Comment on lines 15 to 16

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this PR actually decreases the payload size of angular.io, but not by as much is it appears here since master was already a bit lower than the previous recorded values:

file golden master PR diff (%)
main 452165 451671 451600 -71 (-0.01%)
polyfills 52493 52215 52215 0 (0%)

@petebacondarwin petebacondarwin Mar 19, 2021 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any pipe that has non-optional injectable dependencies will have a slightly larger footprint since the InjectFlags.ForPipe value (16) must be added as an extra argument, thus adding 3 characters to the injection instruction per dependency.
It is worth noting that many pipes do not actually inject anything. A quick survey of pipes in angular/angular gives 7 pipes that inject dependencies:

Pipe Deps
async 1
date 1
i18nPlural 1
keyvalue 1
number 1
percent 1
currency 2

}
}
},
Expand All @@ -26,4 +26,4 @@
}
}
}
}
}
4 changes: 2 additions & 2 deletions integration/ngcc/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ assertSucceeded "Expected 'ngcc' to log 'Compiling'."


# Did it generate a base factory call for synthesized constructors correctly?
grep "const ɵMatTable_BaseFactory = /\*@__PURE__\*/ ɵngcc0.ɵɵgetInheritedFactory(MatTable);" node_modules/@angular/material/esm2015/table/table.js
grep "/\*@__PURE__\*/ function () { let ɵMatTable_BaseFactory; return function MatTable_Factory(t) { return (ɵMatTable_BaseFactory || (ɵMatTable_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(MatTable)))(t || MatTable); }; }();" node_modules/@angular/material/esm2015/table/table.js
assertSucceeded "Expected 'ngcc' to generate a base factory for 'MatTable' in '@angular/material' (esm2015)."

grep "var ɵMatTable_BaseFactory = /\*@__PURE__\*/ ɵngcc0.ɵɵgetInheritedFactory(MatTable);" node_modules/@angular/material/esm5/table/table.js
grep "/\*@__PURE__\*/ function () { var ɵMatTable_BaseFactory; return function MatTable_Factory(t) { return (ɵMatTable_BaseFactory || (ɵMatTable_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(MatTable)))(t || MatTable); }; }();" node_modules/@angular/material/esm5/table/table.js
assertSucceeded "Expected 'ngcc' to generate a base factory for 'MatTable' in '@angular/material' (esm5)."


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* @license
* Copyright Google LLC 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 {compileFactoryFunction, ConstantPool, FactoryTarget, R3DeclareDependencyMetadata, R3DeclareFactoryMetadata, R3DependencyMetadata, R3FactoryMetadata, R3PartialDeclaration} from '@angular/compiler';
import * as o from '@angular/compiler/src/output/output_ast';

import {AstObject} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';

import {PartialLinker} from './partial_linker';
import {parseEnum, wrapReference} from './util';

/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareFactory()` call expressions.
*/
export class PartialFactoryLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>): o.Expression {
const meta = toR3FactoryMeta(metaObj);
const def = compileFactoryFunction(meta);
return def.expression;
}
}

/**
* Derives the `R3FactoryMetadata` structure from the AST object.
*/
export function toR3FactoryMeta<TExpression>(
metaObj: AstObject<R3DeclareFactoryMetadata, TExpression>): R3FactoryMetadata {
const typeExpr = metaObj.getValue('type');
const typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new FatalLinkerError(
typeExpr.expression, 'Unsupported type, its name could not be determined');
}

return {
name: typeName,
type: wrapReference(typeExpr.getOpaque()),
internalType: metaObj.getOpaque('type'),
typeArgumentCount: 0,
target: parseEnum(metaObj.getValue('target'), FactoryTarget),
deps: getDeps(metaObj, 'deps'),
};
}

function getDeps<TExpression>(
metaObj: AstObject<R3DeclareFactoryMetadata, TExpression>,
propName: keyof R3DeclareFactoryMetadata): R3DependencyMetadata[]|null|'invalid' {
if (!metaObj.has(propName)) {
return null;
}
const deps = metaObj.getValue(propName);
if (deps.isArray()) {
return deps.getArray().map(dep => getDep(dep.getObject()));
}
if (deps.isString()) {
return 'invalid';
}
return null;
}

function getDep<TExpression>(depObj: AstObject<R3DeclareDependencyMetadata, TExpression>):
R3DependencyMetadata {
const isAttribute = depObj.has('attribute') && depObj.getBoolean('attribute');
const token = depObj.getOpaque('token');
// Normally `attribute` is a string literal and so its `attributeNameType` is the same string
// literal. If the `attribute` is some other expression, the `attributeNameType` would be the
// `unknown` type. It is not possible to generate this when linking, since it only deals with JS
// and not typings. When linking the existence of the `attributeNameType` only acts as a marker to
// change the injection instruction that is generated, so we just pass the literal string
// `"unknown"`.
const attributeNameType = isAttribute ? o.literal('unknown') : null;
const dep: R3DependencyMetadata = {
token,
attributeNameType,
host: depObj.has('host') && depObj.getBoolean('host'),
optional: depObj.has('optional') && depObj.getBoolean('optional'),
self: depObj.has('self') && depObj.getBoolean('self'),
skipSelf: depObj.has('skipSelf') && depObj.getBoolean('skipSelf'),
};
return dep;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,21 @@ import {LinkerEnvironment} from '../linker_environment';

import {PartialComponentLinkerVersion1} from './partial_component_linker_1';
import {PartialDirectiveLinkerVersion1} from './partial_directive_linker_1';
import {PartialFactoryLinkerVersion1} from './partial_factory_linker_1';
import {PartialInjectorLinkerVersion1} from './partial_injector_linker_1';
import {PartialLinker} from './partial_linker';
import {PartialNgModuleLinkerVersion1} from './partial_ng_module_linker_1';
import {PartialPipeLinkerVersion1} from './partial_pipe_linker_1';

export const ɵɵngDeclareDirective = 'ɵɵngDeclareDirective';
export const ɵɵngDeclareComponent = 'ɵɵngDeclareComponent';
export const ɵɵngDeclareFactory = 'ɵɵngDeclareFactory';
export const ɵɵngDeclareInjector = 'ɵɵngDeclareInjector';
export const ɵɵngDeclareNgModule = 'ɵɵngDeclareNgModule';
export const ɵɵngDeclarePipe = 'ɵɵngDeclarePipe';
export const declarationFunctions = [
ɵɵngDeclareDirective, ɵɵngDeclareComponent, ɵɵngDeclareInjector, ɵɵngDeclareNgModule,
ɵɵngDeclarePipe
ɵɵngDeclareDirective, ɵɵngDeclareComponent, ɵɵngDeclareFactory, ɵɵngDeclareInjector,
ɵɵngDeclareNgModule, ɵɵngDeclarePipe
];

interface LinkerRange<TExpression> {
Expand Down Expand Up @@ -90,6 +92,7 @@ export class PartialLinkerSelector<TStatement, TExpression> {
const partialComponentLinkerVersion1 = new PartialComponentLinkerVersion1(
environment, createGetSourceFile(sourceUrl, code, environment.sourceFileLoader), sourceUrl,
code);
const partialFactoryLinkerVersion1 = new PartialFactoryLinkerVersion1();
const partialInjectorLinkerVersion1 = new PartialInjectorLinkerVersion1();
const partialNgModuleLinkerVersion1 =
new PartialNgModuleLinkerVersion1(environment.options.linkerJitMode);
Expand All @@ -104,6 +107,10 @@ export class PartialLinkerSelector<TStatement, TExpression> {
{range: '0.0.0-PLACEHOLDER', linker: partialComponentLinkerVersion1},
{range: '>=11.1.0-next.1', linker: partialComponentLinkerVersion1},
]);
linkers.set(ɵɵngDeclareFactory, [
{range: '0.0.0-PLACEHOLDER', linker: partialFactoryLinkerVersion1},
{range: '>=11.1.0-next.1', linker: partialFactoryLinkerVersion1},
]);
linkers.set(ɵɵngDeclareInjector, [
{range: '0.0.0-PLACEHOLDER', linker: partialInjectorLinkerVersion1},
{range: '>=11.1.0-next.1', linker: partialInjectorLinkerVersion1},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,25 @@
*/
import {R3Reference} from '@angular/compiler';
import * as o from '@angular/compiler/src/output/output_ast';
import {AstValue} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';

export function wrapReference<TExpression>(wrapped: o.WrappedNodeExpr<TExpression>): R3Reference {
return {value: wrapped, type: wrapped};
}

/**
* Parses the value of an enum from the AST value's symbol name.
*/
export function parseEnum<TExpression, TEnum>(
Comment thread
petebacondarwin marked this conversation as resolved.
Resolved
value: AstValue<unknown, TExpression>, Enum: TEnum): TEnum[keyof TEnum] {
const symbolName = value.getSymbolName();
if (symbolName === null) {
throw new FatalLinkerError(value.expression, 'Expected value to have a symbol name');
}
const enumValue = Enum[symbolName as keyof typeof Enum];
if (enumValue === undefined) {
throw new FatalLinkerError(value.expression, `Unsupported enum value for ${Enum}`);
}
return enumValue;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {TypeScriptAstHost} from '../../../src/ast/typescript/typescript_ast_host
import {LinkerEnvironment} from '../../../src/file_linker/linker_environment';
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 {PartialFactoryLinkerVersion1} from '../../../src/file_linker/partial_linkers/partial_factory_linker_1';
import {PartialInjectorLinkerVersion1} from '../../../src/file_linker/partial_linkers/partial_injector_linker_1';
import {PartialLinkerSelector} from '../../../src/file_linker/partial_linkers/partial_linker_selector';
import {PartialNgModuleLinkerVersion1} from '../../../src/file_linker/partial_linkers/partial_ng_module_linker_1';
Expand All @@ -41,6 +42,9 @@ describe('PartialLinkerSelector', () => {
environment, fs.resolve('/some/path/to/file.js'), 'some file contents');
expect(selector.supportsDeclaration('ɵɵngDeclareDirective')).toBe(true);
expect(selector.supportsDeclaration('ɵɵngDeclareComponent')).toBe(true);
expect(selector.supportsDeclaration('ɵɵngDeclareFactory')).toBe(true);
expect(selector.supportsDeclaration('ɵɵngDeclareInjector')).toBe(true);
expect(selector.supportsDeclaration('ɵɵngDeclareNgModule')).toBe(true);
expect(selector.supportsDeclaration('ɵɵngDeclarePipe')).toBe(true);
expect(selector.supportsDeclaration('$foo')).toBe(false);
});
Expand All @@ -60,12 +64,14 @@ describe('PartialLinkerSelector', () => {
.toBeInstanceOf(PartialDirectiveLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclareComponent', '0.0.0-PLACEHOLDER'))
.toBeInstanceOf(PartialComponentLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclarePipe', '0.0.0-PLACEHOLDER'))
.toBeInstanceOf(PartialPipeLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclareFactory', '0.0.0-PLACEHOLDER'))
.toBeInstanceOf(PartialFactoryLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclareInjector', '0.0.0-PLACEHOLDER'))
.toBeInstanceOf(PartialInjectorLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclareNgModule', '0.0.0-PLACEHOLDER'))
.toBeInstanceOf(PartialNgModuleLinkerVersion1);
expect(selector.getLinker('ɵɵngDeclarePipe', '0.0.0-PLACEHOLDER'))
.toBeInstanceOf(PartialPipeLinkerVersion1);
});

it('should return the linker that matches the name and valid full version', () => {
Expand Down
6 changes: 3 additions & 3 deletions packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ runInEachFileSystem(() => {
expect(jsContents).toContain('__spreadArray([], __read(arguments))');
expect(jsContents)
.toContain(
'var ɵSubClass_BaseFactory = /*@__PURE__*/ ɵngcc0.ɵɵgetInheritedFactory(SubClass);');
'var ɵSubClass_BaseFactory; return function SubClass_Factory(t) { return (ɵSubClass_BaseFactory || (ɵSubClass_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(SubClass)))(t || SubClass); };');
});

it(`should be able to detect synthesized constructors in ES5 with downlevelIteration enabled (emitted helpers)`,
Expand Down Expand Up @@ -423,7 +423,7 @@ runInEachFileSystem(() => {
expect(jsContents).toContain('__spreadArray([], __read(arguments))');
expect(jsContents)
.toContain(
'var ɵSubClass_BaseFactory = /*@__PURE__*/ ɵngcc0.ɵɵgetInheritedFactory(SubClass);');
'var ɵSubClass_BaseFactory; return function SubClass_Factory(t) { return (ɵSubClass_BaseFactory || (ɵSubClass_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(SubClass)))(t || SubClass); };');
});

it('should not add `const` in ES5 generated code', () => {
Expand Down Expand Up @@ -823,7 +823,7 @@ runInEachFileSystem(() => {
expect(jsContents)
.toContain(
`TestClass.ɵfac = function TestClass_Factory(t) { ` +
`return new (t || TestClass)(ɵngcc0.ɵɵinjectPipeChangeDetectorRef()); };`);
`return new (t || TestClass)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ChangeDetectorRef, 16)); };`);
});

it('should use the correct type name in typings files when an export has a different name in source files',
Expand Down
33 changes: 7 additions & 26 deletions packages/compiler-cli/src/ngtsc/annotations/src/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {compileComponentFromMetadata, compileDeclareComponentFromMetadata, ConstantPool, CssSelector, DeclarationListEmitMode, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, Identifiers, InterpolationConfig, LexerRange, makeBindingParser, ParsedTemplate, ParseSourceFile, parseTemplate, R3CompiledExpression, R3ComponentMetadata, R3FactoryTarget, R3TargetBinder, R3UsedDirectiveMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr} from '@angular/compiler';
import {compileComponentFromMetadata, compileDeclareComponentFromMetadata, ConstantPool, CssSelector, DeclarationListEmitMode, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, FactoryTarget, InterpolationConfig, LexerRange, makeBindingParser, ParsedTemplate, ParseSourceFile, parseTemplate, R3ComponentMetadata, R3FactoryMetadata, R3TargetBinder, R3UsedDirectiveMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr} from '@angular/compiler';
import * as ts from 'typescript';

import {Cycle, CycleAnalyzer, CycleHandlingStrategy} from '../../cycles';
Expand All @@ -29,10 +29,10 @@ import {SubsetOfKeys} from '../../util/src/typescript';
import {ResourceLoader} from './api';
import {createValueHasWrongTypeError, getDirectiveDiagnostics, getProviderDiagnostics} from './diagnostics';
import {DirectiveSymbol, extractDirectiveMetadata, parseFieldArrayValue} from './directive';
import {compileNgFactoryDefField} from './factory';
import {compileDeclareFactory, compileNgFactoryDefField} from './factory';
import {generateSetClassMetadataCall} from './metadata';
import {NgModuleSymbol} from './ng_module';
import {findAngularDecorator, isAngularCoreReference, isExpressionForwardReference, readBaseClass, resolveProvidersRequiringFactory, unwrapExpression, wrapFunctionExpressionsInParens} from './util';
import {compileResults, findAngularDecorator, isAngularCoreReference, isExpressionForwardReference, readBaseClass, resolveProvidersRequiringFactory, toFactoryMetadata, unwrapExpression, wrapFunctionExpressionsInParens} from './util';

const EMPTY_MAP = new Map<string, Expression>();
const EMPTY_ARRAY: any[] = [];
Expand Down Expand Up @@ -833,8 +833,9 @@ export class ComponentDecoratorHandler implements
return [];
}
const meta: R3ComponentMetadata = {...analysis.meta, ...resolution};
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
return this.compileComponent(analysis, def);
return compileResults(fac, def, analysis.metadataStmt, 'ɵcmp');
}

compilePartial(
Expand All @@ -844,29 +845,9 @@ export class ComponentDecoratorHandler implements
return [];
}
const meta: R3ComponentMetadata = {...analysis.meta, ...resolution};
const fac = compileDeclareFactory(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileDeclareComponentFromMetadata(meta, analysis.template);
return this.compileComponent(analysis, def);
}

private compileComponent(
analysis: Readonly<ComponentAnalysisData>,
{expression: initializer, statements, type}: R3CompiledExpression): CompileResult[] {
const factoryRes = compileNgFactoryDefField({
...analysis.meta,
injectFn: Identifiers.directiveInject,
target: R3FactoryTarget.Component,
});
if (analysis.metadataStmt !== null) {
factoryRes.statements.push(analysis.metadataStmt);
}
return [
factoryRes, {
name: 'ɵcmp',
initializer,
statements,
type,
}
];
return compileResults(fac, def, analysis.metadataStmt, 'ɵcmp');
}

private _resolveLiteral(decorator: Decorator): ts.ObjectLiteralExpression {
Expand Down
Loading