2018-04-06 09:53:10 -07:00
|
|
|
/**
|
|
|
|
* @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';
|
2018-08-28 14:13:22 -07:00
|
|
|
import {nocollapseHack} from '../transformers/nocollapse_hack';
|
2018-04-06 09:53:10 -07:00
|
|
|
|
2019-02-19 12:05:03 -08:00
|
|
|
import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, NoopReferencesRegistry, PipeDecoratorHandler, ReferencesRegistry} from './annotations';
|
2018-08-07 12:04:39 -07:00
|
|
|
import {BaseDefDecoratorHandler} from './annotations/src/base_def';
|
feat(ivy): detect cycles and use remote scoping of components if needed (#28169)
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.
Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.
TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.
To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.
FW-647 #resolve
PR Close #28169
2019-01-15 12:32:10 -08:00
|
|
|
import {CycleAnalyzer, ImportGraph} from './cycles';
|
2018-12-13 11:52:20 -08:00
|
|
|
import {ErrorCode, ngErrorCode} from './diagnostics';
|
|
|
|
import {FlatIndexGenerator, ReferenceGraph, checkForPrivateExports, findFlatIndexEntryPoint} from './entry_point';
|
2019-02-19 17:36:26 -08:00
|
|
|
import {AbsoluteModuleStrategy, AliasGenerator, AliasStrategy, FileToModuleHost, FileToModuleStrategy, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, R3SymbolsImportRewriter, Reference, ReferenceEmitter} from './imports';
|
2018-12-18 09:48:15 -08:00
|
|
|
import {PartialEvaluator} from './partial_evaluator';
|
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
|
|
|
import {AbsoluteFsPath, LogicalFileSystem} from './path';
|
2018-12-18 09:48:15 -08:00
|
|
|
import {TypeScriptReflectionHost} from './reflection';
|
2019-01-16 17:22:53 +00:00
|
|
|
import {HostResourceLoader} from './resource_loader';
|
2019-02-07 19:03:13 +02:00
|
|
|
import {NgModuleRouteAnalyzer, entryPointKeyFor} from './routing';
|
2019-02-19 12:05:03 -08:00
|
|
|
import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from './scope';
|
2018-12-07 14:37:32 -08:00
|
|
|
import {FactoryGenerator, FactoryInfo, GeneratedShimsHostWrapper, ShimGenerator, SummaryGenerator, 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';
|
2019-01-24 10:38:58 +00:00
|
|
|
import {IvyCompilation, declarationTransformFactory, ivyTransformFactory} from './transform';
|
2019-02-19 17:36:26 -08:00
|
|
|
import {aliasTransformFactory} from './transform/src/alias';
|
2018-09-21 14:03:55 -07:00
|
|
|
import {TypeCheckContext, TypeCheckProgramHost} from './typecheck';
|
2019-01-12 19:00:39 +01:00
|
|
|
import {normalizeSeparators} from './util/src/path';
|
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
|
|
|
import {getRootDirs, isDtsPath} from './util/src/typescript';
|
2018-04-06 09:53:10 -07:00
|
|
|
|
|
|
|
export class NgtscProgram implements api.Program {
|
|
|
|
private tsProgram: ts.Program;
|
2019-01-16 17:22:53 +00:00
|
|
|
private resourceManager: HostResourceLoader;
|
2018-06-26 15:01:09 -07:00
|
|
|
private compilation: IvyCompilation|undefined = undefined;
|
2018-07-27 22:57:44 -07:00
|
|
|
private factoryToSourceInfo: Map<string, FactoryInfo>|null = null;
|
|
|
|
private sourceToFactorySymbols: Map<string, Set<string>>|null = null;
|
|
|
|
private host: ts.CompilerHost;
|
2018-06-26 15:01:09 -07:00
|
|
|
private _coreImportsFrom: ts.SourceFile|null|undefined = undefined;
|
2019-01-08 11:49:58 -08:00
|
|
|
private _importRewriter: ImportRewriter|undefined = undefined;
|
2018-06-26 15:01:09 -07:00
|
|
|
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[];
|
2018-08-28 14:13:22 -07:00
|
|
|
private closureCompilerEnabled: boolean;
|
2018-12-13 11:52:20 -08:00
|
|
|
private entryPoint: ts.SourceFile|null;
|
|
|
|
private exportReferenceGraph: ReferenceGraph|null = null;
|
|
|
|
private flatIndexGenerator: FlatIndexGenerator|null = null;
|
2018-11-16 17:56:18 +01:00
|
|
|
private routeAnalyzer: NgModuleRouteAnalyzer|null = null;
|
2018-12-13 11:52:20 -08:00
|
|
|
|
|
|
|
private constructionDiagnostics: ts.Diagnostic[] = [];
|
2018-11-16 17:01:56 +01:00
|
|
|
private moduleResolver: ModuleResolver;
|
feat(ivy): detect cycles and use remote scoping of components if needed (#28169)
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.
Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.
TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.
To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.
FW-647 #resolve
PR Close #28169
2019-01-15 12:32:10 -08:00
|
|
|
private cycleAnalyzer: CycleAnalyzer;
|
2018-04-06 09:53:10 -07:00
|
|
|
|
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;
|
2018-07-27 22:57:44 -07:00
|
|
|
|
2018-04-06 09:53:10 -07:00
|
|
|
constructor(
|
|
|
|
rootNames: ReadonlyArray<string>, private options: api.CompilerOptions,
|
2018-07-27 22:57:44 -07:00
|
|
|
host: api.CompilerHost, oldProgram?: api.Program) {
|
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);
|
2018-08-28 14:13:22 -07:00
|
|
|
this.closureCompilerEnabled = !!options.annotateForClosureCompiler;
|
2019-01-16 17:22:53 +00:00
|
|
|
this.resourceManager = new HostResourceLoader(host, options);
|
2018-10-16 14:47:08 -07:00
|
|
|
const shouldGenerateShims = options.allowEmptyCodegenFiles || false;
|
2018-07-27 22:57:44 -07:00
|
|
|
this.host = host;
|
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;
|
|
|
|
}
|
2018-07-27 22:57:44 -07:00
|
|
|
let rootFiles = [...rootNames];
|
2018-12-05 16:05:29 -08:00
|
|
|
|
|
|
|
const generators: ShimGenerator[] = [];
|
2018-10-16 14:47:08 -07:00
|
|
|
if (shouldGenerateShims) {
|
|
|
|
// Summary generation.
|
2018-10-16 15:07:46 -07:00
|
|
|
const summaryGenerator = SummaryGenerator.forRootFiles(rootNames);
|
2018-10-16 14:47:08 -07:00
|
|
|
|
|
|
|
// Factory generation.
|
|
|
|
const factoryGenerator = FactoryGenerator.forRootFiles(rootNames);
|
|
|
|
const factoryFileMap = factoryGenerator.factoryFileMap;
|
2018-07-27 22:57:44 -07:00
|
|
|
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});
|
|
|
|
});
|
2018-10-16 15:07:46 -07:00
|
|
|
|
|
|
|
const factoryFileNames = Array.from(factoryFileMap.keys());
|
|
|
|
rootFiles.push(...factoryFileNames, ...summaryGenerator.getSummaryFileNames());
|
2018-12-05 16:05:29 -08:00
|
|
|
generators.push(summaryGenerator, factoryGenerator);
|
|
|
|
}
|
|
|
|
|
2018-12-13 11:52:20 -08:00
|
|
|
let entryPoint: string|null = null;
|
2018-12-05 16:05:29 -08:00
|
|
|
if (options.flatModuleOutFile !== undefined) {
|
2018-12-13 11:52:20 -08:00
|
|
|
entryPoint = findFlatIndexEntryPoint(rootNames);
|
|
|
|
if (entryPoint === null) {
|
2018-12-05 16:05:29 -08:00
|
|
|
// 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.
|
2018-12-13 11:52:20 -08:00
|
|
|
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;
|
2019-01-12 19:00:39 +01:00
|
|
|
const flatModuleOutFile = normalizeSeparators(options.flatModuleOutFile);
|
2018-12-13 11:52:20 -08:00
|
|
|
this.flatIndexGenerator =
|
2019-01-12 19:00:39 +01:00
|
|
|
new FlatIndexGenerator(entryPoint, flatModuleOutFile, flatModuleId);
|
2018-12-13 11:52:20 -08:00
|
|
|
generators.push(this.flatIndexGenerator);
|
|
|
|
rootFiles.push(this.flatIndexGenerator.flatIndexPath);
|
2018-12-05 16:05:29 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (generators.length > 0) {
|
|
|
|
this.host = new GeneratedShimsHostWrapper(host, generators);
|
2018-07-27 22:57:44 -07:00
|
|
|
}
|
2018-06-26 15:01:09 -07:00
|
|
|
|
2018-04-06 09:53:10 -07:00
|
|
|
this.tsProgram =
|
2018-07-27 22:57:44 -07:00
|
|
|
ts.createProgram(rootFiles, options, this.host, oldProgram && oldProgram.getTsProgram());
|
2018-12-13 11:52:20 -08:00
|
|
|
|
|
|
|
this.entryPoint = entryPoint !== null ? this.tsProgram.getSourceFile(entryPoint) || null : null;
|
2018-11-16 17:01:56 +01:00
|
|
|
this.moduleResolver = new ModuleResolver(this.tsProgram, options, this.host);
|
feat(ivy): detect cycles and use remote scoping of components if needed (#28169)
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.
Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.
TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.
To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.
FW-647 #resolve
PR Close #28169
2019-01-15 12:32:10 -08:00
|
|
|
this.cycleAnalyzer = new CycleAnalyzer(new ImportGraph(this.moduleResolver));
|
2018-04-06 09:53:10 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
getTsProgram(): ts.Program { return this.tsProgram; }
|
|
|
|
|
|
|
|
getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken|
|
|
|
|
undefined): ReadonlyArray<ts.Diagnostic> {
|
|
|
|
return this.tsProgram.getOptionsDiagnostics(cancellationToken);
|
|
|
|
}
|
|
|
|
|
|
|
|
getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken|
|
2018-12-13 11:52:20 -08:00
|
|
|
undefined): ReadonlyArray<ts.Diagnostic|api.Diagnostic> {
|
|
|
|
return this.constructionDiagnostics;
|
2018-04-06 09:53:10 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
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(
|
2018-08-23 14:34:55 -07:00
|
|
|
fileName?: string|undefined, cancellationToken?: ts.CancellationToken|
|
|
|
|
undefined): ReadonlyArray<ts.Diagnostic|api.Diagnostic> {
|
|
|
|
const compilation = this.ensureAnalyzed();
|
2018-09-21 14:03:55 -07:00
|
|
|
const diagnostics = [...compilation.diagnostics];
|
|
|
|
if (!!this.options.fullTemplateTypeCheck) {
|
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 ctx = new TypeCheckContext(this.refEmitter !);
|
2018-09-21 14:03:55 -07:00
|
|
|
compilation.typeCheck(ctx);
|
|
|
|
diagnostics.push(...this.compileTypeCheckProgram(ctx));
|
|
|
|
}
|
2018-12-13 11:52:20 -08:00
|
|
|
if (this.entryPoint !== null && this.exportReferenceGraph !== null) {
|
|
|
|
diagnostics.push(...checkForPrivateExports(
|
|
|
|
this.entryPoint, this.tsProgram.getTypeChecker(), this.exportReferenceGraph));
|
|
|
|
}
|
2018-09-21 14:03:55 -07:00
|
|
|
return diagnostics;
|
2018-04-06 09:53:10 -07:00
|
|
|
}
|
|
|
|
|
2018-06-26 15:01:09 -07:00
|
|
|
async loadNgStructureAsync(): Promise<void> {
|
|
|
|
if (this.compilation === undefined) {
|
|
|
|
this.compilation = this.makeCompilation();
|
|
|
|
}
|
2018-07-26 13:32:23 -07:00
|
|
|
await Promise.all(this.tsProgram.getSourceFiles()
|
|
|
|
.filter(file => !file.fileName.endsWith('.d.ts'))
|
|
|
|
.map(file => this.compilation !.analyzeAsync(file))
|
|
|
|
.filter((result): result is Promise<void> => result !== undefined));
|
feat(ivy): detect cycles and use remote scoping of components if needed (#28169)
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.
Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.
TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.
To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.
FW-647 #resolve
PR Close #28169
2019-01-15 12:32:10 -08:00
|
|
|
this.compilation.resolve();
|
2018-06-26 15:01:09 -07:00
|
|
|
}
|
2018-04-06 09:53:10 -07:00
|
|
|
|
2018-11-16 17:56:18 +01:00
|
|
|
listLazyRoutes(entryRoute?: string|undefined): api.LazyRoute[] {
|
2019-02-07 19:03:13 +02:00
|
|
|
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(
|
2019-02-19 17:29:04 +01:00
|
|
|
`Failed to list lazy routes: Resolution of relative paths (${entryRoute}) is not supported.`);
|
2019-02-07 19:03:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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 resolved = ts.resolveModuleName(entryPath, containingFile, this.options, this.host);
|
|
|
|
|
|
|
|
if (resolved.resolvedModule) {
|
|
|
|
entryRoute = entryPointKeyFor(resolved.resolvedModule.resolvedFileName, moduleName);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-16 17:56:18 +01:00
|
|
|
this.ensureAnalyzed();
|
2019-02-05 16:47:35 +02:00
|
|
|
return this.routeAnalyzer !.listLazyRoutes(entryRoute);
|
2018-11-16 17:56:18 +01:00
|
|
|
}
|
2018-04-06 09:53:10 -07:00
|
|
|
|
|
|
|
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.');
|
|
|
|
}
|
|
|
|
|
2018-08-23 14:34:55 -07:00
|
|
|
private ensureAnalyzed(): IvyCompilation {
|
|
|
|
if (this.compilation === undefined) {
|
|
|
|
this.compilation = this.makeCompilation();
|
|
|
|
this.tsProgram.getSourceFiles()
|
|
|
|
.filter(file => !file.fileName.endsWith('.d.ts'))
|
|
|
|
.forEach(file => this.compilation !.analyzeSync(file));
|
feat(ivy): detect cycles and use remote scoping of components if needed (#28169)
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.
Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.
TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.
To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.
FW-647 #resolve
PR Close #28169
2019-01-15 12:32:10 -08:00
|
|
|
this.compilation.resolve();
|
2018-08-23 14:34:55 -07:00
|
|
|
}
|
|
|
|
return this.compilation;
|
|
|
|
}
|
|
|
|
|
2018-04-06 09:53:10 -07:00
|
|
|
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;
|
|
|
|
|
2019-01-24 10:38:58 +00:00
|
|
|
const compilation = this.ensureAnalyzed();
|
2018-04-06 09:53:10 -07:00
|
|
|
|
|
|
|
const writeFile: ts.WriteFileCallback =
|
|
|
|
(fileName: string, data: string, writeByteOrderMark: boolean,
|
|
|
|
onError: ((message: string) => void) | undefined,
|
|
|
|
sourceFiles: ReadonlyArray<ts.SourceFile>) => {
|
2019-01-24 10:38:58 +00:00
|
|
|
if (this.closureCompilerEnabled && fileName.endsWith('.js')) {
|
2018-08-28 14:13:22 -07:00
|
|
|
data = nocollapseHack(data);
|
2018-04-06 09:53:10 -07:00
|
|
|
}
|
|
|
|
this.host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
|
|
|
|
};
|
|
|
|
|
2019-01-03 12:23:00 +02:00
|
|
|
const customTransforms = opts && opts.customTransformers;
|
2019-02-19 17:36:26 -08:00
|
|
|
const beforeTransforms = [
|
|
|
|
ivyTransformFactory(
|
|
|
|
compilation, this.reflector, this.importRewriter, this.isCore,
|
|
|
|
this.closureCompilerEnabled),
|
|
|
|
aliasTransformFactory(compilation.exportStatements) as ts.TransformerFactory<ts.SourceFile>,
|
|
|
|
];
|
|
|
|
const afterDeclarationsTransforms = [
|
|
|
|
declarationTransformFactory(compilation),
|
|
|
|
];
|
|
|
|
|
2019-01-03 12:23:00 +02:00
|
|
|
|
2018-07-27 22:57:44 -07:00
|
|
|
if (this.factoryToSourceInfo !== null) {
|
2019-01-03 12:23:00 +02:00
|
|
|
beforeTransforms.push(
|
2019-01-08 13:02:11 -08:00
|
|
|
generatedFactoryTransform(this.factoryToSourceInfo, this.importRewriter));
|
2018-07-27 22:57:44 -07:00
|
|
|
}
|
2019-02-01 15:33:41 -08:00
|
|
|
beforeTransforms.push(ivySwitchTransform);
|
2019-01-03 12:23:00 +02:00
|
|
|
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
|
|
|
}
|
2019-01-03 12:23:00 +02:00
|
|
|
|
2019-03-06 14:26:56 -08:00
|
|
|
const emitResults: ts.EmitResult[] = [];
|
|
|
|
for (const targetSourceFile of this.tsProgram.getSourceFiles()) {
|
|
|
|
if (targetSourceFile.isDeclarationFile) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
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,
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2018-04-06 09:53:10 -07:00
|
|
|
// Run the emit, including a custom transformer that will downlevel the Ivy decorators in code.
|
2019-03-06 14:26:56 -08:00
|
|
|
return ((opts && opts.mergeEmitResultsCallback) || mergeEmitResults)(emitResults);
|
2018-04-06 09:53:10 -07:00
|
|
|
}
|
2018-06-26 15:01:09 -07:00
|
|
|
|
2018-09-21 14:03:55 -07:00
|
|
|
private compileTypeCheckProgram(ctx: TypeCheckContext): ReadonlyArray<ts.Diagnostic> {
|
|
|
|
const host = new TypeCheckProgramHost(this.tsProgram, this.host, ctx);
|
|
|
|
const auxProgram = ts.createProgram({
|
|
|
|
host,
|
|
|
|
rootNames: this.tsProgram.getRootFileNames(),
|
|
|
|
oldProgram: this.tsProgram,
|
|
|
|
options: this.options,
|
|
|
|
});
|
|
|
|
return auxProgram.getSemanticDiagnostics();
|
|
|
|
}
|
|
|
|
|
2018-06-26 15:01:09 -07:00
|
|
|
private makeCompilation(): IvyCompilation {
|
|
|
|
const checker = this.tsProgram.getTypeChecker();
|
2019-02-19 17:36:26 -08:00
|
|
|
|
|
|
|
let aliasGenerator: AliasGenerator|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
|
|
|
// Construct the ReferenceEmitter.
|
|
|
|
if (this.fileToModuleHost === null || !this.options._useHostForImportGeneration) {
|
|
|
|
// 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),
|
|
|
|
// Finally, check if the reference is being written into a file within the project's logical
|
|
|
|
// file system, and use a relative import if so. If this fails, ReferenceEmitter will throw
|
|
|
|
// an error.
|
|
|
|
new LogicalProjectStrategy(checker, new LogicalFileSystem(this.rootDirs)),
|
|
|
|
]);
|
|
|
|
} 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(),
|
2019-02-19 17:36:26 -08:00
|
|
|
// 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(checker, this.fileToModuleHost),
|
|
|
|
]);
|
2019-02-19 17:36:26 -08:00
|
|
|
aliasGenerator = new AliasGenerator(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);
|
2019-02-19 17:36:26 -08:00
|
|
|
const depScopeReader =
|
|
|
|
new MetadataDtsModuleScopeResolver(checker, this.reflector, aliasGenerator);
|
|
|
|
const scopeRegistry =
|
|
|
|
new LocalModuleScopeRegistry(depScopeReader, this.refEmitter, aliasGenerator);
|
2019-02-19 12:05:03 -08:00
|
|
|
|
2018-12-13 11:52:20 -08:00
|
|
|
|
|
|
|
// 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();
|
|
|
|
}
|
2018-06-26 15:01:09 -07:00
|
|
|
|
2018-11-16 17:56:18 +01:00
|
|
|
this.routeAnalyzer = new NgModuleRouteAnalyzer(this.moduleResolver, evaluator);
|
|
|
|
|
2018-06-26 15:01:09 -07:00
|
|
|
// Set up the IvyCompilation, which manages state for the Ivy transformer.
|
|
|
|
const handlers = [
|
2018-12-18 09:48:15 -08:00
|
|
|
new BaseDefDecoratorHandler(this.reflector, evaluator),
|
2018-06-26 15:01:09 -07:00
|
|
|
new ComponentDecoratorHandler(
|
2019-01-16 17:22:53 +00:00
|
|
|
this.reflector, evaluator, scopeRegistry, this.isCore, this.resourceManager,
|
|
|
|
this.rootDirs, this.options.preserveWhitespaces || false,
|
2019-02-19 12:05:03 -08:00
|
|
|
this.options.i18nUseExternalIds !== false, this.moduleResolver, this.cycleAnalyzer,
|
|
|
|
this.refEmitter),
|
2018-12-18 09:48:15 -08:00
|
|
|
new DirectiveDecoratorHandler(this.reflector, evaluator, scopeRegistry, this.isCore),
|
feat(ivy): compile @Injectable on classes not meant for DI (#28523)
In the past, @Injectable had no side effects and existing Angular code is
therefore littered with @Injectable usage on classes which are not intended
to be injected.
A common example is:
@Injectable()
class Foo {
constructor(private notInjectable: string) {}
}
and somewhere else:
providers: [{provide: Foo, useFactory: ...})
Here, there is no need for Foo to be injectable - indeed, it's impossible
for the DI system to create an instance of it, as it has a non-injectable
constructor. The provider configures a factory for the DI system to be
able to create instances of Foo.
Adding @Injectable in Ivy signifies that the class's own constructor, and
not a provider, determines how the class will be created.
This commit adds logic to compile classes which are marked with @Injectable
but are otherwise not injectable, and create an ngInjectableDef field with
a factory function that throws an error. This way, existing code in the wild
continues to compile, but if someone attempts to use the injectable it will
fail with a useful error message.
In the case where strictInjectionParameters is set to true, a compile-time
error is thrown instead of the runtime error, as ngtsc has enough
information to determine when injection couldn't possibly be valid.
PR Close #28523
2019-01-31 14:23:54 -08:00
|
|
|
new InjectableDecoratorHandler(
|
|
|
|
this.reflector, this.isCore, this.options.strictInjectionParameters || false),
|
2018-11-13 14:40:54 +00:00
|
|
|
new NgModuleDecoratorHandler(
|
2018-11-16 17:56:18 +01:00
|
|
|
this.reflector, evaluator, scopeRegistry, referencesRegistry, this.isCore,
|
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.routeAnalyzer, this.refEmitter),
|
2018-12-18 09:48:15 -08:00
|
|
|
new PipeDecoratorHandler(this.reflector, evaluator, scopeRegistry, this.isCore),
|
2018-06-26 15:01:09 -07:00
|
|
|
];
|
|
|
|
|
2018-07-27 22:57:44 -07:00
|
|
|
return new IvyCompilation(
|
2019-01-08 11:49:58 -08:00
|
|
|
handlers, checker, this.reflector, this.importRewriter, this.sourceToFactorySymbols);
|
2018-06-26 15:01:09 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
2019-01-08 11:49:58 -08:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
2018-04-06 09:53:10 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
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};
|
|
|
|
}
|
2018-06-20 15:54:16 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2018-12-13 11:52:20 -08:00
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|