fix(ivy): reuse default imports in type-to-value references (#29266)
This fixes an issue with commitb6f6b117
. 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 inb6f6b117
) 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:

committed by
Kara Erickson

parent
940fbf796c
commit
ccb70e1c64
@ -9,7 +9,6 @@ ts_library(
|
||||
"//packages:types",
|
||||
"//packages/compiler",
|
||||
"//packages/compiler-cli/src/ngtsc/imports",
|
||||
"//packages/compiler-cli/src/ngtsc/reflection",
|
||||
"//packages/compiler-cli/src/ngtsc/util",
|
||||
"@npm//typescript",
|
||||
],
|
||||
|
@ -9,8 +9,7 @@
|
||||
import {ArrayType, AssertNotNull, BinaryOperator, BinaryOperatorExpr, BuiltinType, BuiltinTypeName, CastExpr, ClassStmt, CommaExpr, CommentStmt, ConditionalExpr, DeclareFunctionStmt, DeclareVarStmt, Expression, ExpressionStatement, ExpressionType, ExpressionVisitor, ExternalExpr, ExternalReference, FunctionExpr, IfStmt, InstantiateExpr, InvokeFunctionExpr, InvokeMethodExpr, JSDocCommentStmt, LiteralArrayExpr, LiteralExpr, LiteralMapExpr, MapType, NotExpr, ReadKeyExpr, ReadPropExpr, ReadVarExpr, ReturnStatement, Statement, StatementVisitor, StmtModifier, ThrowStmt, TryCatchStmt, Type, TypeVisitor, TypeofExpr, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr} from '@angular/compiler';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {ImportRewriter, NoopImportRewriter} from '../../imports';
|
||||
import {DEFAULT_EXPORT_NAME} from '../../reflection';
|
||||
import {DefaultImportRecorder, ImportRewriter, NOOP_DEFAULT_IMPORT_RECORDER, NoopImportRewriter} from '../../imports';
|
||||
|
||||
export class Context {
|
||||
constructor(readonly isStatement: boolean) {}
|
||||
@ -40,8 +39,7 @@ const BINARY_OPERATORS = new Map<BinaryOperator, ts.BinaryOperator>([
|
||||
]);
|
||||
|
||||
export class ImportManager {
|
||||
private nonDefaultImports = new Map<string, string>();
|
||||
private defaultImports = new Map<string, string>();
|
||||
private specifierToIdentifier = new Map<string, string>();
|
||||
private nextIndex = 0;
|
||||
|
||||
constructor(protected rewriter: ImportRewriter = new NoopImportRewriter(), private prefix = 'i') {
|
||||
@ -61,47 +59,36 @@ export class ImportManager {
|
||||
|
||||
// If not, this symbol will be imported. Allocate a prefix for the imported module if needed.
|
||||
|
||||
const isDefault = symbol === DEFAULT_EXPORT_NAME;
|
||||
|
||||
// Use a different map for non-default vs default imports. This allows the same module to be
|
||||
// imported in both ways simultaneously.
|
||||
const trackingMap = !isDefault ? this.nonDefaultImports : this.defaultImports;
|
||||
|
||||
if (!trackingMap.has(moduleName)) {
|
||||
trackingMap.set(moduleName, `${this.prefix}${this.nextIndex++}`);
|
||||
if (!this.specifierToIdentifier.has(moduleName)) {
|
||||
this.specifierToIdentifier.set(moduleName, `${this.prefix}${this.nextIndex++}`);
|
||||
}
|
||||
const moduleImport = trackingMap.get(moduleName) !;
|
||||
const moduleImport = this.specifierToIdentifier.get(moduleName) !;
|
||||
|
||||
if (isDefault) {
|
||||
// For an import of a module's default symbol, the moduleImport *is* the name to use to refer
|
||||
// to the import.
|
||||
return {moduleImport: null, symbol: moduleImport};
|
||||
} else {
|
||||
// Non-default imports have a qualifier and the symbol name to import.
|
||||
return {moduleImport, symbol};
|
||||
}
|
||||
return {moduleImport, symbol};
|
||||
}
|
||||
|
||||
getAllImports(contextPath: string): {specifier: string, qualifier: string, isDefault: boolean}[] {
|
||||
const imports: {specifier: string, qualifier: string, isDefault: boolean}[] = [];
|
||||
this.nonDefaultImports.forEach((qualifier, specifier) => {
|
||||
getAllImports(contextPath: string): {specifier: string, qualifier: string}[] {
|
||||
const imports: {specifier: string, qualifier: string}[] = [];
|
||||
this.specifierToIdentifier.forEach((qualifier, specifier) => {
|
||||
specifier = this.rewriter.rewriteSpecifier(specifier, contextPath);
|
||||
imports.push({specifier, qualifier, isDefault: false});
|
||||
});
|
||||
this.defaultImports.forEach((qualifier, specifier) => {
|
||||
specifier = this.rewriter.rewriteSpecifier(specifier, contextPath);
|
||||
imports.push({specifier, qualifier, isDefault: true});
|
||||
imports.push({specifier, qualifier});
|
||||
});
|
||||
return imports;
|
||||
}
|
||||
}
|
||||
|
||||
export function translateExpression(expression: Expression, imports: ImportManager): ts.Expression {
|
||||
return expression.visitExpression(new ExpressionTranslatorVisitor(imports), new Context(false));
|
||||
export function translateExpression(
|
||||
expression: Expression, imports: ImportManager,
|
||||
defaultImportRecorder: DefaultImportRecorder): ts.Expression {
|
||||
return expression.visitExpression(
|
||||
new ExpressionTranslatorVisitor(imports, defaultImportRecorder), new Context(false));
|
||||
}
|
||||
|
||||
export function translateStatement(statement: Statement, imports: ImportManager): ts.Statement {
|
||||
return statement.visitStatement(new ExpressionTranslatorVisitor(imports), new Context(true));
|
||||
export function translateStatement(
|
||||
statement: Statement, imports: ImportManager,
|
||||
defaultImportRecorder: DefaultImportRecorder): ts.Statement {
|
||||
return statement.visitStatement(
|
||||
new ExpressionTranslatorVisitor(imports, defaultImportRecorder), new Context(true));
|
||||
}
|
||||
|
||||
export function translateType(type: Type, imports: ImportManager): ts.TypeNode {
|
||||
@ -110,7 +97,8 @@ export function translateType(type: Type, imports: ImportManager): ts.TypeNode {
|
||||
|
||||
class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor {
|
||||
private externalSourceFiles = new Map<string, ts.SourceMapSource>();
|
||||
constructor(private imports: ImportManager) {}
|
||||
constructor(
|
||||
private imports: ImportManager, private defaultImportRecorder: DefaultImportRecorder) {}
|
||||
|
||||
visitDeclareVarStmt(stmt: DeclareVarStmt, context: Context): ts.VariableStatement {
|
||||
const nodeFlags = stmt.hasModifier(StmtModifier.Final) ? ts.NodeFlags.Const : ts.NodeFlags.None;
|
||||
@ -324,7 +312,12 @@ class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
visitWrappedNodeExpr(ast: WrappedNodeExpr<any>, context: Context): any { return ast.node; }
|
||||
visitWrappedNodeExpr(ast: WrappedNodeExpr<any>, context: Context): any {
|
||||
if (ts.isIdentifier(ast.node)) {
|
||||
this.defaultImportRecorder.recordUsedIdentifier(ast.node);
|
||||
}
|
||||
return ast.node;
|
||||
}
|
||||
|
||||
visitTypeofExpr(ast: TypeofExpr, context: Context): ts.TypeOfExpression {
|
||||
return ts.createTypeOf(ast.expr.visitExpression(this, context));
|
||||
@ -496,7 +489,7 @@ export class TypeTranslatorVisitor implements ExpressionVisitor, TypeVisitor {
|
||||
}
|
||||
|
||||
visitTypeofExpr(ast: TypeofExpr, context: Context): ts.TypeQueryNode {
|
||||
let expr = translateExpression(ast.expr, this.imports);
|
||||
let expr = translateExpression(ast.expr, this.imports, NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
return ts.createTypeQueryNode(expr as ts.Identifier);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user