fix(ivy): reuse default imports in type-to-value references (#29266)

This fixes an issue with commit b6f6b117. In this commit, default imports
processed in a type-to-value conversion were recorded as non-local imports
with a '*' name, and the ImportManager generated a new default import for
them. When transpiled to ES2015 modules, this resulted in the following
correct code:

import i3 from './module';

// somewhere in the file, a value reference of i3:
{type: i3}

However, when the AST with this synthetic import and reference was
transpiled to non-ES2015 modules (for example, to commonjs) an issue
appeared:

var module_1 = require('./module');
{type: i3}

TypeScript renames the imported identifier from i3 to module_1, but doesn't
substitute later references to i3. This is because the import and reference
are both synthetic, and never went through the TypeScript AST step of
"binding" which associates the reference to its import. This association is
important during emit when the identifiers might change.

Synthetic (transformer-added) imports will never be bound properly. The only
possible solution is to reuse the user's original import and the identifier
from it, which will be properly downleveled. The issue with this approach
(which prompted the fix in b6f6b117) is that if the import is only used in a
type position, TypeScript will mark it for deletion in the generated JS,
even though additional non-type usages are added in the transformer. This
again would leave a dangling import.

To work around this, it's necessary for the compiler to keep track of
identifiers that it emits which came from default imports, and tell TS not
to remove those imports during transpilation. A `DefaultImportTracker` class
is implemented to perform this tracking. It implements a
`DefaultImportRecorder` interface, which is used to record two significant
pieces of information:

* when a WrappedNodeExpr is generated which refers to a default imported
  value, the ts.Identifier is associated to the ts.ImportDeclaration via
  the recorder.
* when that WrappedNodeExpr is later emitted as part of the statement /
  expression translators, the fact that the ts.Identifier was used is
  also recorded.

Combined, this tracking gives the `DefaultImportTracker` enough information
to implement another TS transformer, which can recognize default imports
which were used in the output of the Ivy transform and can prevent them
from being elided. This is done by creating a new ts.ImportDeclaration for
the imports with the same ts.ImportClause. A test verifies that this works.

PR Close #29266
This commit is contained in:
Alex Rickabaugh
2019-03-11 16:54:07 -07:00
committed by Kara Erickson
parent 940fbf796c
commit ccb70e1c64
39 changed files with 535 additions and 206 deletions

View File

@ -12,7 +12,7 @@ import * as ts from 'typescript';
import {BaseDefDecoratorHandler, ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, PipeDecoratorHandler, ReferencesRegistry, ResourceLoader} from '../../../ngtsc/annotations';
import {CycleAnalyzer, ImportGraph} from '../../../ngtsc/cycles';
import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, ReferenceEmitter} from '../../../ngtsc/imports';
import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../../ngtsc/imports';
import {PartialEvaluator} from '../../../ngtsc/partial_evaluator';
import {AbsoluteFsPath, LogicalFileSystem} from '../../../ngtsc/path';
import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../../ngtsc/scope';
@ -85,14 +85,18 @@ export class DecorationAnalyzer {
new ComponentDecoratorHandler(
this.reflectionHost, this.evaluator, this.scopeRegistry, this.isCore, this.resourceManager,
this.rootDirs, /* defaultPreserveWhitespaces */ false, /* i18nUseExternalIds */ true,
this.moduleResolver, this.cycleAnalyzer, this.refEmitter),
this.moduleResolver, this.cycleAnalyzer, this.refEmitter, NOOP_DEFAULT_IMPORT_RECORDER),
new DirectiveDecoratorHandler(
this.reflectionHost, this.evaluator, this.scopeRegistry, this.isCore),
new InjectableDecoratorHandler(this.reflectionHost, this.isCore, /* strictCtorDeps */ false),
this.reflectionHost, this.evaluator, this.scopeRegistry, NOOP_DEFAULT_IMPORT_RECORDER,
this.isCore),
new InjectableDecoratorHandler(
this.reflectionHost, NOOP_DEFAULT_IMPORT_RECORDER, this.isCore, /* strictCtorDeps */ false),
new NgModuleDecoratorHandler(
this.reflectionHost, this.evaluator, this.scopeRegistry, this.referencesRegistry,
this.isCore, /* routeAnalyzer */ null, this.refEmitter),
new PipeDecoratorHandler(this.reflectionHost, this.evaluator, this.scopeRegistry, this.isCore),
this.isCore, /* routeAnalyzer */ null, this.refEmitter, NOOP_DEFAULT_IMPORT_RECORDER),
new PipeDecoratorHandler(
this.reflectionHost, this.evaluator, this.scopeRegistry, NOOP_DEFAULT_IMPORT_RECORDER,
this.isCore),
];
constructor(

View File

@ -901,8 +901,9 @@ export class Esm2015ReflectionHost extends TypeScriptReflectionHost implements N
return {
name: getNameText(nameNode),
nameNode,
typeValueReference:
typeExpression !== null ? {local: true as true, expression: typeExpression} : null,
typeValueReference: typeExpression !== null ?
{local: true as true, expression: typeExpression, defaultImportStatement: null} :
null,
typeNode: null, decorators
};
});

View File

@ -25,17 +25,10 @@ export class EsmRenderer extends Renderer {
/**
* Add the imports at the top of the file
*/
addImports(output: MagicString, imports: {
specifier: string; qualifier: string; isDefault: boolean
}[]): void {
addImports(output: MagicString, imports: {specifier: string; qualifier: string;}[]): void {
// The imports get inserted at the very top of the file.
imports.forEach(i => {
if (!i.isDefault) {
output.appendLeft(0, `import * as ${i.qualifier} from '${i.specifier}';\n`);
} else {
output.appendLeft(0, `import ${i.qualifier} from '${i.specifier}';\n`);
}
});
imports.forEach(
i => { output.appendLeft(0, `import * as ${i.qualifier} from '${i.specifier}';\n`); });
}
addExports(output: MagicString, entryPointBasePath: string, exports: ExportInfo[]): void {

View File

@ -13,7 +13,7 @@ import {basename, dirname, relative, resolve} from 'canonical-path';
import {SourceMapConsumer, SourceMapGenerator, RawSourceMap} from 'source-map';
import * as ts from 'typescript';
import {NoopImportRewriter, ImportRewriter, R3SymbolsImportRewriter} from '@angular/compiler-cli/src/ngtsc/imports';
import {NoopImportRewriter, ImportRewriter, R3SymbolsImportRewriter, NOOP_DEFAULT_IMPORT_RECORDER} from '@angular/compiler-cli/src/ngtsc/imports';
import {CompileResult} from '@angular/compiler-cli/src/ngtsc/transform';
import {translateStatement, translateType, ImportManager} from '../../../ngtsc/translator';
import {NgccFlatImportRewriter} from './ngcc_import_rewriter';
@ -245,9 +245,8 @@ export abstract class Renderer {
protected abstract addConstants(output: MagicString, constants: string, file: ts.SourceFile):
void;
protected abstract addImports(
output: MagicString,
imports: {specifier: string, qualifier: string, isDefault: boolean}[]): void;
protected abstract addImports(output: MagicString, imports: {specifier: string,
qualifier: string}[]): void;
protected abstract addExports(
output: MagicString, entryPointBasePath: string, exports: ExportInfo[]): void;
protected abstract addDefinitions(
@ -464,7 +463,8 @@ export function mergeSourceMaps(
export function renderConstantPool(
sourceFile: ts.SourceFile, constantPool: ConstantPool, imports: ImportManager): string {
const printer = ts.createPrinter();
return constantPool.statements.map(stmt => translateStatement(stmt, imports))
return constantPool.statements
.map(stmt => translateStatement(stmt, imports, NOOP_DEFAULT_IMPORT_RECORDER))
.map(stmt => printer.printNode(ts.EmitHint.Unspecified, stmt, sourceFile))
.join('\n');
}
@ -481,12 +481,13 @@ export function renderDefinitions(
sourceFile: ts.SourceFile, compiledClass: CompiledClass, imports: ImportManager): string {
const printer = ts.createPrinter();
const name = (compiledClass.declaration as ts.NamedDeclaration).name !;
const translate = (stmt: Statement) =>
translateStatement(stmt, imports, NOOP_DEFAULT_IMPORT_RECORDER);
const definitions =
compiledClass.compilation
.map(
c => c.statements.map(statement => translateStatement(statement, imports))
.concat(translateStatement(
createAssignmentStatement(name, c.name, c.initializer), imports))
c => c.statements.map(statement => translate(statement))
.concat(translate(createAssignmentStatement(name, c.name, c.initializer)))
.map(
statement =>
printer.printNode(ts.EmitHint.Unspecified, statement, sourceFile))

View File

@ -302,7 +302,8 @@ describe('Fesm2015ReflectionHost [import helper style]', () => {
const ctrDecorators = host.getConstructorParameters(classNode) !;
const identifierOfViewContainerRef = (ctrDecorators[0].typeValueReference !as{
local: true,
expression: ts.Identifier
expression: ts.Identifier,
defaultImportStatement: null,
}).expression;
const expectedDeclarationNode = getDeclaration(

View File

@ -1295,7 +1295,8 @@ describe('Fesm2015ReflectionHost', () => {
const ctrDecorators = host.getConstructorParameters(classNode) !;
const identifierOfViewContainerRef = (ctrDecorators[0].typeValueReference !as{
local: true,
expression: ts.Identifier
expression: ts.Identifier,
defaultImportStatement: null,
}).expression;
const expectedDeclarationNode = getDeclaration(

View File

@ -338,7 +338,8 @@ describe('Esm5ReflectionHost [import helper style]', () => {
const ctrDecorators = host.getConstructorParameters(classNode) !;
const identifierOfViewContainerRef = (ctrDecorators[0].typeValueReference !as{
local: true,
expression: ts.Identifier
expression: ts.Identifier,
defaultImportStatement: null,
}).expression;
const expectedDeclarationNode = getDeclaration(

View File

@ -1276,7 +1276,8 @@ describe('Esm5ReflectionHost', () => {
const ctrDecorators = host.getConstructorParameters(classNode) !;
const identifierOfViewContainerRef = (ctrDecorators[0].typeValueReference !as{
local: true,
expression: ts.Identifier
expression: ts.Identifier,
defaultImportStatement: null,
}).expression;
const expectedDeclarationNode = getDeclaration(

View File

@ -116,23 +116,14 @@ describe('Esm2015Renderer', () => {
const {renderer} = setup(PROGRAM);
const output = new MagicString(PROGRAM.contents);
renderer.addImports(output, [
{specifier: '@angular/core', qualifier: 'i0', isDefault: false},
{specifier: '@angular/common', qualifier: 'i1', isDefault: false}
{specifier: '@angular/core', qualifier: 'i0'},
{specifier: '@angular/common', qualifier: 'i1'}
]);
expect(output.toString()).toContain(`import * as i0 from '@angular/core';
import * as i1 from '@angular/common';
/* A copyright notice */`);
});
it('should insert a default import at the start of the source file', () => {
const {renderer} = setup(PROGRAM);
const output = new MagicString(PROGRAM.contents);
renderer.addImports(output, [
{specifier: 'test', qualifier: 'i0', isDefault: true},
]);
expect(output.toString()).toContain(`import i0 from 'test';`);
});
});
describe('addExports', () => {

View File

@ -153,23 +153,14 @@ describe('Esm5Renderer', () => {
const {renderer} = setup(PROGRAM);
const output = new MagicString(PROGRAM.contents);
renderer.addImports(output, [
{specifier: '@angular/core', qualifier: 'i0', isDefault: false},
{specifier: '@angular/common', qualifier: 'i1', isDefault: false}
{specifier: '@angular/core', qualifier: 'i0'},
{specifier: '@angular/common', qualifier: 'i1'}
]);
expect(output.toString()).toContain(`import * as i0 from '@angular/core';
import * as i1 from '@angular/common';
/* A copyright notice */`);
});
it('should insert a default import at the start of the source file', () => {
const {renderer} = setup(PROGRAM);
const output = new MagicString(PROGRAM.contents);
renderer.addImports(output, [
{specifier: 'test', qualifier: 'i0', isDefault: true},
]);
expect(output.toString()).toContain(`import i0 from 'test';`);
});
});
describe('addExports', () => {

View File

@ -23,8 +23,7 @@ class TestRenderer extends Renderer {
constructor(host: Esm2015ReflectionHost, isCore: boolean, bundle: EntryPointBundle) {
super(host, isCore, bundle, '/src', '/dist');
}
addImports(
output: MagicString, imports: {specifier: string, qualifier: string, isDefault: boolean}[]) {
addImports(output: MagicString, imports: {specifier: string, qualifier: string}[]) {
output.prepend('\n// ADD IMPORTS\n');
}
addExports(output: MagicString, baseEntryPointPath: string, exports: {
@ -172,7 +171,7 @@ A.ngComponentDef = ɵngcc0.ɵdefineComponent({ type: A, selectors: [["a"]], fact
const addImportsSpy = renderer.addImports as jasmine.Spy;
expect(addImportsSpy.calls.first().args[0].toString()).toEqual(RENDERED_CONTENTS);
expect(addImportsSpy.calls.first().args[1]).toEqual([
{specifier: '@angular/core', qualifier: 'ɵngcc0', isDefault: false}
{specifier: '@angular/core', qualifier: 'ɵngcc0'}
]);
});
@ -289,7 +288,7 @@ A.ngDirectiveDef = ɵngcc0.ɵdefineDirective({ type: A, selectors: [["", "a", ""
.toContain(`/*@__PURE__*/ ɵngcc0.setClassMetadata(`);
const addImportsSpy = renderer.addImports as jasmine.Spy;
expect(addImportsSpy.calls.first().args[1]).toEqual([
{specifier: './r3_symbols', qualifier: 'ɵngcc0', isDefault: false}
{specifier: './r3_symbols', qualifier: 'ɵngcc0'}
]);
});
@ -505,9 +504,9 @@ A.ngDirectiveDef = ɵngcc0.ɵdefineDirective({ type: A, selectors: [["", "a", ""
export declare function withProviders8(): (MyModuleWithProviders)&{ngModule:SomeModule};`);
expect(renderer.addImports).toHaveBeenCalledWith(jasmine.any(MagicString), [
{specifier: './module', qualifier: 'ɵngcc0', isDefault: false},
{specifier: '@angular/core', qualifier: 'ɵngcc1', isDefault: false},
{specifier: 'some-library', qualifier: 'ɵngcc2', isDefault: false},
{specifier: './module', qualifier: 'ɵngcc0'},
{specifier: '@angular/core', qualifier: 'ɵngcc1'},
{specifier: 'some-library', qualifier: 'ɵngcc2'},
]);