749 lines
33 KiB
TypeScript
Raw Normal View History

/**
* @license
* Copyright Google Inc. 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 {GeneratedFile} from '@angular/compiler';
import * as ts from 'typescript';
import * as api from '../transformers/api';
import {nocollapseHack} from '../transformers/nocollapse_hack';
import {verifySupportedTypeScriptVersion} from '../typescript_support';
import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, NoopReferencesRegistry, PipeDecoratorHandler, ReferencesRegistry} from './annotations';
import {CycleAnalyzer, ImportGraph} from './cycles';
import {ErrorCode, ngErrorCode} from './diagnostics';
import {FlatIndexGenerator, ReferenceGraph, checkForPrivateExports, findFlatIndexEntryPoint} from './entry_point';
refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921) To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
2019-06-06 20:22:32 +01:00
import {AbsoluteFsPath, LogicalFileSystem, absoluteFrom} from './file_system';
import {AbsoluteModuleStrategy, AliasStrategy, AliasingHost, DefaultImportTracker, FileToModuleAliasingHost, FileToModuleHost, FileToModuleStrategy, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy} from './imports';
import {IncrementalState} from './incremental';
import {IndexedComponent, IndexingContext} from './indexer';
import {generateAnalysis} from './indexer/src/transform';
import {CompoundMetadataReader, CompoundMetadataRegistry, DtsMetadataReader, LocalMetadataRegistry, MetadataReader} from './metadata';
import {PartialEvaluator} from './partial_evaluator';
import {NOOP_PERF_RECORDER, PerfRecorder, PerfTracker} from './perf';
import {TypeScriptReflectionHost} from './reflection';
import {HostResourceLoader} from './resource_loader';
import {NgModuleRouteAnalyzer, entryPointKeyFor} from './routing';
import {ComponentScopeReader, CompoundComponentScopeReader, LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from './scope';
import {FactoryGenerator, FactoryInfo, GeneratedShimsHostWrapper, ShimGenerator, SummaryGenerator, TypeCheckShimGenerator, generatedFactoryTransform} from './shims';
refactor(ivy): obviate the Bazel component of the ivy_switch (#26550) Originally, the ivy_switch mechanism used Bazel genrules to conditionally compile one TS file or another depending on whether ngc or ngtsc was the selected compiler. This was done because we wanted to avoid importing certain modules (and thus pulling them into the build) if Ivy was on or off. This mechanism had a major drawback: ivy_switch became a bottleneck in the import graph, as it both imports from many places in the codebase and is imported by many modules in the codebase. This frequently resulted in cyclic imports which caused issues both with TS and Closure compilation. It turns out ngcc needs both code paths in the bundle to perform the switch during its operation anyway, so import switching was later abandoned. This means that there's no real reason why the ivy_switch mechanism needed to operate at the Bazel level, and for the ivy_switch file to be a bottleneck. This commit removes the Bazel-level ivy_switch mechanism, and introduces an additional TypeScript transform in ngtsc (and the pass-through tsc compiler used for testing JIT) to perform the same operation that ngcc does, and flip the switch during ngtsc compilation. This allows the ivy_switch file to be removed, and the individual switches to be located directly next to their consumers in the codebase, greatly mitigating the circular import issues and making the mechanism much easier to use. As part of this commit, the tag for marking switched variables was changed from __PRE_NGCC__ to __PRE_R3__, since it's no longer just ngcc which flips these tags. Most variables were renamed from R3_* to SWITCH_* as well, since they're referenced mostly in render2 code. Test strategy: existing test coverage is more than sufficient - if this didn't work correctly it would break the hello world and todo apps. PR Close #26550
2018-10-17 15:44:44 -07:00
import {ivySwitchTransform} from './switch';
import {IvyCompilation, declarationTransformFactory, ivyTransformFactory} from './transform';
import {aliasTransformFactory} from './transform/src/alias';
import {TypeCheckContext, TypeCheckingConfig, typeCheckFilePath} from './typecheck';
import {normalizeSeparators} from './util/src/path';
refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921) To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
2019-06-06 20:22:32 +01:00
import {getRootDirs, getSourceFileOrNull, isDtsPath, resolveModuleName} from './util/src/typescript';
export class NgtscProgram implements api.Program {
private tsProgram: ts.Program;
private reuseTsProgram: ts.Program;
private resourceManager: HostResourceLoader;
private compilation: IvyCompilation|undefined = undefined;
private factoryToSourceInfo: Map<string, FactoryInfo>|null = null;
private sourceToFactorySymbols: Map<string, Set<string>>|null = null;
private _coreImportsFrom: ts.SourceFile|null|undefined = undefined;
private _importRewriter: ImportRewriter|undefined = undefined;
private _reflector: TypeScriptReflectionHost|undefined = undefined;
private _isCore: boolean|undefined = undefined;
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
private rootDirs: AbsoluteFsPath[];
private closureCompilerEnabled: boolean;
private entryPoint: ts.SourceFile|null;
private exportReferenceGraph: ReferenceGraph|null = null;
private flatIndexGenerator: FlatIndexGenerator|null = null;
private routeAnalyzer: NgModuleRouteAnalyzer|null = null;
private constructionDiagnostics: ts.Diagnostic[] = [];
private moduleResolver: ModuleResolver;
private cycleAnalyzer: CycleAnalyzer;
private metaReader: MetadataReader|null = null;
feat(ivy): enable re-export of the compilation scope of NgModules privately (#33177) This commit refactors the aliasing system to support multiple different AliasingHost implementations, which control specific aliasing behavior in ngtsc (see the README.md). A new host is introduced, the `PrivateExportAliasingHost`. This solves a longstanding problem in ngtsc regarding support for "monorepo" style private libraries. These are libraries which are compiled separately from the main application, and depended upon through TypeScript path mappings. Such libraries are frequently not in the Angular Package Format and do not have entrypoints, but rather make use of deep import style module specifiers. This can cause issues with ngtsc's ability to import a directive given the module specifier of its NgModule. For example, if the application uses a directive `Foo` from such a library `foo`, the user might write: ```typescript import {FooModule} from 'foo/module'; ``` In this case, foo/module.d.ts is path-mapped into the program. Ordinarily the compiler would see this as an absolute module specifier, and assume that the `Foo` directive can be imported from the same specifier. For such non- APF libraries, this assumption fails. Really `Foo` should be imported from the file which declares it, but there are two problems with this: 1. The compiler would have to reverse the path mapping in order to determine a path-mapped path to the file (maybe foo/dir.d.ts). 2. There is no guarantee that the file containing the directive is path- mapped in the program at all. The compiler would effectively have to "guess" 'foo/dir' as a module specifier, which may or may not be accurate depending on how the library and path mapping are set up. It's strongly desirable that the compiler not break its current invariant that the module specifier given by the user for the NgModule is always the module specifier from which directives/pipes are imported. Thus, for any given NgModule from a particular module specifier, it must always be possible to import any directives/pipes from the same specifier, no matter how it's packaged. To make this possible, when compiling a file containing an NgModule, ngtsc will automatically add re-exports for any directives/pipes not yet exported by the user, with a name of the form: ɵngExportɵModuleNameɵDirectiveName This has several effects: 1. It guarantees anyone depending on the NgModule will be able to import its directives/pipes from the same specifier. 2. It maintains a stable name for the exported symbol that is safe to depend on from code on NPM. Effectively, this private exported name will be a part of the package's .d.ts API, and cannot be changed in a non-breaking fashion. Fixes #29361 FW-1610 #resolve PR Close #33177
2019-10-14 12:03:29 -07:00
private aliasingHost: AliasingHost|null = null;
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
private refEmitter: ReferenceEmitter|null = null;
private fileToModuleHost: FileToModuleHost|null = null;
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
2019-03-11 16:54:07 -07:00
private defaultImportTracker: DefaultImportTracker;
private perfRecorder: PerfRecorder = NOOP_PERF_RECORDER;
private perfTracker: PerfTracker|null = null;
private incrementalState: IncrementalState;
private typeCheckFilePath: AbsoluteFsPath;
private modifiedResourceFiles: Set<string>|null;
constructor(
rootNames: ReadonlyArray<string>, private options: api.CompilerOptions,
private host: api.CompilerHost, oldProgram?: NgtscProgram) {
if (!options.disableTypeScriptVersionCheck) {
verifySupportedTypeScriptVersion();
}
if (shouldEnablePerfTracing(options)) {
this.perfTracker = PerfTracker.zeroedToNow();
this.perfRecorder = this.perfTracker;
}
this.modifiedResourceFiles =
this.host.getModifiedResourceFiles && this.host.getModifiedResourceFiles() || null;
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
this.rootDirs = getRootDirs(host, options);
this.closureCompilerEnabled = !!options.annotateForClosureCompiler;
this.resourceManager = new HostResourceLoader(host, options);
// TODO(alxhub): remove the fallback to allowEmptyCodegenFiles after verifying that the rest of
// our build tooling is no longer relying on it.
const allowEmptyCodegenFiles = options.allowEmptyCodegenFiles || false;
const shouldGenerateFactoryShims = options.generateNgFactoryShims !== undefined ?
options.generateNgFactoryShims :
allowEmptyCodegenFiles;
const shouldGenerateSummaryShims = options.generateNgSummaryShims !== undefined ?
options.generateNgSummaryShims :
allowEmptyCodegenFiles;
refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921) To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
2019-06-06 20:22:32 +01:00
const normalizedRootNames = rootNames.map(n => absoluteFrom(n));
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
if (host.fileNameToModuleName !== undefined) {
this.fileToModuleHost = host as FileToModuleHost;
}
let rootFiles = [...rootNames];
const generators: ShimGenerator[] = [];
let summaryGenerator: SummaryGenerator|null = null;
if (shouldGenerateSummaryShims) {
// Summary generation.
summaryGenerator = SummaryGenerator.forRootFiles(normalizedRootNames);
generators.push(summaryGenerator);
}
if (shouldGenerateFactoryShims) {
// Factory generation.
const factoryGenerator = FactoryGenerator.forRootFiles(normalizedRootNames);
const factoryFileMap = factoryGenerator.factoryFileMap;
this.factoryToSourceInfo = new Map<string, FactoryInfo>();
this.sourceToFactorySymbols = new Map<string, Set<string>>();
factoryFileMap.forEach((sourceFilePath, factoryPath) => {
const moduleSymbolNames = new Set<string>();
this.sourceToFactorySymbols !.set(sourceFilePath, moduleSymbolNames);
this.factoryToSourceInfo !.set(factoryPath, {sourceFilePath, moduleSymbolNames});
});
const factoryFileNames = Array.from(factoryFileMap.keys());
rootFiles.push(...factoryFileNames);
generators.push(factoryGenerator);
}
// Done separately to preserve the order of factory files before summary files in rootFiles.
// TODO(alxhub): validate that this is necessary.
if (shouldGenerateSummaryShims) {
rootFiles.push(...summaryGenerator !.getSummaryFileNames());
}
this.typeCheckFilePath = typeCheckFilePath(this.rootDirs);
generators.push(new TypeCheckShimGenerator(this.typeCheckFilePath));
rootFiles.push(this.typeCheckFilePath);
refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921) To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
2019-06-06 20:22:32 +01:00
let entryPoint: AbsoluteFsPath|null = null;
if (options.flatModuleOutFile != null && options.flatModuleOutFile !== '') {
entryPoint = findFlatIndexEntryPoint(normalizedRootNames);
if (entryPoint === null) {
// This error message talks specifically about having a single .ts file in "files". However
// the actual logic is a bit more permissive. If a single file exists, that will be taken,
// otherwise the highest level (shortest path) "index.ts" file will be used as the flat
// module entry point instead. If neither of these conditions apply, the error below is
// given.
//
// The user is not informed about the "index.ts" option as this behavior is deprecated -
// an explicit entrypoint should always be specified.
this.constructionDiagnostics.push({
category: ts.DiagnosticCategory.Error,
code: ngErrorCode(ErrorCode.CONFIG_FLAT_MODULE_NO_INDEX),
file: undefined,
start: undefined,
length: undefined,
messageText:
'Angular compiler option "flatModuleOutFile" requires one and only one .ts file in the "files" field.',
});
} else {
const flatModuleId = options.flatModuleId || null;
const flatModuleOutFile = normalizeSeparators(options.flatModuleOutFile);
this.flatIndexGenerator =
new FlatIndexGenerator(entryPoint, flatModuleOutFile, flatModuleId);
generators.push(this.flatIndexGenerator);
rootFiles.push(this.flatIndexGenerator.flatIndexPath);
}
}
if (generators.length > 0) {
// FIXME: Remove the any cast once google3 is fully on TS3.6.
this.host = (new GeneratedShimsHostWrapper(host, generators) as any);
}
this.tsProgram =
ts.createProgram(rootFiles, options, this.host, oldProgram && oldProgram.reuseTsProgram);
this.reuseTsProgram = this.tsProgram;
refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921) To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
2019-06-06 20:22:32 +01:00
this.entryPoint = entryPoint !== null ? getSourceFileOrNull(this.tsProgram, entryPoint) : null;
this.moduleResolver = new ModuleResolver(this.tsProgram, options, this.host);
this.cycleAnalyzer = new CycleAnalyzer(new ImportGraph(this.moduleResolver));
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
2019-03-11 16:54:07 -07:00
this.defaultImportTracker = new DefaultImportTracker();
if (oldProgram === undefined) {
this.incrementalState = IncrementalState.fresh();
} else {
this.incrementalState = IncrementalState.reconcile(
oldProgram.reuseTsProgram, this.tsProgram, this.modifiedResourceFiles);
}
}
getTsProgram(): ts.Program { return this.tsProgram; }
getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken|
undefined): ReadonlyArray<ts.Diagnostic> {
return this.tsProgram.getOptionsDiagnostics(cancellationToken);
}
getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken|
feat(ivy): convert all ngtsc diagnostics to ts.Diagnostics (#31952) Historically, the Angular Compiler has produced both native TypeScript diagnostics (called ts.Diagnostics) and its own internal Diagnostic format (called an api.Diagnostic). This was done because TypeScript ts.Diagnostics cannot be produced for files not in the ts.Program, and template type- checking diagnostics are naturally produced for external .html template files. This design isn't optimal for several reasons: 1) Downstream tooling (such as the CLI) must support multiple formats of diagnostics, adding to the maintenance burden. 2) ts.Diagnostics have gotten a lot better in recent releases, with support for suggested changes, highlighting of the code in question, etc. None of these changes have been of any benefit for api.Diagnostics, which have continued to be reported in a very primitive fashion. 3) A future plugin model will not support anything but ts.Diagnostics, so generating api.Diagnostics is a blocker for ngtsc-as-a-plugin. 4) The split complicates both the typings and the testing of ngtsc. To fix this issue, this commit changes template type-checking to produce ts.Diagnostics instead. Instead of reporting a special kind of diagnostic for external template files, errors in a template are always reported in a ts.Diagnostic that highlights the portion of the template which contains the error. When this template text is distinct from the source .ts file (for example, when the template is parsed from an external resource file), additional contextual information links the error back to the originating component. A template error can thus be reported in 3 separate ways, depending on how the template was configured: 1) For inline template strings which can be directly mapped to offsets in the TS code, ts.Diagnostics point to real ranges in the source. This is the case if an inline template is used with a string literal or a "no-substitution" string. For example: ```typescript @Component({..., template: ` <p>Bar: {{baz}}</p> `}) export class TestCmp { bar: string; } ``` The above template contains an error (no 'baz' property of `TestCmp`). The error produced by TS will look like: ``` <p>Bar: {{baz}}</p> ~~~ test.ts:2:11 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. Did you mean 'bar'? ``` 2) For template strings which cannot be directly mapped to offsets in the TS code, a logical offset into the template string will be included in the error message. For example: ```typescript const SOME_TEMPLATE = '<p>Bar: {{baz}}</p>'; @Component({..., template: SOME_TEMPLATE}) export class TestCmp { bar: string; } ``` Because the template is a reference to another variable and is not an inline string constant, the compiler will not be able to use "absolute" positions when parsing the template. As a result, errors will report logical offsets into the template string: ``` <p>Bar: {{baz}}</p> ~~~ test.ts (TestCmp template):2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. test.ts:3:28 @Component({..., template: TEMPLATE}) ~~~~~~~~ Error occurs in the template of component TestCmp. ``` This error message uses logical offsets into the template string, and also gives a reference to the `TEMPLATE` expression from which the template was parsed. This helps in locating the component which contains the error. 3) For external templates (templateUrl), the error message is delivered within the HTML template file (testcmp.html) instead, and additional information contextualizes the error on the templateUrl expression from which the template file was determined: ``` <p>Bar: {{baz}}</p> ~~~ testcmp.html:2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. test.ts:10:31 @Component({..., templateUrl: './testcmp.html'}) ~~~~~~~~~~~~~~~~ Error occurs in the template of component TestCmp. ``` PR Close #31952
2019-08-01 15:01:55 -07:00
undefined): ReadonlyArray<ts.Diagnostic> {
return this.constructionDiagnostics;
}
getTsSyntacticDiagnostics(
sourceFile?: ts.SourceFile|undefined,
cancellationToken?: ts.CancellationToken|undefined): ReadonlyArray<ts.Diagnostic> {
return this.tsProgram.getSyntacticDiagnostics(sourceFile, cancellationToken);
}
getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken|
undefined): ReadonlyArray<api.Diagnostic> {
return [];
}
getTsSemanticDiagnostics(
sourceFile?: ts.SourceFile|undefined,
cancellationToken?: ts.CancellationToken|undefined): ReadonlyArray<ts.Diagnostic> {
return this.tsProgram.getSemanticDiagnostics(sourceFile, cancellationToken);
}
getNgSemanticDiagnostics(
feat(ivy): convert all ngtsc diagnostics to ts.Diagnostics (#31952) Historically, the Angular Compiler has produced both native TypeScript diagnostics (called ts.Diagnostics) and its own internal Diagnostic format (called an api.Diagnostic). This was done because TypeScript ts.Diagnostics cannot be produced for files not in the ts.Program, and template type- checking diagnostics are naturally produced for external .html template files. This design isn't optimal for several reasons: 1) Downstream tooling (such as the CLI) must support multiple formats of diagnostics, adding to the maintenance burden. 2) ts.Diagnostics have gotten a lot better in recent releases, with support for suggested changes, highlighting of the code in question, etc. None of these changes have been of any benefit for api.Diagnostics, which have continued to be reported in a very primitive fashion. 3) A future plugin model will not support anything but ts.Diagnostics, so generating api.Diagnostics is a blocker for ngtsc-as-a-plugin. 4) The split complicates both the typings and the testing of ngtsc. To fix this issue, this commit changes template type-checking to produce ts.Diagnostics instead. Instead of reporting a special kind of diagnostic for external template files, errors in a template are always reported in a ts.Diagnostic that highlights the portion of the template which contains the error. When this template text is distinct from the source .ts file (for example, when the template is parsed from an external resource file), additional contextual information links the error back to the originating component. A template error can thus be reported in 3 separate ways, depending on how the template was configured: 1) For inline template strings which can be directly mapped to offsets in the TS code, ts.Diagnostics point to real ranges in the source. This is the case if an inline template is used with a string literal or a "no-substitution" string. For example: ```typescript @Component({..., template: ` <p>Bar: {{baz}}</p> `}) export class TestCmp { bar: string; } ``` The above template contains an error (no 'baz' property of `TestCmp`). The error produced by TS will look like: ``` <p>Bar: {{baz}}</p> ~~~ test.ts:2:11 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. Did you mean 'bar'? ``` 2) For template strings which cannot be directly mapped to offsets in the TS code, a logical offset into the template string will be included in the error message. For example: ```typescript const SOME_TEMPLATE = '<p>Bar: {{baz}}</p>'; @Component({..., template: SOME_TEMPLATE}) export class TestCmp { bar: string; } ``` Because the template is a reference to another variable and is not an inline string constant, the compiler will not be able to use "absolute" positions when parsing the template. As a result, errors will report logical offsets into the template string: ``` <p>Bar: {{baz}}</p> ~~~ test.ts (TestCmp template):2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. test.ts:3:28 @Component({..., template: TEMPLATE}) ~~~~~~~~ Error occurs in the template of component TestCmp. ``` This error message uses logical offsets into the template string, and also gives a reference to the `TEMPLATE` expression from which the template was parsed. This helps in locating the component which contains the error. 3) For external templates (templateUrl), the error message is delivered within the HTML template file (testcmp.html) instead, and additional information contextualizes the error on the templateUrl expression from which the template file was determined: ``` <p>Bar: {{baz}}</p> ~~~ testcmp.html:2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. test.ts:10:31 @Component({..., templateUrl: './testcmp.html'}) ~~~~~~~~~~~~~~~~ Error occurs in the template of component TestCmp. ``` PR Close #31952
2019-08-01 15:01:55 -07:00
fileName?: string|undefined,
cancellationToken?: ts.CancellationToken|undefined): ReadonlyArray<ts.Diagnostic> {
const compilation = this.ensureAnalyzed();
const diagnostics = [...compilation.diagnostics, ...this.getTemplateDiagnostics()];
if (this.entryPoint !== null && this.exportReferenceGraph !== null) {
diagnostics.push(...checkForPrivateExports(
this.entryPoint, this.tsProgram.getTypeChecker(), this.exportReferenceGraph));
}
return diagnostics;
}
async loadNgStructureAsync(): Promise<void> {
if (this.compilation === undefined) {
this.compilation = this.makeCompilation();
}
const analyzeSpan = this.perfRecorder.start('analyze');
await Promise.all(this.tsProgram.getSourceFiles()
.filter(file => !file.fileName.endsWith('.d.ts'))
.map(file => {
const analyzeFileSpan = this.perfRecorder.start('analyzeFile', file);
let analysisPromise = this.compilation !.analyzeAsync(file);
if (analysisPromise === undefined) {
this.perfRecorder.stop(analyzeFileSpan);
} else if (this.perfRecorder.enabled) {
analysisPromise = analysisPromise.then(
() => this.perfRecorder.stop(analyzeFileSpan));
}
return analysisPromise;
})
.filter((result): result is Promise<void> => result !== undefined));
this.perfRecorder.stop(analyzeSpan);
this.compilation.resolve();
}
listLazyRoutes(entryRoute?: string|undefined): api.LazyRoute[] {
if (entryRoute) {
// Note:
// This resolution step is here to match the implementation of the old `AotCompilerHost` (see
// https://github.com/angular/angular/blob/50732e156/packages/compiler-cli/src/transformers/compiler_host.ts#L175-L188).
//
// `@angular/cli` will always call this API with an absolute path, so the resolution step is
// not necessary, but keeping it backwards compatible in case someone else is using the API.
// Relative entry paths are disallowed.
if (entryRoute.startsWith('.')) {
throw new Error(
`Failed to list lazy routes: Resolution of relative paths (${entryRoute}) is not supported.`);
}
// Non-relative entry paths fall into one of the following categories:
// - Absolute system paths (e.g. `/foo/bar/my-project/my-module`), which are unaffected by the
// logic below.
// - Paths to enternal modules (e.g. `some-lib`).
// - Paths mapped to directories in `tsconfig.json` (e.g. `shared/my-module`).
// (See https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping.)
//
// In all cases above, the `containingFile` argument is ignored, so we can just take the first
// of the root files.
const containingFile = this.tsProgram.getRootFileNames()[0];
const [entryPath, moduleName] = entryRoute.split('#');
const resolvedModule = resolveModuleName(entryPath, containingFile, this.options, this.host);
if (resolvedModule) {
entryRoute = entryPointKeyFor(resolvedModule.resolvedFileName, moduleName);
}
}
this.ensureAnalyzed();
return this.routeAnalyzer !.listLazyRoutes(entryRoute);
}
getLibrarySummaries(): Map<string, api.LibrarySummary> {
throw new Error('Method not implemented.');
}
getEmittedGeneratedFiles(): Map<string, GeneratedFile> {
throw new Error('Method not implemented.');
}
getEmittedSourceFiles(): Map<string, ts.SourceFile> {
throw new Error('Method not implemented.');
}
private ensureAnalyzed(): IvyCompilation {
if (this.compilation === undefined) {
const analyzeSpan = this.perfRecorder.start('analyze');
this.compilation = this.makeCompilation();
this.tsProgram.getSourceFiles().filter(file => !file.isDeclarationFile).forEach(file => {
const analyzeFileSpan = this.perfRecorder.start('analyzeFile', file);
this.compilation !.analyzeSync(file);
this.perfRecorder.stop(analyzeFileSpan);
});
this.perfRecorder.stop(analyzeSpan);
this.compilation.resolve();
}
return this.compilation;
}
emit(opts?: {
emitFlags?: api.EmitFlags,
cancellationToken?: ts.CancellationToken,
customTransformers?: api.CustomTransformers,
emitCallback?: api.TsEmitCallback,
mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback
}): ts.EmitResult {
const emitCallback = opts && opts.emitCallback || defaultEmitCallback;
const compilation = this.ensureAnalyzed();
const writeFile: ts.WriteFileCallback =
(fileName: string, data: string, writeByteOrderMark: boolean,
onError: ((message: string) => void) | undefined,
sourceFiles: ReadonlyArray<ts.SourceFile>| undefined) => {
if (this.closureCompilerEnabled && fileName.endsWith('.js')) {
data = nocollapseHack(data);
}
this.host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
};
const customTransforms = opts && opts.customTransformers;
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
2019-03-11 16:54:07 -07:00
const beforeTransforms = [
ivyTransformFactory(
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
2019-03-11 16:54:07 -07:00
compilation, this.reflector, this.importRewriter, this.defaultImportTracker, this.isCore,
this.closureCompilerEnabled),
aliasTransformFactory(compilation.exportStatements) as ts.TransformerFactory<ts.SourceFile>,
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
2019-03-11 16:54:07 -07:00
this.defaultImportTracker.importPreservingTransformer(),
];
const afterDeclarationsTransforms = [
declarationTransformFactory(compilation),
];
feat(ivy): enable re-export of the compilation scope of NgModules privately (#33177) This commit refactors the aliasing system to support multiple different AliasingHost implementations, which control specific aliasing behavior in ngtsc (see the README.md). A new host is introduced, the `PrivateExportAliasingHost`. This solves a longstanding problem in ngtsc regarding support for "monorepo" style private libraries. These are libraries which are compiled separately from the main application, and depended upon through TypeScript path mappings. Such libraries are frequently not in the Angular Package Format and do not have entrypoints, but rather make use of deep import style module specifiers. This can cause issues with ngtsc's ability to import a directive given the module specifier of its NgModule. For example, if the application uses a directive `Foo` from such a library `foo`, the user might write: ```typescript import {FooModule} from 'foo/module'; ``` In this case, foo/module.d.ts is path-mapped into the program. Ordinarily the compiler would see this as an absolute module specifier, and assume that the `Foo` directive can be imported from the same specifier. For such non- APF libraries, this assumption fails. Really `Foo` should be imported from the file which declares it, but there are two problems with this: 1. The compiler would have to reverse the path mapping in order to determine a path-mapped path to the file (maybe foo/dir.d.ts). 2. There is no guarantee that the file containing the directive is path- mapped in the program at all. The compiler would effectively have to "guess" 'foo/dir' as a module specifier, which may or may not be accurate depending on how the library and path mapping are set up. It's strongly desirable that the compiler not break its current invariant that the module specifier given by the user for the NgModule is always the module specifier from which directives/pipes are imported. Thus, for any given NgModule from a particular module specifier, it must always be possible to import any directives/pipes from the same specifier, no matter how it's packaged. To make this possible, when compiling a file containing an NgModule, ngtsc will automatically add re-exports for any directives/pipes not yet exported by the user, with a name of the form: ɵngExportɵModuleNameɵDirectiveName This has several effects: 1. It guarantees anyone depending on the NgModule will be able to import its directives/pipes from the same specifier. 2. It maintains a stable name for the exported symbol that is safe to depend on from code on NPM. Effectively, this private exported name will be a part of the package's .d.ts API, and cannot be changed in a non-breaking fashion. Fixes #29361 FW-1610 #resolve PR Close #33177
2019-10-14 12:03:29 -07:00
// Only add aliasing re-exports to the .d.ts output if the `AliasingHost` requests it.
if (this.aliasingHost !== null && this.aliasingHost.aliasExportsInDts) {
afterDeclarationsTransforms.push(aliasTransformFactory(compilation.exportStatements));
}
if (this.factoryToSourceInfo !== null) {
beforeTransforms.push(
generatedFactoryTransform(this.factoryToSourceInfo, this.importRewriter));
}
beforeTransforms.push(ivySwitchTransform);
if (customTransforms && customTransforms.beforeTs) {
beforeTransforms.push(...customTransforms.beforeTs);
refactor(ivy): obviate the Bazel component of the ivy_switch (#26550) Originally, the ivy_switch mechanism used Bazel genrules to conditionally compile one TS file or another depending on whether ngc or ngtsc was the selected compiler. This was done because we wanted to avoid importing certain modules (and thus pulling them into the build) if Ivy was on or off. This mechanism had a major drawback: ivy_switch became a bottleneck in the import graph, as it both imports from many places in the codebase and is imported by many modules in the codebase. This frequently resulted in cyclic imports which caused issues both with TS and Closure compilation. It turns out ngcc needs both code paths in the bundle to perform the switch during its operation anyway, so import switching was later abandoned. This means that there's no real reason why the ivy_switch mechanism needed to operate at the Bazel level, and for the ivy_switch file to be a bottleneck. This commit removes the Bazel-level ivy_switch mechanism, and introduces an additional TypeScript transform in ngtsc (and the pass-through tsc compiler used for testing JIT) to perform the same operation that ngcc does, and flip the switch during ngtsc compilation. This allows the ivy_switch file to be removed, and the individual switches to be located directly next to their consumers in the codebase, greatly mitigating the circular import issues and making the mechanism much easier to use. As part of this commit, the tag for marking switched variables was changed from __PRE_NGCC__ to __PRE_R3__, since it's no longer just ngcc which flips these tags. Most variables were renamed from R3_* to SWITCH_* as well, since they're referenced mostly in render2 code. Test strategy: existing test coverage is more than sufficient - if this didn't work correctly it would break the hello world and todo apps. PR Close #26550
2018-10-17 15:44:44 -07:00
}
const emitSpan = this.perfRecorder.start('emit');
const emitResults: ts.EmitResult[] = [];
refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921) To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
2019-06-06 20:22:32 +01:00
const typeCheckFile = getSourceFileOrNull(this.tsProgram, this.typeCheckFilePath);
for (const targetSourceFile of this.tsProgram.getSourceFiles()) {
if (targetSourceFile.isDeclarationFile || targetSourceFile === typeCheckFile) {
continue;
}
if (this.incrementalState.safeToSkip(targetSourceFile)) {
continue;
}
const fileEmitSpan = this.perfRecorder.start('emitFile', targetSourceFile);
emitResults.push(emitCallback({
targetSourceFile,
program: this.tsProgram,
host: this.host,
options: this.options,
emitOnlyDtsFiles: false, writeFile,
customTransformers: {
before: beforeTransforms,
after: customTransforms && customTransforms.afterTs,
afterDeclarations: afterDeclarationsTransforms,
},
}));
this.perfRecorder.stop(fileEmitSpan);
}
this.perfRecorder.stop(emitSpan);
if (this.perfTracker !== null && this.options.tracePerformance !== undefined) {
this.perfTracker.serializeToFile(this.options.tracePerformance, this.host);
}
// Run the emit, including a custom transformer that will downlevel the Ivy decorators in code.
return ((opts && opts.mergeEmitResultsCallback) || mergeEmitResults)(emitResults);
}
feat(ivy): convert all ngtsc diagnostics to ts.Diagnostics (#31952) Historically, the Angular Compiler has produced both native TypeScript diagnostics (called ts.Diagnostics) and its own internal Diagnostic format (called an api.Diagnostic). This was done because TypeScript ts.Diagnostics cannot be produced for files not in the ts.Program, and template type- checking diagnostics are naturally produced for external .html template files. This design isn't optimal for several reasons: 1) Downstream tooling (such as the CLI) must support multiple formats of diagnostics, adding to the maintenance burden. 2) ts.Diagnostics have gotten a lot better in recent releases, with support for suggested changes, highlighting of the code in question, etc. None of these changes have been of any benefit for api.Diagnostics, which have continued to be reported in a very primitive fashion. 3) A future plugin model will not support anything but ts.Diagnostics, so generating api.Diagnostics is a blocker for ngtsc-as-a-plugin. 4) The split complicates both the typings and the testing of ngtsc. To fix this issue, this commit changes template type-checking to produce ts.Diagnostics instead. Instead of reporting a special kind of diagnostic for external template files, errors in a template are always reported in a ts.Diagnostic that highlights the portion of the template which contains the error. When this template text is distinct from the source .ts file (for example, when the template is parsed from an external resource file), additional contextual information links the error back to the originating component. A template error can thus be reported in 3 separate ways, depending on how the template was configured: 1) For inline template strings which can be directly mapped to offsets in the TS code, ts.Diagnostics point to real ranges in the source. This is the case if an inline template is used with a string literal or a "no-substitution" string. For example: ```typescript @Component({..., template: ` <p>Bar: {{baz}}</p> `}) export class TestCmp { bar: string; } ``` The above template contains an error (no 'baz' property of `TestCmp`). The error produced by TS will look like: ``` <p>Bar: {{baz}}</p> ~~~ test.ts:2:11 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. Did you mean 'bar'? ``` 2) For template strings which cannot be directly mapped to offsets in the TS code, a logical offset into the template string will be included in the error message. For example: ```typescript const SOME_TEMPLATE = '<p>Bar: {{baz}}</p>'; @Component({..., template: SOME_TEMPLATE}) export class TestCmp { bar: string; } ``` Because the template is a reference to another variable and is not an inline string constant, the compiler will not be able to use "absolute" positions when parsing the template. As a result, errors will report logical offsets into the template string: ``` <p>Bar: {{baz}}</p> ~~~ test.ts (TestCmp template):2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. test.ts:3:28 @Component({..., template: TEMPLATE}) ~~~~~~~~ Error occurs in the template of component TestCmp. ``` This error message uses logical offsets into the template string, and also gives a reference to the `TEMPLATE` expression from which the template was parsed. This helps in locating the component which contains the error. 3) For external templates (templateUrl), the error message is delivered within the HTML template file (testcmp.html) instead, and additional information contextualizes the error on the templateUrl expression from which the template file was determined: ``` <p>Bar: {{baz}}</p> ~~~ testcmp.html:2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. test.ts:10:31 @Component({..., templateUrl: './testcmp.html'}) ~~~~~~~~~~~~~~~~ Error occurs in the template of component TestCmp. ``` PR Close #31952
2019-08-01 15:01:55 -07:00
private getTemplateDiagnostics(): ReadonlyArray<ts.Diagnostic> {
// Skip template type-checking if it's disabled.
if (this.options.ivyTemplateTypeCheck === false &&
this.options.fullTemplateTypeCheck !== true) {
return [];
}
const compilation = this.ensureAnalyzed();
// Run template type-checking.
// First select a type-checking configuration, based on whether full template type-checking is
// requested.
let typeCheckingConfig: TypeCheckingConfig;
if (this.options.fullTemplateTypeCheck) {
const strictTemplates = !!this.options.strictTemplates;
typeCheckingConfig = {
applyTemplateContextGuards: strictTemplates,
checkQueries: false,
checkTemplateBodies: true,
checkTypeOfInputBindings: strictTemplates,
strictNullInputBindings: strictTemplates,
checkTypeOfAttributes: strictTemplates,
// Even in full template type-checking mode, DOM binding checks are not quite ready yet.
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: strictTemplates,
checkTypeOfAnimationEvents: strictTemplates,
// Checking of DOM events currently has an adverse effect on developer experience,
// e.g. for `<input (blur)="update($event.target.value)">` enabling this check results in:
// - error TS2531: Object is possibly 'null'.
// - error TS2339: Property 'value' does not exist on type 'EventTarget'.
checkTypeOfDomEvents: strictTemplates,
checkTypeOfDomReferences: strictTemplates,
// Non-DOM references have the correct type in View Engine so there is no strictness flag.
checkTypeOfNonDomReferences: true,
// Pipes are checked in View Engine so there is no strictness flag.
checkTypeOfPipes: true,
strictSafeNavigationTypes: strictTemplates,
};
} else {
typeCheckingConfig = {
applyTemplateContextGuards: false,
checkQueries: false,
checkTemplateBodies: false,
checkTypeOfInputBindings: false,
strictNullInputBindings: false,
checkTypeOfAttributes: false,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: false,
checkTypeOfAnimationEvents: false,
checkTypeOfDomEvents: false,
checkTypeOfDomReferences: false,
checkTypeOfNonDomReferences: false,
checkTypeOfPipes: false,
strictSafeNavigationTypes: false,
};
}
// Apply explicitly configured strictness flags on top of the default configuration
// based on "fullTemplateTypeCheck".
if (this.options.strictInputTypes !== undefined) {
typeCheckingConfig.checkTypeOfInputBindings = this.options.strictInputTypes;
typeCheckingConfig.applyTemplateContextGuards = this.options.strictInputTypes;
}
if (this.options.strictNullInputTypes !== undefined) {
typeCheckingConfig.strictNullInputBindings = this.options.strictNullInputTypes;
}
if (this.options.strictOutputEventTypes !== undefined) {
typeCheckingConfig.checkTypeOfOutputEvents = this.options.strictOutputEventTypes;
typeCheckingConfig.checkTypeOfAnimationEvents = this.options.strictOutputEventTypes;
}
if (this.options.strictDomEventTypes !== undefined) {
typeCheckingConfig.checkTypeOfDomEvents = this.options.strictDomEventTypes;
}
if (this.options.strictSafeNavigationTypes !== undefined) {
typeCheckingConfig.strictSafeNavigationTypes = this.options.strictSafeNavigationTypes;
}
if (this.options.strictDomLocalRefTypes !== undefined) {
typeCheckingConfig.checkTypeOfDomReferences = this.options.strictDomLocalRefTypes;
}
if (this.options.strictAttributeTypes !== undefined) {
typeCheckingConfig.checkTypeOfAttributes = this.options.strictAttributeTypes;
}
// Execute the typeCheck phase of each decorator in the program.
const prepSpan = this.perfRecorder.start('typeCheckPrep');
const ctx = new TypeCheckContext(typeCheckingConfig, this.refEmitter !, this.typeCheckFilePath);
compilation.typeCheck(ctx);
this.perfRecorder.stop(prepSpan);
// Get the diagnostics.
const typeCheckSpan = this.perfRecorder.start('typeCheckDiagnostics');
const {diagnostics, program} =
ctx.calculateTemplateDiagnostics(this.tsProgram, this.host, this.options);
this.perfRecorder.stop(typeCheckSpan);
this.reuseTsProgram = program;
return diagnostics;
}
getIndexedComponents(): Map<ts.Declaration, IndexedComponent> {
const compilation = this.ensureAnalyzed();
const context = new IndexingContext();
compilation.index(context);
return generateAnalysis(context);
}
private makeCompilation(): IvyCompilation {
const checker = this.tsProgram.getTypeChecker();
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
// Construct the ReferenceEmitter.
if (this.fileToModuleHost === null || !this.options._useHostForImportGeneration) {
let localImportStrategy: ReferenceEmitStrategy;
// The strategy used for local, in-project imports depends on whether TS has been configured
// with rootDirs. If so, then multiple directories may be mapped in the same "module
// namespace" and the logic of `LogicalProjectStrategy` is required to generate correct
// imports which may cross these multiple directories. Otherwise, plain relative imports are
// sufficient.
if (this.options.rootDir !== undefined ||
(this.options.rootDirs !== undefined && this.options.rootDirs.length > 0)) {
// rootDirs logic is in effect - use the `LogicalProjectStrategy` for in-project relative
// imports.
localImportStrategy =
new LogicalProjectStrategy(this.reflector, new LogicalFileSystem(this.rootDirs));
} else {
// Plain relative imports are all that's needed.
localImportStrategy = new RelativePathStrategy(this.reflector);
}
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
// The CompilerHost doesn't have fileNameToModuleName, so build an NPM-centric reference
// resolution strategy.
this.refEmitter = new ReferenceEmitter([
// First, try to use local identifiers if available.
new LocalIdentifierStrategy(),
// Next, attempt to use an absolute import.
new AbsoluteModuleStrategy(
this.tsProgram, checker, this.options, this.host, this.reflector),
// Finally, check if the reference is being written into a file within the project's .ts
// sources, and use a relative import if so. If this fails, ReferenceEmitter will throw
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
// an error.
localImportStrategy,
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
]);
feat(ivy): enable re-export of the compilation scope of NgModules privately (#33177) This commit refactors the aliasing system to support multiple different AliasingHost implementations, which control specific aliasing behavior in ngtsc (see the README.md). A new host is introduced, the `PrivateExportAliasingHost`. This solves a longstanding problem in ngtsc regarding support for "monorepo" style private libraries. These are libraries which are compiled separately from the main application, and depended upon through TypeScript path mappings. Such libraries are frequently not in the Angular Package Format and do not have entrypoints, but rather make use of deep import style module specifiers. This can cause issues with ngtsc's ability to import a directive given the module specifier of its NgModule. For example, if the application uses a directive `Foo` from such a library `foo`, the user might write: ```typescript import {FooModule} from 'foo/module'; ``` In this case, foo/module.d.ts is path-mapped into the program. Ordinarily the compiler would see this as an absolute module specifier, and assume that the `Foo` directive can be imported from the same specifier. For such non- APF libraries, this assumption fails. Really `Foo` should be imported from the file which declares it, but there are two problems with this: 1. The compiler would have to reverse the path mapping in order to determine a path-mapped path to the file (maybe foo/dir.d.ts). 2. There is no guarantee that the file containing the directive is path- mapped in the program at all. The compiler would effectively have to "guess" 'foo/dir' as a module specifier, which may or may not be accurate depending on how the library and path mapping are set up. It's strongly desirable that the compiler not break its current invariant that the module specifier given by the user for the NgModule is always the module specifier from which directives/pipes are imported. Thus, for any given NgModule from a particular module specifier, it must always be possible to import any directives/pipes from the same specifier, no matter how it's packaged. To make this possible, when compiling a file containing an NgModule, ngtsc will automatically add re-exports for any directives/pipes not yet exported by the user, with a name of the form: ɵngExportɵModuleNameɵDirectiveName This has several effects: 1. It guarantees anyone depending on the NgModule will be able to import its directives/pipes from the same specifier. 2. It maintains a stable name for the exported symbol that is safe to depend on from code on NPM. Effectively, this private exported name will be a part of the package's .d.ts API, and cannot be changed in a non-breaking fashion. Fixes #29361 FW-1610 #resolve PR Close #33177
2019-10-14 12:03:29 -07:00
// If an entrypoint is present, then all user imports should be directed through the
// entrypoint and private exports are not needed. The compiler will validate that all publicly
// visible directives/pipes are importable via this entrypoint.
if (this.entryPoint === null && this.options.generateDeepReexports === true) {
// No entrypoint is present and deep re-exports were requested, so configure the aliasing
// system to generate them.
this.aliasingHost = new PrivateExportAliasingHost(this.reflector);
}
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
} else {
// The CompilerHost supports fileNameToModuleName, so use that to emit imports.
this.refEmitter = new ReferenceEmitter([
// First, try to use local identifiers if available.
new LocalIdentifierStrategy(),
// Then use aliased references (this is a workaround to StrictDeps checks).
new AliasStrategy(),
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
// Then use fileNameToModuleName to emit imports.
new FileToModuleStrategy(this.reflector, this.fileToModuleHost),
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
]);
feat(ivy): enable re-export of the compilation scope of NgModules privately (#33177) This commit refactors the aliasing system to support multiple different AliasingHost implementations, which control specific aliasing behavior in ngtsc (see the README.md). A new host is introduced, the `PrivateExportAliasingHost`. This solves a longstanding problem in ngtsc regarding support for "monorepo" style private libraries. These are libraries which are compiled separately from the main application, and depended upon through TypeScript path mappings. Such libraries are frequently not in the Angular Package Format and do not have entrypoints, but rather make use of deep import style module specifiers. This can cause issues with ngtsc's ability to import a directive given the module specifier of its NgModule. For example, if the application uses a directive `Foo` from such a library `foo`, the user might write: ```typescript import {FooModule} from 'foo/module'; ``` In this case, foo/module.d.ts is path-mapped into the program. Ordinarily the compiler would see this as an absolute module specifier, and assume that the `Foo` directive can be imported from the same specifier. For such non- APF libraries, this assumption fails. Really `Foo` should be imported from the file which declares it, but there are two problems with this: 1. The compiler would have to reverse the path mapping in order to determine a path-mapped path to the file (maybe foo/dir.d.ts). 2. There is no guarantee that the file containing the directive is path- mapped in the program at all. The compiler would effectively have to "guess" 'foo/dir' as a module specifier, which may or may not be accurate depending on how the library and path mapping are set up. It's strongly desirable that the compiler not break its current invariant that the module specifier given by the user for the NgModule is always the module specifier from which directives/pipes are imported. Thus, for any given NgModule from a particular module specifier, it must always be possible to import any directives/pipes from the same specifier, no matter how it's packaged. To make this possible, when compiling a file containing an NgModule, ngtsc will automatically add re-exports for any directives/pipes not yet exported by the user, with a name of the form: ɵngExportɵModuleNameɵDirectiveName This has several effects: 1. It guarantees anyone depending on the NgModule will be able to import its directives/pipes from the same specifier. 2. It maintains a stable name for the exported symbol that is safe to depend on from code on NPM. Effectively, this private exported name will be a part of the package's .d.ts API, and cannot be changed in a non-breaking fashion. Fixes #29361 FW-1610 #resolve PR Close #33177
2019-10-14 12:03:29 -07:00
this.aliasingHost = new FileToModuleAliasingHost(this.fileToModuleHost);
feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523) The ultimate goal of this commit is to make use of fileNameToModuleName to get the module specifier to use when generating an import, when that API is available in the CompilerHost that ngtsc is created with. As part of getting there, the way in which ngtsc tracks references and generates import module specifiers is refactored considerably. References are tracked with the Reference class, and previously ngtsc had several different kinds of Reference. An AbsoluteReference represented a declaration which needed to be imported via an absolute module specifier tracked in the AbsoluteReference, and a RelativeReference represented a declaration from the local program, imported via relative path or referred to directly by identifier if possible. Thus, how to refer to a particular declaration was encoded into the Reference type _at the time of creation of the Reference_. This commit refactors that logic and reduces Reference to a single class with no subclasses. A Reference represents a node being referenced, plus context about how the node was located. This context includes a "bestGuessOwningModule", the compiler's best guess at which absolute module specifier has defined this reference. For example, if the compiler arrives at the declaration of CommonModule via an import to @angular/common, then any references obtained from CommonModule (e.g. NgIf) will also be considered to be owned by @angular/common. A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface are introduced. To produce an Expression referring to a given Reference'd node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy implementations. Several different strategies are defined: - LocalIdentifierStrategy: use local ts.Identifiers if available. - AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule, import the node via an absolute import from that module specifier. - LogicalProjectStrategy: if the Reference is in the logical project (is under the project rootDirs), import the node via a relative import. - FileToModuleStrategy: use a FileToModuleHost to generate the module specifier by which to import the node. Depending on the availability of fileNameToModuleName in the CompilerHost, then, a different collection of these strategies is used for compilation. PR Close #28523
2019-02-01 17:24:21 -08:00
}
const evaluator = new PartialEvaluator(this.reflector, checker, this.incrementalState);
const dtsReader = new DtsMetadataReader(checker, this.reflector);
const localMetaRegistry = new LocalMetadataRegistry();
const localMetaReader: MetadataReader = localMetaRegistry;
feat(ivy): enable re-export of the compilation scope of NgModules privately (#33177) This commit refactors the aliasing system to support multiple different AliasingHost implementations, which control specific aliasing behavior in ngtsc (see the README.md). A new host is introduced, the `PrivateExportAliasingHost`. This solves a longstanding problem in ngtsc regarding support for "monorepo" style private libraries. These are libraries which are compiled separately from the main application, and depended upon through TypeScript path mappings. Such libraries are frequently not in the Angular Package Format and do not have entrypoints, but rather make use of deep import style module specifiers. This can cause issues with ngtsc's ability to import a directive given the module specifier of its NgModule. For example, if the application uses a directive `Foo` from such a library `foo`, the user might write: ```typescript import {FooModule} from 'foo/module'; ``` In this case, foo/module.d.ts is path-mapped into the program. Ordinarily the compiler would see this as an absolute module specifier, and assume that the `Foo` directive can be imported from the same specifier. For such non- APF libraries, this assumption fails. Really `Foo` should be imported from the file which declares it, but there are two problems with this: 1. The compiler would have to reverse the path mapping in order to determine a path-mapped path to the file (maybe foo/dir.d.ts). 2. There is no guarantee that the file containing the directive is path- mapped in the program at all. The compiler would effectively have to "guess" 'foo/dir' as a module specifier, which may or may not be accurate depending on how the library and path mapping are set up. It's strongly desirable that the compiler not break its current invariant that the module specifier given by the user for the NgModule is always the module specifier from which directives/pipes are imported. Thus, for any given NgModule from a particular module specifier, it must always be possible to import any directives/pipes from the same specifier, no matter how it's packaged. To make this possible, when compiling a file containing an NgModule, ngtsc will automatically add re-exports for any directives/pipes not yet exported by the user, with a name of the form: ɵngExportɵModuleNameɵDirectiveName This has several effects: 1. It guarantees anyone depending on the NgModule will be able to import its directives/pipes from the same specifier. 2. It maintains a stable name for the exported symbol that is safe to depend on from code on NPM. Effectively, this private exported name will be a part of the package's .d.ts API, and cannot be changed in a non-breaking fashion. Fixes #29361 FW-1610 #resolve PR Close #33177
2019-10-14 12:03:29 -07:00
const depScopeReader = new MetadataDtsModuleScopeResolver(dtsReader, this.aliasingHost);
const scopeRegistry = new LocalModuleScopeRegistry(
localMetaReader, depScopeReader, this.refEmitter, this.aliasingHost);
const scopeReader: ComponentScopeReader = scopeRegistry;
const metaRegistry = new CompoundMetadataRegistry([localMetaRegistry, scopeRegistry]);
this.metaReader = new CompoundMetadataReader([localMetaReader, dtsReader]);
// If a flat module entrypoint was specified, then track references via a `ReferenceGraph` in
// order to produce proper diagnostics for incorrectly exported directives/pipes/etc. If there
// is no flat module entrypoint then don't pay the cost of tracking references.
let referencesRegistry: ReferencesRegistry;
if (this.entryPoint !== null) {
this.exportReferenceGraph = new ReferenceGraph();
referencesRegistry = new ReferenceGraphAdapter(this.exportReferenceGraph);
} else {
referencesRegistry = new NoopReferencesRegistry();
}
this.routeAnalyzer = new NgModuleRouteAnalyzer(this.moduleResolver, evaluator);
// Set up the IvyCompilation, which manages state for the Ivy transformer.
const handlers = [
new ComponentDecoratorHandler(
this.reflector, evaluator, metaRegistry, this.metaReader !, scopeReader, scopeRegistry,
this.isCore, this.resourceManager, this.rootDirs,
this.options.preserveWhitespaces || false, this.options.i18nUseExternalIds !== false,
this.getI18nLegacyMessageFormat(), this.moduleResolver, this.cycleAnalyzer,
this.refEmitter, this.defaultImportTracker, this.closureCompilerEnabled,
this.incrementalState),
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
2019-03-11 16:54:07 -07:00
new DirectiveDecoratorHandler(
this.reflector, evaluator, metaRegistry, this.defaultImportTracker, this.isCore,
this.closureCompilerEnabled),
new InjectableDecoratorHandler(
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
2019-03-11 16:54:07 -07:00
this.reflector, this.defaultImportTracker, this.isCore,
this.options.strictInjectionParameters || false),
new NgModuleDecoratorHandler(
this.reflector, evaluator, this.metaReader, metaRegistry, scopeRegistry,
referencesRegistry, this.isCore, this.routeAnalyzer, this.refEmitter,
this.defaultImportTracker, this.closureCompilerEnabled, this.options.i18nInLocale),
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
2019-03-11 16:54:07 -07:00
new PipeDecoratorHandler(
this.reflector, evaluator, metaRegistry, this.defaultImportTracker, this.isCore),
];
return new IvyCompilation(
handlers, this.reflector, this.importRewriter, this.incrementalState, this.perfRecorder,
this.sourceToFactorySymbols, scopeRegistry);
}
private getI18nLegacyMessageFormat(): string {
return this.options.enableI18nLegacyMessageIdFormat !== false && this.options.i18nInFormat ||
'';
}
private get reflector(): TypeScriptReflectionHost {
if (this._reflector === undefined) {
this._reflector = new TypeScriptReflectionHost(this.tsProgram.getTypeChecker());
}
return this._reflector;
}
private get coreImportsFrom(): ts.SourceFile|null {
if (this._coreImportsFrom === undefined) {
this._coreImportsFrom = this.isCore && getR3SymbolsFile(this.tsProgram) || null;
}
return this._coreImportsFrom;
}
private get isCore(): boolean {
if (this._isCore === undefined) {
this._isCore = isAngularCorePackage(this.tsProgram);
}
return this._isCore;
}
private get importRewriter(): ImportRewriter {
if (this._importRewriter === undefined) {
const coreImportsFrom = this.coreImportsFrom;
this._importRewriter = coreImportsFrom !== null ?
new R3SymbolsImportRewriter(coreImportsFrom.fileName) :
new NoopImportRewriter();
}
return this._importRewriter;
}
}
const defaultEmitCallback: api.TsEmitCallback =
({program, targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles,
customTransformers}) =>
program.emit(
targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult {
const diagnostics: ts.Diagnostic[] = [];
let emitSkipped = false;
const emittedFiles: string[] = [];
for (const er of emitResults) {
diagnostics.push(...er.diagnostics);
emitSkipped = emitSkipped || er.emitSkipped;
emittedFiles.push(...(er.emittedFiles || []));
}
return {diagnostics, emitSkipped, emittedFiles};
}
/**
* Find the 'r3_symbols.ts' file in the given `Program`, or return `null` if it wasn't there.
*/
function getR3SymbolsFile(program: ts.Program): ts.SourceFile|null {
return program.getSourceFiles().find(file => file.fileName.indexOf('r3_symbols.ts') >= 0) || null;
}
/**
* Determine if the given `Program` is @angular/core.
*/
function isAngularCorePackage(program: ts.Program): boolean {
// Look for its_just_angular.ts somewhere in the program.
const r3Symbols = getR3SymbolsFile(program);
if (r3Symbols === null) {
return false;
}
// Look for the constant ITS_JUST_ANGULAR in that file.
return r3Symbols.statements.some(stmt => {
// The statement must be a variable declaration statement.
if (!ts.isVariableStatement(stmt)) {
return false;
}
// It must be exported.
if (stmt.modifiers === undefined ||
!stmt.modifiers.some(mod => mod.kind === ts.SyntaxKind.ExportKeyword)) {
return false;
}
// It must declare ITS_JUST_ANGULAR.
return stmt.declarationList.declarations.some(decl => {
// The declaration must match the name.
if (!ts.isIdentifier(decl.name) || decl.name.text !== 'ITS_JUST_ANGULAR') {
return false;
}
// It must initialize the variable to true.
if (decl.initializer === undefined || decl.initializer.kind !== ts.SyntaxKind.TrueKeyword) {
return false;
}
// This definition matches.
return true;
});
});
}
export class ReferenceGraphAdapter implements ReferencesRegistry {
constructor(private graph: ReferenceGraph) {}
add(source: ts.Declaration, ...references: Reference<ts.Declaration>[]): void {
for (const {node} of references) {
let sourceFile = node.getSourceFile();
if (sourceFile === undefined) {
sourceFile = ts.getOriginalNode(node).getSourceFile();
}
// Only record local references (not references into .d.ts files).
if (sourceFile === undefined || !isDtsPath(sourceFile.fileName)) {
this.graph.add(source, node);
}
}
}
}
function shouldEnablePerfTracing(options: api.CompilerOptions): boolean {
return options.tracePerformance !== undefined;
}