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-01-16 17:22:53 +00:00
|
|
|
import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, NoopReferencesRegistry, PipeDecoratorHandler, ReferencesRegistry, SelectorScopeRegistry} 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';
|
2018-11-16 17:01:56 +01:00
|
|
|
import {ImportRewriter, ModuleResolver, NoopImportRewriter, R3SymbolsImportRewriter, Reference, TsReferenceResolver} from './imports';
|
2018-12-18 09:48:15 -08:00
|
|
|
import {PartialEvaluator} from './partial_evaluator';
|
|
|
|
import {TypeScriptReflectionHost} from './reflection';
|
2019-01-16 17:22:53 +00:00
|
|
|
import {HostResourceLoader} from './resource_loader';
|
2018-11-16 17:56:18 +01:00
|
|
|
import {NgModuleRouteAnalyzer} from './routing';
|
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';
|
2018-05-31 15:50:02 -07:00
|
|
|
import {IvyCompilation, ivyTransformFactory} from './transform';
|
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';
|
2018-12-13 11:52:20 -08:00
|
|
|
import {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;
|
2018-08-27 11:11:02 -07:00
|
|
|
private rootDirs: string[];
|
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
|
|
|
|
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) {
|
2018-08-27 11:11:02 -07:00
|
|
|
this.rootDirs = [];
|
|
|
|
if (options.rootDirs !== undefined) {
|
|
|
|
this.rootDirs.push(...options.rootDirs);
|
|
|
|
} else if (options.rootDir !== undefined) {
|
|
|
|
this.rootDirs.push(options.rootDir);
|
|
|
|
} else {
|
|
|
|
this.rootDirs.push(host.getCurrentDirectory());
|
|
|
|
}
|
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;
|
|
|
|
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) {
|
|
|
|
const ctx = new TypeCheckContext();
|
|
|
|
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[] {
|
|
|
|
if (entryRoute !== undefined) {
|
|
|
|
throw new Error(
|
|
|
|
`Listing specific routes is unsupported for now (got query for ${entryRoute})`);
|
|
|
|
}
|
|
|
|
this.ensureAnalyzed();
|
|
|
|
return this.routeAnalyzer !.listLazyRoutes();
|
|
|
|
}
|
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;
|
|
|
|
|
2018-08-23 14:34:55 -07:00
|
|
|
this.ensureAnalyzed();
|
2018-04-06 09:53:10 -07:00
|
|
|
|
|
|
|
// Since there is no .d.ts transformation API, .d.ts files are transformed during write.
|
|
|
|
const writeFile: ts.WriteFileCallback =
|
|
|
|
(fileName: string, data: string, writeByteOrderMark: boolean,
|
|
|
|
onError: ((message: string) => void) | undefined,
|
|
|
|
sourceFiles: ReadonlyArray<ts.SourceFile>) => {
|
|
|
|
if (fileName.endsWith('.d.ts')) {
|
|
|
|
data = sourceFiles.reduce(
|
2018-07-26 22:44:07 +03:00
|
|
|
(data, sf) => this.compilation !.transformedDtsFor(sf.fileName, data), data);
|
2019-01-10 10:40:24 -08:00
|
|
|
} else 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;
|
|
|
|
const beforeTransforms =
|
2019-01-08 11:49:58 -08:00
|
|
|
[ivyTransformFactory(this.compilation !, this.reflector, this.importRewriter, this.isCore)];
|
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
|
|
|
}
|
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
|
|
|
if (this.isCore) {
|
2019-01-03 12:23:00 +02:00
|
|
|
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
|
|
|
}
|
2019-01-03 12:23:00 +02:00
|
|
|
|
2018-04-06 09:53:10 -07:00
|
|
|
// Run the emit, including a custom transformer that will downlevel the Ivy decorators in code.
|
|
|
|
const emitResult = emitCallback({
|
|
|
|
program: this.tsProgram,
|
|
|
|
host: this.host,
|
|
|
|
options: this.options,
|
|
|
|
emitOnlyDtsFiles: false, writeFile,
|
|
|
|
customTransformers: {
|
2019-01-03 12:23:00 +02:00
|
|
|
before: beforeTransforms,
|
|
|
|
after: customTransforms && customTransforms.afterTs,
|
2018-04-06 09:53:10 -07:00
|
|
|
},
|
|
|
|
});
|
|
|
|
return emitResult;
|
|
|
|
}
|
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();
|
2018-12-18 11:09:21 -08:00
|
|
|
const refResolver = new TsReferenceResolver(this.tsProgram, checker, this.options, this.host);
|
|
|
|
const evaluator = new PartialEvaluator(this.reflector, checker, refResolver);
|
|
|
|
const scopeRegistry = new SelectorScopeRegistry(checker, this.reflector, refResolver);
|
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,
|
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.options.i18nUseExternalIds !== false, this.moduleResolver, this.cycleAnalyzer),
|
2018-12-18 09:48:15 -08:00
|
|
|
new DirectiveDecoratorHandler(this.reflector, evaluator, scopeRegistry, this.isCore),
|
2018-06-26 15:01:09 -07:00
|
|
|
new InjectableDecoratorHandler(this.reflector, this.isCore),
|
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,
|
|
|
|
this.routeAnalyzer),
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|