fix(compiler-cli): ensure the compiler tracks `ts.Program`s correctly (#41291)

`NgCompiler` previously had a notion of the "next" `ts.Program`, which
served two purposes:

* it allowed a client using the `ts.createProgram` API to query for the
  latest program produced by the previous `NgCompiler`, as a starting
  point for building the _next_ program that incorporated any new user
  changes.

* it allowed the old `NgCompiler` to be queried for the `ts.Program` on
  which all prior state is based, which is needed to compute the delta
  from the new program to ultimately determine how much of the prior
  state can be reused.

This system contained a flaw: it relied on the `NgCompiler` knowing when
the `ts.Program` would be changed. This works fine for changes that
originate in `NgCompiler` APIs, but a client of the `TemplateTypeChecker`
may use that API in ways that create new `ts.Program`s without the
`NgCompiler`'s knowledge. This caused the `NgCompiler`'s concept of the
"next" program to get out of sync, causing incorrectness in future
incremental analysis.

This refactoring cleans up the compiler's `ts.Program` management in
several ways:

* `TypeCheckingProgramStrategy`, the API which controls `ts.Program`
  updating, is renamed to the `ProgramDriver` and extracted to a separate
  ngtsc package.

* It loses its responsibility of determining component shim filenames. That
  functionality now lives exclusively in the template type-checking package.

* The "next" `ts.Program` concept is renamed to the "current" program, as
  the "next" name was misleading in several ways.

* `NgCompiler` now wraps the `ProgramDriver` used in the
  `TemplateTypeChecker` to know when a new `ts.Program` is created,
  regardless of which API drove the creation, which actually fixes the bug.

PR Close #41291
This commit is contained in:
Alex Rickabaugh 2021-03-19 17:06:10 -07:00 committed by Zach Arend
parent 10a7c87692
commit deacc741e0
30 changed files with 366 additions and 324 deletions

View File

@ -33,6 +33,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/indexer", "//packages/compiler-cli/src/ngtsc/indexer",
"//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/translator",

View File

@ -26,6 +26,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/modulewithproviders", "//packages/compiler-cli/src/ngtsc/modulewithproviders",
"//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/resource", "//packages/compiler-cli/src/ngtsc/resource",
"//packages/compiler-cli/src/ngtsc/routing", "//packages/compiler-cli/src/ngtsc/routing",

View File

@ -13,7 +13,7 @@ import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecorato
import {CycleAnalyzer, CycleHandlingStrategy, ImportGraph} from '../../cycles'; import {CycleAnalyzer, CycleHandlingStrategy, ImportGraph} from '../../cycles';
import {COMPILER_ERRORS_WITH_GUIDES, ERROR_DETAILS_PAGE_BASE_URL, ErrorCode, ngErrorCode} from '../../diagnostics'; import {COMPILER_ERRORS_WITH_GUIDES, ERROR_DETAILS_PAGE_BASE_URL, ErrorCode, ngErrorCode} from '../../diagnostics';
import {checkForPrivateExports, ReferenceGraph} from '../../entry_point'; import {checkForPrivateExports, ReferenceGraph} from '../../entry_point';
import {LogicalFileSystem, resolve} from '../../file_system'; import {AbsoluteFsPath, LogicalFileSystem, resolve} from '../../file_system';
import {AbsoluteModuleStrategy, AliasingHost, AliasStrategy, DefaultImportTracker, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesAliasingHost, UnifiedModulesStrategy} from '../../imports'; import {AbsoluteModuleStrategy, AliasingHost, AliasStrategy, DefaultImportTracker, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesAliasingHost, UnifiedModulesStrategy} from '../../imports';
import {IncrementalBuildStrategy, IncrementalDriver} from '../../incremental'; import {IncrementalBuildStrategy, IncrementalDriver} from '../../incremental';
import {SemanticSymbol} from '../../incremental/semantic_graph'; import {SemanticSymbol} from '../../incremental/semantic_graph';
@ -21,9 +21,8 @@ import {generateAnalysis, IndexedComponent, IndexingContext} from '../../indexer
import {ComponentResources, CompoundMetadataReader, CompoundMetadataRegistry, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry, MetadataReader, ResourceRegistry} from '../../metadata'; import {ComponentResources, CompoundMetadataReader, CompoundMetadataRegistry, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry, MetadataReader, ResourceRegistry} from '../../metadata';
import {ModuleWithProvidersScanner} from '../../modulewithproviders'; import {ModuleWithProvidersScanner} from '../../modulewithproviders';
import {PartialEvaluator} from '../../partial_evaluator'; import {PartialEvaluator} from '../../partial_evaluator';
import {ActivePerfRecorder} from '../../perf'; import {ActivePerfRecorder, DelegatingPerfRecorder, PerfCheckpoint, PerfEvent, PerfPhase} from '../../perf';
import {PerfCheckpoint, PerfEvent, PerfPhase} from '../../perf/src/api'; import {ProgramDriver, UpdateMode} from '../../program_driver';
import {DelegatingPerfRecorder} from '../../perf/src/recorder';
import {DeclarationNode, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {DeclarationNode, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {AdapterResourceLoader} from '../../resource'; import {AdapterResourceLoader} from '../../resource';
import {entryPointKeyFor, NgModuleRouteAnalyzer} from '../../routing'; import {entryPointKeyFor, NgModuleRouteAnalyzer} from '../../routing';
@ -32,7 +31,7 @@ import {generatedFactoryTransform} from '../../shims';
import {ivySwitchTransform} from '../../switch'; import {ivySwitchTransform} from '../../switch';
import {aliasTransformFactory, CompilationMode, declarationTransformFactory, DecoratorHandler, DtsTransformRegistry, ivyTransformFactory, TraitCompiler} from '../../transform'; import {aliasTransformFactory, CompilationMode, declarationTransformFactory, DecoratorHandler, DtsTransformRegistry, ivyTransformFactory, TraitCompiler} from '../../transform';
import {TemplateTypeCheckerImpl} from '../../typecheck'; import {TemplateTypeCheckerImpl} from '../../typecheck';
import {OptimizeFor, TemplateTypeChecker, TypeCheckingConfig, TypeCheckingProgramStrategy} from '../../typecheck/api'; import {OptimizeFor, TemplateTypeChecker, TypeCheckingConfig} from '../../typecheck/api';
import {getSourceFileOrNull, isDtsPath, resolveModuleName} from '../../util/src/typescript'; import {getSourceFileOrNull, isDtsPath, resolveModuleName} from '../../util/src/typescript';
import {LazyRoute, NgCompilerAdapter, NgCompilerOptions} from '../api'; import {LazyRoute, NgCompilerAdapter, NgCompilerOptions} from '../api';
@ -78,7 +77,7 @@ export interface FreshCompilationTicket {
kind: CompilationTicketKind.Fresh; kind: CompilationTicketKind.Fresh;
options: NgCompilerOptions; options: NgCompilerOptions;
incrementalBuildStrategy: IncrementalBuildStrategy; incrementalBuildStrategy: IncrementalBuildStrategy;
typeCheckingProgramStrategy: TypeCheckingProgramStrategy; programDriver: ProgramDriver;
enableTemplateTypeChecker: boolean; enableTemplateTypeChecker: boolean;
usePoisonedData: boolean; usePoisonedData: boolean;
tsProgram: ts.Program; tsProgram: ts.Program;
@ -94,7 +93,7 @@ export interface IncrementalTypeScriptCompilationTicket {
oldProgram: ts.Program; oldProgram: ts.Program;
newProgram: ts.Program; newProgram: ts.Program;
incrementalBuildStrategy: IncrementalBuildStrategy; incrementalBuildStrategy: IncrementalBuildStrategy;
typeCheckingProgramStrategy: TypeCheckingProgramStrategy; programDriver: ProgramDriver;
newDriver: IncrementalDriver; newDriver: IncrementalDriver;
enableTemplateTypeChecker: boolean; enableTemplateTypeChecker: boolean;
usePoisonedData: boolean; usePoisonedData: boolean;
@ -123,15 +122,15 @@ export type CompilationTicket = FreshCompilationTicket|IncrementalTypeScriptComp
*/ */
export function freshCompilationTicket( export function freshCompilationTicket(
tsProgram: ts.Program, options: NgCompilerOptions, tsProgram: ts.Program, options: NgCompilerOptions,
incrementalBuildStrategy: IncrementalBuildStrategy, incrementalBuildStrategy: IncrementalBuildStrategy, programDriver: ProgramDriver,
typeCheckingProgramStrategy: TypeCheckingProgramStrategy, perfRecorder: ActivePerfRecorder|null, perfRecorder: ActivePerfRecorder|null, enableTemplateTypeChecker: boolean,
enableTemplateTypeChecker: boolean, usePoisonedData: boolean): CompilationTicket { usePoisonedData: boolean): CompilationTicket {
return { return {
kind: CompilationTicketKind.Fresh, kind: CompilationTicketKind.Fresh,
tsProgram, tsProgram,
options, options,
incrementalBuildStrategy, incrementalBuildStrategy,
typeCheckingProgramStrategy, programDriver,
enableTemplateTypeChecker, enableTemplateTypeChecker,
usePoisonedData, usePoisonedData,
perfRecorder: perfRecorder ?? ActivePerfRecorder.zeroedToNow(), perfRecorder: perfRecorder ?? ActivePerfRecorder.zeroedToNow(),
@ -144,17 +143,16 @@ export function freshCompilationTicket(
*/ */
export function incrementalFromCompilerTicket( export function incrementalFromCompilerTicket(
oldCompiler: NgCompiler, newProgram: ts.Program, oldCompiler: NgCompiler, newProgram: ts.Program,
incrementalBuildStrategy: IncrementalBuildStrategy, incrementalBuildStrategy: IncrementalBuildStrategy, programDriver: ProgramDriver,
typeCheckingProgramStrategy: TypeCheckingProgramStrategy, modifiedResourceFiles: Set<string>, modifiedResourceFiles: Set<string>, perfRecorder: ActivePerfRecorder|null): CompilationTicket {
perfRecorder: ActivePerfRecorder|null): CompilationTicket { const oldProgram = oldCompiler.getCurrentProgram();
const oldProgram = oldCompiler.getNextProgram();
const oldDriver = oldCompiler.incrementalStrategy.getIncrementalDriver(oldProgram); const oldDriver = oldCompiler.incrementalStrategy.getIncrementalDriver(oldProgram);
if (oldDriver === null) { if (oldDriver === null) {
// No incremental step is possible here, since no IncrementalDriver was found for the old // No incremental step is possible here, since no IncrementalDriver was found for the old
// program. // program.
return freshCompilationTicket( return freshCompilationTicket(
newProgram, oldCompiler.options, incrementalBuildStrategy, typeCheckingProgramStrategy, newProgram, oldCompiler.options, incrementalBuildStrategy, programDriver, perfRecorder,
perfRecorder, oldCompiler.enableTemplateTypeChecker, oldCompiler.usePoisonedData); oldCompiler.enableTemplateTypeChecker, oldCompiler.usePoisonedData);
} }
if (perfRecorder === null) { if (perfRecorder === null) {
@ -170,7 +168,7 @@ export function incrementalFromCompilerTicket(
usePoisonedData: oldCompiler.usePoisonedData, usePoisonedData: oldCompiler.usePoisonedData,
options: oldCompiler.options, options: oldCompiler.options,
incrementalBuildStrategy, incrementalBuildStrategy,
typeCheckingProgramStrategy, programDriver,
newDriver, newDriver,
oldProgram, oldProgram,
newProgram, newProgram,
@ -185,13 +183,12 @@ export function incrementalFromCompilerTicket(
export function incrementalFromDriverTicket( export function incrementalFromDriverTicket(
oldProgram: ts.Program, oldDriver: IncrementalDriver, newProgram: ts.Program, oldProgram: ts.Program, oldDriver: IncrementalDriver, newProgram: ts.Program,
options: NgCompilerOptions, incrementalBuildStrategy: IncrementalBuildStrategy, options: NgCompilerOptions, incrementalBuildStrategy: IncrementalBuildStrategy,
typeCheckingProgramStrategy: TypeCheckingProgramStrategy, modifiedResourceFiles: Set<string>, programDriver: ProgramDriver, modifiedResourceFiles: Set<string>,
perfRecorder: ActivePerfRecorder|null, enableTemplateTypeChecker: boolean, perfRecorder: ActivePerfRecorder|null, enableTemplateTypeChecker: boolean,
usePoisonedData: boolean): CompilationTicket { usePoisonedData: boolean): CompilationTicket {
if (perfRecorder === null) { if (perfRecorder === null) {
perfRecorder = ActivePerfRecorder.zeroedToNow(); perfRecorder = ActivePerfRecorder.zeroedToNow();
} }
const newDriver = IncrementalDriver.reconcile( const newDriver = IncrementalDriver.reconcile(
oldProgram, oldDriver, newProgram, modifiedResourceFiles, perfRecorder); oldProgram, oldDriver, newProgram, modifiedResourceFiles, perfRecorder);
return { return {
@ -201,7 +198,7 @@ export function incrementalFromDriverTicket(
options, options,
incrementalBuildStrategy, incrementalBuildStrategy,
newDriver, newDriver,
typeCheckingProgramStrategy, programDriver,
enableTemplateTypeChecker, enableTemplateTypeChecker,
usePoisonedData, usePoisonedData,
perfRecorder, perfRecorder,
@ -255,7 +252,7 @@ export class NgCompiler {
private nonTemplateDiagnostics: ts.Diagnostic[]|null = null; private nonTemplateDiagnostics: ts.Diagnostic[]|null = null;
private closureCompilerEnabled: boolean; private closureCompilerEnabled: boolean;
private nextProgram: ts.Program; private currentProgram: ts.Program;
private entryPoint: ts.SourceFile|null; private entryPoint: ts.SourceFile|null;
private moduleResolver: ModuleResolver; private moduleResolver: ModuleResolver;
private resourceManager: AdapterResourceLoader; private resourceManager: AdapterResourceLoader;
@ -286,7 +283,7 @@ export class NgCompiler {
adapter, adapter,
ticket.options, ticket.options,
ticket.tsProgram, ticket.tsProgram,
ticket.typeCheckingProgramStrategy, ticket.programDriver,
ticket.incrementalBuildStrategy, ticket.incrementalBuildStrategy,
IncrementalDriver.fresh(ticket.tsProgram), IncrementalDriver.fresh(ticket.tsProgram),
ticket.enableTemplateTypeChecker, ticket.enableTemplateTypeChecker,
@ -298,7 +295,7 @@ export class NgCompiler {
adapter, adapter,
ticket.options, ticket.options,
ticket.newProgram, ticket.newProgram,
ticket.typeCheckingProgramStrategy, ticket.programDriver,
ticket.incrementalBuildStrategy, ticket.incrementalBuildStrategy,
ticket.newDriver, ticket.newDriver,
ticket.enableTemplateTypeChecker, ticket.enableTemplateTypeChecker,
@ -315,8 +312,8 @@ export class NgCompiler {
private constructor( private constructor(
private adapter: NgCompilerAdapter, private adapter: NgCompilerAdapter,
readonly options: NgCompilerOptions, readonly options: NgCompilerOptions,
private tsProgram: ts.Program, private inputProgram: ts.Program,
readonly typeCheckingProgramStrategy: TypeCheckingProgramStrategy, readonly programDriver: ProgramDriver,
readonly incrementalStrategy: IncrementalBuildStrategy, readonly incrementalStrategy: IncrementalBuildStrategy,
readonly incrementalDriver: IncrementalDriver, readonly incrementalDriver: IncrementalDriver,
readonly enableTemplateTypeChecker: boolean, readonly enableTemplateTypeChecker: boolean,
@ -329,11 +326,11 @@ export class NgCompiler {
this.constructionDiagnostics.push(incompatibleTypeCheckOptionsDiagnostic); this.constructionDiagnostics.push(incompatibleTypeCheckOptionsDiagnostic);
} }
this.nextProgram = tsProgram; this.currentProgram = inputProgram;
this.closureCompilerEnabled = !!this.options.annotateForClosureCompiler; this.closureCompilerEnabled = !!this.options.annotateForClosureCompiler;
this.entryPoint = this.entryPoint =
adapter.entryPoint !== null ? getSourceFileOrNull(tsProgram, adapter.entryPoint) : null; adapter.entryPoint !== null ? getSourceFileOrNull(inputProgram, adapter.entryPoint) : null;
const moduleResolutionCache = ts.createModuleResolutionCache( const moduleResolutionCache = ts.createModuleResolutionCache(
this.adapter.getCurrentDirectory(), this.adapter.getCurrentDirectory(),
@ -343,19 +340,19 @@ export class NgCompiler {
// way into all kinds of places inside TS internal objects. // way into all kinds of places inside TS internal objects.
this.adapter.getCanonicalFileName.bind(this.adapter)); this.adapter.getCanonicalFileName.bind(this.adapter));
this.moduleResolver = this.moduleResolver =
new ModuleResolver(tsProgram, this.options, this.adapter, moduleResolutionCache); new ModuleResolver(inputProgram, this.options, this.adapter, moduleResolutionCache);
this.resourceManager = new AdapterResourceLoader(adapter, this.options); this.resourceManager = new AdapterResourceLoader(adapter, this.options);
this.cycleAnalyzer = this.cycleAnalyzer = new CycleAnalyzer(
new CycleAnalyzer(new ImportGraph(tsProgram.getTypeChecker(), this.delegatingPerfRecorder)); new ImportGraph(inputProgram.getTypeChecker(), this.delegatingPerfRecorder));
this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, tsProgram); this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, inputProgram);
this.ignoreForDiagnostics = this.ignoreForDiagnostics =
new Set(tsProgram.getSourceFiles().filter(sf => this.adapter.isShim(sf))); new Set(inputProgram.getSourceFiles().filter(sf => this.adapter.isShim(sf)));
this.ignoreForEmit = this.adapter.ignoreForEmit; this.ignoreForEmit = this.adapter.ignoreForEmit;
let dtsFileCount = 0; let dtsFileCount = 0;
let nonDtsFileCount = 0; let nonDtsFileCount = 0;
for (const sf of tsProgram.getSourceFiles()) { for (const sf of inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) { if (sf.isDeclarationFile) {
dtsFileCount++; dtsFileCount++;
} else { } else {
@ -462,16 +459,22 @@ export class NgCompiler {
} }
/** /**
* Get the `ts.Program` to use as a starting point when spawning a subsequent incremental * Get the current `ts.Program` known to this `NgCompiler`.
* compilation.
* *
* The `NgCompiler` spawns an internal incremental TypeScript compilation (inheriting the * Compilation begins with an input `ts.Program`, and during template type-checking operations new
* consumer's `ts.Program` into a new one for the purposes of template type-checking). After this * `ts.Program`s may be produced using the `ProgramDriver`. The most recent such `ts.Program` to
* operation, the consumer's `ts.Program` is no longer usable for starting a new incremental * be produced is available here.
* compilation. `getNextProgram` retrieves the `ts.Program` which can be used instead. *
* This `ts.Program` serves two key purposes:
*
* * As an incremental starting point for creating the next `ts.Program` based on files that the
* user has changed (for clients using the TS compiler program APIs).
*
* * As the "before" point for an incremental compilation invocation, to determine what's changed
* between the old and new programs (for all compilations).
*/ */
getNextProgram(): ts.Program { getCurrentProgram(): ts.Program {
return this.nextProgram; return this.currentProgram;
} }
getTemplateTypeChecker(): TemplateTypeChecker { getTemplateTypeChecker(): TemplateTypeChecker {
@ -533,7 +536,7 @@ export class NgCompiler {
this.compilation = this.makeCompilation(); this.compilation = this.makeCompilation();
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
for (const sf of this.tsProgram.getSourceFiles()) { for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) { if (sf.isDeclarationFile) {
continue; continue;
} }
@ -579,7 +582,7 @@ export class NgCompiler {
// //
// In all cases above, the `containingFile` argument is ignored, so we can just take the first // In all cases above, the `containingFile` argument is ignored, so we can just take the first
// of the root files. // of the root files.
const containingFile = this.tsProgram.getRootFileNames()[0]; const containingFile = this.inputProgram.getRootFileNames()[0];
const [entryPath, moduleName] = entryRoute.split('#'); const [entryPath, moduleName] = entryRoute.split('#');
const resolvedModule = const resolvedModule =
resolveModuleName(entryPath, containingFile, this.options, this.adapter, null); resolveModuleName(entryPath, containingFile, this.options, this.adapter, null);
@ -602,7 +605,7 @@ export class NgCompiler {
} { } {
const compilation = this.ensureAnalyzed(); const compilation = this.ensureAnalyzed();
const coreImportsFrom = compilation.isCore ? getR3SymbolsFile(this.tsProgram) : null; const coreImportsFrom = compilation.isCore ? getR3SymbolsFile(this.inputProgram) : null;
let importRewriter: ImportRewriter; let importRewriter: ImportRewriter;
if (coreImportsFrom !== null) { if (coreImportsFrom !== null) {
importRewriter = new R3SymbolsImportRewriter(coreImportsFrom.fileName); importRewriter = new R3SymbolsImportRewriter(coreImportsFrom.fileName);
@ -661,7 +664,7 @@ export class NgCompiler {
private analyzeSync(): void { private analyzeSync(): void {
this.perfRecorder.inPhase(PerfPhase.Analysis, () => { this.perfRecorder.inPhase(PerfPhase.Analysis, () => {
this.compilation = this.makeCompilation(); this.compilation = this.makeCompilation();
for (const sf of this.tsProgram.getSourceFiles()) { for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) { if (sf.isDeclarationFile) {
continue; continue;
} }
@ -703,7 +706,7 @@ export class NgCompiler {
// is not disabled when `strictTemplates` is enabled. // is not disabled when `strictTemplates` is enabled.
const strictTemplates = !!this.options.strictTemplates; const strictTemplates = !!this.options.strictTemplates;
const useInlineTypeConstructors = this.typeCheckingProgramStrategy.supportsInlineOperations; const useInlineTypeConstructors = this.programDriver.supportsInlineOperations;
// First select a type-checking configuration, based on whether full template type-checking is // First select a type-checking configuration, based on whether full template type-checking is
// requested. // requested.
@ -816,7 +819,7 @@ export class NgCompiler {
// Get the diagnostics. // Get the diagnostics.
const diagnostics: ts.Diagnostic[] = []; const diagnostics: ts.Diagnostic[] = [];
for (const sf of this.tsProgram.getSourceFiles()) { for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile || this.adapter.isShim(sf)) { if (sf.isDeclarationFile || this.adapter.isShim(sf)) {
continue; continue;
} }
@ -825,9 +828,9 @@ export class NgCompiler {
...compilation.templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram)); ...compilation.templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram));
} }
const program = this.typeCheckingProgramStrategy.getProgram(); const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, program); this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, program);
this.nextProgram = program; this.currentProgram = program;
return diagnostics; return diagnostics;
} }
@ -842,9 +845,9 @@ export class NgCompiler {
diagnostics.push(...compilation.templateTypeChecker.getDiagnosticsForFile(sf, optimizeFor)); diagnostics.push(...compilation.templateTypeChecker.getDiagnosticsForFile(sf, optimizeFor));
} }
const program = this.typeCheckingProgramStrategy.getProgram(); const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, program); this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, program);
this.nextProgram = program; this.currentProgram = program;
return diagnostics; return diagnostics;
} }
@ -855,7 +858,7 @@ export class NgCompiler {
this.nonTemplateDiagnostics = [...compilation.traitCompiler.diagnostics]; this.nonTemplateDiagnostics = [...compilation.traitCompiler.diagnostics];
if (this.entryPoint !== null && compilation.exportReferenceGraph !== null) { if (this.entryPoint !== null && compilation.exportReferenceGraph !== null) {
this.nonTemplateDiagnostics.push(...checkForPrivateExports( this.nonTemplateDiagnostics.push(...checkForPrivateExports(
this.entryPoint, this.tsProgram.getTypeChecker(), compilation.exportReferenceGraph)); this.entryPoint, this.inputProgram.getTypeChecker(), compilation.exportReferenceGraph));
} }
} }
return this.nonTemplateDiagnostics; return this.nonTemplateDiagnostics;
@ -872,7 +875,7 @@ export class NgCompiler {
} }
private makeCompilation(): LazyCompilationState { private makeCompilation(): LazyCompilationState {
const checker = this.tsProgram.getTypeChecker(); const checker = this.inputProgram.getTypeChecker();
const reflector = new TypeScriptReflectionHost(checker); const reflector = new TypeScriptReflectionHost(checker);
@ -904,7 +907,7 @@ export class NgCompiler {
// First, try to use local identifiers if available. // First, try to use local identifiers if available.
new LocalIdentifierStrategy(), new LocalIdentifierStrategy(),
// Next, attempt to use an absolute import. // Next, attempt to use an absolute import.
new AbsoluteModuleStrategy(this.tsProgram, checker, this.moduleResolver, reflector), new AbsoluteModuleStrategy(this.inputProgram, checker, this.moduleResolver, reflector),
// Finally, check if the reference is being written into a file within the project's .ts // Finally, check if the reference is being written into a file within the project's .ts
// sources, and use a relative import if so. If this fails, ReferenceEmitter will throw // sources, and use a relative import if so. If this fails, ReferenceEmitter will throw
// an error. // an error.
@ -966,7 +969,7 @@ export class NgCompiler {
const mwpScanner = new ModuleWithProvidersScanner(reflector, evaluator, refEmitter); const mwpScanner = new ModuleWithProvidersScanner(reflector, evaluator, refEmitter);
const isCore = isAngularCorePackage(this.tsProgram); const isCore = isAngularCorePackage(this.inputProgram);
const defaultImportTracker = new DefaultImportTracker(); const defaultImportTracker = new DefaultImportTracker();
const resourceRegistry = new ResourceRegistry(); const resourceRegistry = new ResourceRegistry();
@ -1024,10 +1027,18 @@ export class NgCompiler {
this.options.compileNonExportedClasses !== false, compilationMode, dtsTransforms, this.options.compileNonExportedClasses !== false, compilationMode, dtsTransforms,
semanticDepGraphUpdater); semanticDepGraphUpdater);
// Template type-checking may use the `ProgramDriver` to produce new `ts.Program`(s). If this
// happens, they need to be tracked by the `NgCompiler`.
const notifyingDriver =
new NotifyingProgramDriverWrapper(this.programDriver, (program: ts.Program) => {
this.incrementalStrategy.setIncrementalDriver(this.incrementalDriver, program);
this.currentProgram = program;
});
const templateTypeChecker = new TemplateTypeCheckerImpl( const templateTypeChecker = new TemplateTypeCheckerImpl(
this.tsProgram, this.typeCheckingProgramStrategy, traitCompiler, this.inputProgram, notifyingDriver, traitCompiler, this.getTypeCheckingConfig(), refEmitter,
this.getTypeCheckingConfig(), refEmitter, reflector, this.adapter, this.incrementalDriver, reflector, this.adapter, this.incrementalDriver, scopeRegistry, typeCheckScopeRegistry,
scopeRegistry, typeCheckScopeRegistry, this.delegatingPerfRecorder); this.delegatingPerfRecorder);
return { return {
isCore, isCore,
@ -1141,3 +1152,21 @@ class ReferenceGraphAdapter implements ReferencesRegistry {
} }
} }
} }
class NotifyingProgramDriverWrapper implements ProgramDriver {
constructor(
private delegate: ProgramDriver, private notifyNewProgram: (program: ts.Program) => void) {}
get supportsInlineOperations() {
return this.delegate.supportsInlineOperations;
}
getProgram(): ts.Program {
return this.delegate.getProgram();
}
updateFiles(contents: Map<AbsoluteFsPath, string>, updateMode: UpdateMode): void {
this.delegate.updateFiles(contents, updateMode);
this.notifyNewProgram(this.delegate.getProgram());
}
}

View File

@ -15,6 +15,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/api",

View File

@ -11,9 +11,9 @@ import * as ts from 'typescript';
import {absoluteFrom as _, FileSystem, getFileSystem, getSourceFileOrError, NgtscCompilerHost, setFileSystem} from '../../file_system'; import {absoluteFrom as _, FileSystem, getFileSystem, getSourceFileOrError, NgtscCompilerHost, setFileSystem} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing'; import {runInEachFileSystem} from '../../file_system/testing';
import {IncrementalBuildStrategy, NoopIncrementalBuildStrategy} from '../../incremental'; import {IncrementalBuildStrategy, NoopIncrementalBuildStrategy} from '../../incremental';
import {ProgramDriver, TsCreateProgramDriver} from '../../program_driver';
import {ClassDeclaration, isNamedClassDeclaration} from '../../reflection'; import {ClassDeclaration, isNamedClassDeclaration} from '../../reflection';
import {ReusedProgramStrategy} from '../../typecheck'; import {OptimizeFor} from '../../typecheck/api';
import {OptimizeFor, TypeCheckingProgramStrategy} from '../../typecheck/api';
import {NgCompilerOptions} from '../api'; import {NgCompilerOptions} from '../api';
@ -22,7 +22,7 @@ import {NgCompilerHost} from '../src/host';
function makeFreshCompiler( function makeFreshCompiler(
host: NgCompilerHost, options: NgCompilerOptions, program: ts.Program, host: NgCompilerHost, options: NgCompilerOptions, program: ts.Program,
programStrategy: TypeCheckingProgramStrategy, incrementalStrategy: IncrementalBuildStrategy, programStrategy: ProgramDriver, incrementalStrategy: IncrementalBuildStrategy,
enableTemplateTypeChecker: boolean, usePoisonedData: boolean): NgCompiler { enableTemplateTypeChecker: boolean, usePoisonedData: boolean): NgCompiler {
const ticket = freshCompilationTicket( const ticket = freshCompilationTicket(
program, options, incrementalStrategy, programStrategy, /* perfRecorder */ null, program, options, incrementalStrategy, programStrategy, /* perfRecorder */ null,
@ -61,7 +61,7 @@ runInEachFileSystem(() => {
const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null); const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles}); const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const compiler = makeFreshCompiler( const compiler = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);
@ -113,7 +113,7 @@ runInEachFileSystem(() => {
const CmpC = getClass(getSourceFileOrError(program, cmpCFile), 'CmpC'); const CmpC = getClass(getSourceFileOrError(program, cmpCFile), 'CmpC');
const compiler = makeFreshCompiler( const compiler = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);
const components = compiler.getComponentsWithTemplateFile(templateFile); const components = compiler.getComponentsWithTemplateFile(templateFile);
@ -165,7 +165,7 @@ runInEachFileSystem(() => {
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA'); const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const CmpC = getClass(getSourceFileOrError(program, cmpCFile), 'CmpC'); const CmpC = getClass(getSourceFileOrError(program, cmpCFile), 'CmpC');
const compiler = makeFreshCompiler( const compiler = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);
const components = compiler.getComponentsWithStyleFile(styleFile); const components = compiler.getComponentsWithStyleFile(styleFile);
@ -199,7 +199,7 @@ runInEachFileSystem(() => {
const program = ts.createProgram({host, options, rootNames: host.inputFiles}); const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA'); const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const compiler = makeFreshCompiler( const compiler = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);
const resources = compiler.getComponentResources(CmpA); const resources = compiler.getComponentResources(CmpA);
@ -235,7 +235,7 @@ runInEachFileSystem(() => {
const program = ts.createProgram({host, options, rootNames: host.inputFiles}); const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA'); const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const compiler = makeFreshCompiler( const compiler = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);
const resources = compiler.getComponentResources(CmpA); const resources = compiler.getComponentResources(CmpA);
@ -267,7 +267,7 @@ runInEachFileSystem(() => {
const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null); const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles}); const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const compiler = makeFreshCompiler( const compiler = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);
@ -301,7 +301,7 @@ runInEachFileSystem(() => {
const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null); const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles}); const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const compilerA = makeFreshCompiler( const compilerA = makeFreshCompiler(
host, options, program, new ReusedProgramStrategy(program, host, options, []), host, options, program, new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false, new NoopIncrementalBuildStrategy(), /** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false); /* usePoisonedData */ false);

View File

@ -18,9 +18,9 @@ import {absoluteFrom, AbsoluteFsPath, getFileSystem} from './file_system';
import {TrackedIncrementalBuildStrategy} from './incremental'; import {TrackedIncrementalBuildStrategy} from './incremental';
import {IndexedComponent} from './indexer'; import {IndexedComponent} from './indexer';
import {ActivePerfRecorder, PerfCheckpoint as PerfCheckpoint, PerfEvent, PerfPhase} from './perf'; import {ActivePerfRecorder, PerfCheckpoint as PerfCheckpoint, PerfEvent, PerfPhase} from './perf';
import {TsCreateProgramDriver} from './program_driver';
import {DeclarationNode} from './reflection'; import {DeclarationNode} from './reflection';
import {retagAllTsFiles, untagAllTsFiles} from './shims'; import {retagAllTsFiles, untagAllTsFiles} from './shims';
import {ReusedProgramStrategy} from './typecheck';
import {OptimizeFor} from './typecheck/api'; import {OptimizeFor} from './typecheck/api';
@ -95,7 +95,7 @@ export class NgtscProgram implements api.Program {
// the program. // the program.
untagAllTsFiles(this.tsProgram); untagAllTsFiles(this.tsProgram);
const reusedProgramStrategy = new ReusedProgramStrategy( const programDriver = new TsCreateProgramDriver(
this.tsProgram, this.host, this.options, this.host.shimExtensionPrefixes); this.tsProgram, this.host, this.options, this.host.shimExtensionPrefixes);
this.incrementalStrategy = oldProgram !== undefined ? this.incrementalStrategy = oldProgram !== undefined ?
@ -114,14 +114,14 @@ export class NgtscProgram implements api.Program {
let ticket: CompilationTicket; let ticket: CompilationTicket;
if (oldProgram === undefined) { if (oldProgram === undefined) {
ticket = freshCompilationTicket( ticket = freshCompilationTicket(
this.tsProgram, options, this.incrementalStrategy, reusedProgramStrategy, perfRecorder, this.tsProgram, options, this.incrementalStrategy, programDriver, perfRecorder,
/* enableTemplateTypeChecker */ false, /* usePoisonedData */ false); /* enableTemplateTypeChecker */ false, /* usePoisonedData */ false);
} else { } else {
ticket = incrementalFromCompilerTicket( ticket = incrementalFromCompilerTicket(
oldProgram.compiler, oldProgram.compiler,
this.tsProgram, this.tsProgram,
this.incrementalStrategy, this.incrementalStrategy,
reusedProgramStrategy, programDriver,
modifiedResourceFiles, modifiedResourceFiles,
perfRecorder, perfRecorder,
); );
@ -223,7 +223,7 @@ export class NgtscProgram implements api.Program {
const diagnostics = sf === undefined ? const diagnostics = sf === undefined ?
this.compiler.getDiagnostics() : this.compiler.getDiagnostics() :
this.compiler.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram); this.compiler.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram);
this.reuseTsProgram = this.compiler.getNextProgram(); this.reuseTsProgram = this.compiler.getCurrentProgram();
return diagnostics; return diagnostics;
} }

View File

@ -0,0 +1,17 @@
load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "program_driver",
srcs = ["index.ts"] + glob([
"src/*.ts",
]),
module_name = "@angular/compiler-cli/src/ngtsc/program_driver",
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/util",
"@npm//typescript",
],
)

View File

@ -0,0 +1,18 @@
# The Program Driver interface
`ProgramDriver` is a small but important interface which allows the template type-checking machinery to request changes to the current `ts.Program`, and to receive a new `ts.Program` with those changes applied. This is used to add template type-checking code to the current `ts.Program`, eventually allowing for diagnostics to be produced within that code. This operation is abstracted behind this interface because different clients create `ts.Program`s differently. The Language Service, for example, creates `ts.Program`s from the current editor state on request, while the TS compiler API creates them explicitly.
When running using the TS APIs, it's important that each new `ts.Program` be created incrementally from the previous `ts.Program`. Under a normal compilation, this means that programs alternate between template type checking programs and user programs:
* `ts.Program#1` is created from user input (the user's source files).
* `ts.Program#2` is created incrementally on top of #1 for template type-checking, and adds private TCB code.
* `ts.Program#3` is created incrementally on top of #2 when the user makes changes to files on disk (incremental build).
* `ts.Program#4` is created incrementally on top of #3 to adjust template type-checking code according to the user's changes.
The `TsCreateProgramDriver` performs this operation for template type-checking `ts.Program`s built by the command-line compiler or by the CLI. The latest template type-checking program is then exposed via the `NgCompiler`'s `getCurrentProgram()` operation, and new user programs are expected to be created incrementally on top of the previous template type-checking program.
## Programs and the compiler as a service
Not all clients of the compiler follow the incremental tick-tock scenario above. When the compiler is used as a service, new `ts.Program`s may be generated in response to various queries, either directly to `NgCompiler` or via the `TemplateTypeChecker`. Internally, the compiler will use the current `ProgramDriver` to create these additional `ts.Program`s as needed.
Incremental builds (new user code changes) may also require changing the `ts.Program`, using the compiler's incremental ticket process. If the `TsCreateProgramDriver` is used, the client is responsible for ensuring that any new incremental `ts.Program`s are created on top of the current program from the previous compilation, which can be obtained via `NgCompiler`'s `getCurrentProgram()`.

View File

@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC 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
*/
export * from './src/api';
export {TsCreateProgramDriver} from './src/ts_create_program_driver';

View File

@ -0,0 +1,44 @@
/**
* @license
* Copyright Google LLC 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 * as ts from 'typescript';
import {AbsoluteFsPath} from '../../file_system';
export interface ProgramDriver {
/**
* Whether this strategy supports modifying user files (inline modifications) in addition to
* modifying type-checking shims.
*/
readonly supportsInlineOperations: boolean;
/**
* Retrieve the latest version of the program, containing all the updates made thus far.
*/
getProgram(): ts.Program;
/**
* Incorporate a set of changes to either augment or completely replace the type-checking code
* included in the type-checking program.
*/
updateFiles(contents: Map<AbsoluteFsPath, string>, updateMode: UpdateMode): void;
}
export enum UpdateMode {
/**
* A complete update creates a completely new overlay of type-checking code on top of the user's
* original program, which doesn't include type-checking code from previous calls to
* `updateFiles`.
*/
Complete,
/**
* An incremental update changes the contents of some files in the type-checking program without
* reverting any prior changes.
*/
Incremental,
}

View File

@ -8,9 +8,20 @@
import * as ts from 'typescript'; import * as ts from 'typescript';
import {copyFileShimData, ShimReferenceTagger} from '../../shims'; /**
* @license
* Copyright Google LLC 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 {AbsoluteFsPath} from '../../file_system';
import {copyFileShimData, retagAllTsFiles, ShimReferenceTagger, untagAllTsFiles} from '../../shims';
import {RequiredDelegations} from '../../util/src/typescript'; import {RequiredDelegations} from '../../util/src/typescript';
import {ProgramDriver, UpdateMode} from './api';
/** /**
* Delegates all methods of `ts.CompilerHost` to a delegate, with the exception of * Delegates all methods of `ts.CompilerHost` to a delegate, with the exception of
* `getSourceFile`, `fileExists` and `writeFile` which are implemented in `TypeCheckProgramHost`. * `getSourceFile`, `fileExists` and `writeFile` which are implemented in `TypeCheckProgramHost`.
@ -51,10 +62,9 @@ export class DelegatingCompilerHost implements
} }
/** /**
* A `ts.CompilerHost` which augments source files with type checking code from a * A `ts.CompilerHost` which augments source files.
* `TypeCheckContext`.
*/ */
export class TypeCheckProgramHost extends DelegatingCompilerHost { class UpdatedProgramHost extends DelegatingCompilerHost {
/** /**
* Map of source file names to `ts.SourceFile` instances. * Map of source file names to `ts.SourceFile` instances.
*/ */
@ -63,12 +73,12 @@ export class TypeCheckProgramHost extends DelegatingCompilerHost {
/** /**
* The `ShimReferenceTagger` responsible for tagging `ts.SourceFile`s loaded via this host. * The `ShimReferenceTagger` responsible for tagging `ts.SourceFile`s loaded via this host.
* *
* The `TypeCheckProgramHost` is used in the creation of a new `ts.Program`. Even though this new * The `UpdatedProgramHost` is used in the creation of a new `ts.Program`. Even though this new
* program is based on a prior one, TypeScript will still start from the root files and enumerate * program is based on a prior one, TypeScript will still start from the root files and enumerate
* all source files to include in the new program. This means that just like during the original * all source files to include in the new program. This means that just like during the original
* program's creation, these source files must be tagged with references to per-file shims in * program's creation, these source files must be tagged with references to per-file shims in
* order for those shims to be loaded, and then cleaned up afterwards. Thus the * order for those shims to be loaded, and then cleaned up afterwards. Thus the
* `TypeCheckProgramHost` has its own `ShimReferenceTagger` to perform this function. * `UpdatedProgramHost` has its own `ShimReferenceTagger` to perform this function.
*/ */
private shimTagger = new ShimReferenceTagger(this.shimExtensionPrefixes); private shimTagger = new ShimReferenceTagger(this.shimExtensionPrefixes);
@ -127,3 +137,72 @@ export class TypeCheckProgramHost extends DelegatingCompilerHost {
return this.sfMap.has(fileName) || this.delegate.fileExists(fileName); return this.sfMap.has(fileName) || this.delegate.fileExists(fileName);
} }
} }
/**
* Updates a `ts.Program` instance with a new one that incorporates specific changes, using the
* TypeScript compiler APIs for incremental program creation.
*/
export class TsCreateProgramDriver implements ProgramDriver {
/**
* A map of source file paths to replacement `ts.SourceFile`s for those paths.
*
* Effectively, this tracks the delta between the user's program (represented by the
* `originalHost`) and the template type-checking program being managed.
*/
private sfMap = new Map<string, ts.SourceFile>();
private program: ts.Program = this.originalProgram;
constructor(
private originalProgram: ts.Program, private originalHost: ts.CompilerHost,
private options: ts.CompilerOptions, private shimExtensionPrefixes: string[]) {}
readonly supportsInlineOperations = true;
getProgram(): ts.Program {
return this.program;
}
updateFiles(contents: Map<AbsoluteFsPath, string>, updateMode: UpdateMode): void {
if (contents.size === 0) {
// No changes have been requested. Is it safe to skip updating entirely?
// If UpdateMode is Incremental, then yes. If UpdateMode is Complete, then it's safe to skip
// only if there are no active changes already (that would be cleared by the update).
if (updateMode !== UpdateMode.Complete || this.sfMap.size === 0) {
// No changes would be made to the `ts.Program` anyway, so it's safe to do nothing here.
return;
}
}
if (updateMode === UpdateMode.Complete) {
this.sfMap.clear();
}
for (const [filePath, text] of contents.entries()) {
this.sfMap.set(filePath, ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true));
}
const host = new UpdatedProgramHost(
this.sfMap, this.originalProgram, this.originalHost, this.shimExtensionPrefixes);
const oldProgram = this.program;
// Retag the old program's `ts.SourceFile`s with shim tags, to allow TypeScript to reuse the
// most data.
retagAllTsFiles(oldProgram);
this.program = ts.createProgram({
host,
rootNames: this.program.getRootFileNames(),
options: this.options,
oldProgram,
});
host.postProgramCreationCleanup();
// And untag them afterwards. We explicitly untag both programs here, because the oldProgram
// may still be used for emit and needs to not contain tags.
untagAllTsFiles(this.program);
untagAllTsFiles(oldProgram);
}
}

View File

@ -12,10 +12,10 @@ import {CompilationTicket, freshCompilationTicket, incrementalFromDriverTicket,
import {NgCompilerOptions, UnifiedModulesHost} from './core/api'; import {NgCompilerOptions, UnifiedModulesHost} from './core/api';
import {NodeJSFileSystem, setFileSystem} from './file_system'; import {NodeJSFileSystem, setFileSystem} from './file_system';
import {PatchedProgramIncrementalBuildStrategy} from './incremental'; import {PatchedProgramIncrementalBuildStrategy} from './incremental';
import {ActivePerfRecorder, NOOP_PERF_RECORDER, PerfPhase} from './perf'; import {ActivePerfRecorder, PerfPhase} from './perf';
import {TsCreateProgramDriver} from './program_driver';
import {untagAllTsFiles} from './shims'; import {untagAllTsFiles} from './shims';
import {OptimizeFor} from './typecheck/api'; import {OptimizeFor} from './typecheck/api';
import {ReusedProgramStrategy} from './typecheck/src/augmented_program';
// The following is needed to fix a the chicken-and-egg issue where the sync (into g3) script will // The following is needed to fix a the chicken-and-egg issue where the sync (into g3) script will
// refuse to accept this file unless the following string appears: // refuse to accept this file unless the following string appears:
@ -106,7 +106,7 @@ export class NgTscPlugin implements TscPlugin {
} }
this.host.postProgramCreationCleanup(); this.host.postProgramCreationCleanup();
untagAllTsFiles(program); untagAllTsFiles(program);
const typeCheckStrategy = new ReusedProgramStrategy( const programDriver = new TsCreateProgramDriver(
program, this.host, this.options, this.host.shimExtensionPrefixes); program, this.host, this.options, this.host.shimExtensionPrefixes);
const strategy = new PatchedProgramIncrementalBuildStrategy(); const strategy = new PatchedProgramIncrementalBuildStrategy();
const oldDriver = oldProgram !== undefined ? strategy.getIncrementalDriver(oldProgram) : null; const oldDriver = oldProgram !== undefined ? strategy.getIncrementalDriver(oldProgram) : null;
@ -122,12 +122,12 @@ export class NgTscPlugin implements TscPlugin {
if (oldProgram === undefined || oldDriver === null) { if (oldProgram === undefined || oldDriver === null) {
ticket = freshCompilationTicket( ticket = freshCompilationTicket(
program, this.options, strategy, typeCheckStrategy, perfRecorder, program, this.options, strategy, programDriver, perfRecorder,
/* enableTemplateTypeChecker */ false, /* usePoisonedData */ false); /* enableTemplateTypeChecker */ false, /* usePoisonedData */ false);
} else { } else {
strategy.toNextBuildStrategy().getIncrementalDriver(oldProgram); strategy.toNextBuildStrategy().getIncrementalDriver(oldProgram);
ticket = incrementalFromDriverTicket( ticket = incrementalFromDriverTicket(
oldProgram, oldDriver, program, this.options, strategy, typeCheckStrategy, oldProgram, oldDriver, program, this.options, strategy, programDriver,
modifiedResourceFiles, perfRecorder, false, false); modifiedResourceFiles, perfRecorder, false, false);
} }
this._compiler = NgCompiler.fromTicket(ticket, this.host); this._compiler = NgCompiler.fromTicket(ticket, this.host);
@ -149,7 +149,7 @@ export class NgTscPlugin implements TscPlugin {
} }
getNextProgram(): ts.Program { getNextProgram(): ts.Program {
return this.compiler.getNextProgram(); return this.compiler.getCurrentProgram();
} }
createTransformers(): ts.CustomTransformers { createTransformers(): ts.CustomTransformers {

View File

@ -16,6 +16,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/incremental:api",
"//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/shims",

View File

@ -352,63 +352,3 @@ export interface FullTemplateMapping {
templateSourceMapping: TemplateSourceMapping; templateSourceMapping: TemplateSourceMapping;
span: ParseSourceSpan; span: ParseSourceSpan;
} }
/**
* Abstracts the operation of determining which shim file will host a particular component's
* template type-checking code.
*
* Different consumers of the type checking infrastructure may choose different approaches to
* optimize for their specific use case (for example, the command-line compiler optimizes for
* efficient `ts.Program` reuse in watch mode).
*/
export interface ComponentToShimMappingStrategy {
/**
* Given a component, determine a path to the shim file into which that component's type checking
* code will be generated.
*
* A major constraint is that components in different input files must not share the same shim
* file. The behavior of the template type-checking system is undefined if this is violated.
*/
shimPathForComponent(node: ts.ClassDeclaration): AbsoluteFsPath;
}
/**
* Strategy used to manage a `ts.Program` which contains template type-checking code and update it
* over time.
*
* This abstraction allows both the Angular compiler itself as well as the language service to
* implement efficient template type-checking using common infrastructure.
*/
export interface TypeCheckingProgramStrategy extends ComponentToShimMappingStrategy {
/**
* Whether this strategy supports modifying user files (inline modifications) in addition to
* modifying type-checking shims.
*/
readonly supportsInlineOperations: boolean;
/**
* Retrieve the latest version of the program, containing all the updates made thus far.
*/
getProgram(): ts.Program;
/**
* Incorporate a set of changes to either augment or completely replace the type-checking code
* included in the type-checking program.
*/
updateFiles(contents: Map<AbsoluteFsPath, string>, updateMode: UpdateMode): void;
}
export enum UpdateMode {
/**
* A complete update creates a completely new overlay of type-checking code on top of the user's
* original program, which doesn't include type-checking code from previous calls to
* `updateFiles`.
*/
Complete,
/**
* An incremental update changes the contents of some files in the type-checking program without
* reverting any prior changes.
*/
Incremental,
}

View File

@ -6,9 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
export {ReusedProgramStrategy} from './src/augmented_program';
export {FileTypeCheckingData, TemplateTypeCheckerImpl} from './src/checker'; export {FileTypeCheckingData, TemplateTypeCheckerImpl} from './src/checker';
export {TypeCheckContextImpl} from './src/context'; export {TypeCheckContextImpl} from './src/context';
export {TypeCheckProgramHost} from './src/host';
export {TypeCheckShimGenerator} from './src/shim'; export {TypeCheckShimGenerator} from './src/shim';
export {typeCheckFilePath} from './src/type_check_file'; export {typeCheckFilePath} from './src/type_check_file';

View File

@ -1,88 +0,0 @@
/**
* @license
* Copyright Google LLC 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 * as ts from 'typescript';
import {absoluteFromSourceFile, AbsoluteFsPath} from '../../file_system';
import {retagAllTsFiles, untagAllTsFiles} from '../../shims';
import {TypeCheckingProgramStrategy, UpdateMode} from '../api';
import {TypeCheckProgramHost} from './host';
import {TypeCheckShimGenerator} from './shim';
/**
* Implements a template type-checking program using `ts.createProgram` and TypeScript's program
* reuse functionality.
*/
export class ReusedProgramStrategy implements TypeCheckingProgramStrategy {
/**
* A map of source file paths to replacement `ts.SourceFile`s for those paths.
*
* Effectively, this tracks the delta between the user's program (represented by the
* `originalHost`) and the template type-checking program being managed.
*/
private sfMap = new Map<string, ts.SourceFile>();
private program: ts.Program = this.originalProgram;
constructor(
private originalProgram: ts.Program, private originalHost: ts.CompilerHost,
private options: ts.CompilerOptions, private shimExtensionPrefixes: string[]) {}
readonly supportsInlineOperations = true;
getProgram(): ts.Program {
return this.program;
}
updateFiles(contents: Map<AbsoluteFsPath, string>, updateMode: UpdateMode): void {
if (contents.size === 0) {
// No changes have been requested. Is it safe to skip updating entirely?
// If UpdateMode is Incremental, then yes. If UpdateMode is Complete, then it's safe to skip
// only if there are no active changes already (that would be cleared by the update).
if (updateMode !== UpdateMode.Complete || this.sfMap.size === 0) {
// No changes would be made to the `ts.Program` anyway, so it's safe to do nothing here.
return;
}
}
if (updateMode === UpdateMode.Complete) {
this.sfMap.clear();
}
for (const [filePath, text] of contents.entries()) {
this.sfMap.set(filePath, ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true));
}
const host = new TypeCheckProgramHost(
this.sfMap, this.originalProgram, this.originalHost, this.shimExtensionPrefixes);
const oldProgram = this.program;
// Retag the old program's `ts.SourceFile`s with shim tags, to allow TypeScript to reuse the
// most data.
retagAllTsFiles(oldProgram);
this.program = ts.createProgram({
host,
rootNames: this.program.getRootFileNames(),
options: this.options,
oldProgram,
});
host.postProgramCreationCleanup();
// And untag them afterwards. We explicitly untag both programs here, because the oldProgram
// may still be used for emit and needs to not contain tags.
untagAllTsFiles(this.program);
untagAllTsFiles(oldProgram);
}
shimPathForComponent(node: ts.ClassDeclaration): AbsoluteFsPath {
return TypeCheckShimGenerator.shimFor(absoluteFromSourceFile(node.getSourceFile()));
}
}

View File

@ -13,16 +13,18 @@ import {absoluteFrom, absoluteFromSourceFile, AbsoluteFsPath, getSourceFileOrErr
import {Reference, ReferenceEmitter} from '../../imports'; import {Reference, ReferenceEmitter} from '../../imports';
import {IncrementalBuild} from '../../incremental/api'; import {IncrementalBuild} from '../../incremental/api';
import {PerfCheckpoint, PerfEvent, PerfPhase, PerfRecorder} from '../../perf'; import {PerfCheckpoint, PerfEvent, PerfPhase, PerfRecorder} from '../../perf';
import {ProgramDriver, UpdateMode} from '../../program_driver';
import {ClassDeclaration, isNamedClassDeclaration, ReflectionHost} from '../../reflection'; import {ClassDeclaration, isNamedClassDeclaration, ReflectionHost} from '../../reflection';
import {ComponentScopeReader, TypeCheckScopeRegistry} from '../../scope'; import {ComponentScopeReader, TypeCheckScopeRegistry} from '../../scope';
import {isShim} from '../../shims'; import {isShim} from '../../shims';
import {getSourceFileOrNull} from '../../util/src/typescript'; import {getSourceFileOrNull} from '../../util/src/typescript';
import {DirectiveInScope, ElementSymbol, FullTemplateMapping, GlobalCompletion, OptimizeFor, PipeInScope, ProgramTypeCheckAdapter, ShimLocation, Symbol, TemplateId, TemplateSymbol, TemplateTypeChecker, TypeCheckableDirectiveMeta, TypeCheckingConfig, TypeCheckingProgramStrategy, UpdateMode} from '../api'; import {DirectiveInScope, ElementSymbol, FullTemplateMapping, GlobalCompletion, OptimizeFor, PipeInScope, ProgramTypeCheckAdapter, ShimLocation, Symbol, TemplateId, TemplateSymbol, TemplateTypeChecker, TypeCheckableDirectiveMeta, TypeCheckingConfig} from '../api';
import {TemplateDiagnostic} from '../diagnostics'; import {TemplateDiagnostic} from '../diagnostics';
import {CompletionEngine} from './completion'; import {CompletionEngine} from './completion';
import {InliningMode, ShimTypeCheckingData, TemplateData, TypeCheckContextImpl, TypeCheckingHost} from './context'; import {InliningMode, ShimTypeCheckingData, TemplateData, TypeCheckContextImpl, TypeCheckingHost} from './context';
import {shouldReportDiagnostic, translateDiagnostic} from './diagnostics'; import {shouldReportDiagnostic, translateDiagnostic} from './diagnostics';
import {TypeCheckShimGenerator} from './shim';
import {TemplateSourceManager} from './source'; import {TemplateSourceManager} from './source';
import {findTypeCheckBlock, getTemplateMapping, TemplateSourceResolver} from './tcb_util'; import {findTypeCheckBlock, getTemplateMapping, TemplateSourceResolver} from './tcb_util';
import {SymbolBuilder} from './template_symbol_builder'; import {SymbolBuilder} from './template_symbol_builder';
@ -76,8 +78,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
private isComplete = false; private isComplete = false;
constructor( constructor(
private originalProgram: ts.Program, private originalProgram: ts.Program, readonly programDriver: ProgramDriver,
readonly typeCheckingStrategy: TypeCheckingProgramStrategy,
private typeCheckAdapter: ProgramTypeCheckAdapter, private config: TypeCheckingConfig, private typeCheckAdapter: ProgramTypeCheckAdapter, private config: TypeCheckingConfig,
private refEmitter: ReferenceEmitter, private reflector: ReflectionHost, private refEmitter: ReferenceEmitter, private reflector: ReflectionHost,
private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>,
@ -100,7 +101,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
const sf = component.getSourceFile(); const sf = component.getSourceFile();
const sfPath = absoluteFromSourceFile(sf); const sfPath = absoluteFromSourceFile(sf);
const shimPath = this.typeCheckingStrategy.shimPathForComponent(component); const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileRecord = this.getFileData(sfPath); const fileRecord = this.getFileData(sfPath);
@ -112,7 +113,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
const shimRecord = fileRecord.shimData.get(shimPath)!; const shimRecord = fileRecord.shimData.get(shimPath)!;
const id = fileRecord.sourceManager.getTemplateId(component); const id = fileRecord.sourceManager.getTemplateId(component);
const program = this.typeCheckingStrategy.getProgram(); const program = this.programDriver.getProgram();
const shimSf = getSourceFileOrNull(program, shimPath); const shimSf = getSourceFileOrNull(program, shimPath);
if (shimSf === null || !fileRecord.shimData.has(shimPath)) { if (shimSf === null || !fileRecord.shimData.has(shimPath)) {
@ -157,7 +158,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
} }
const {fileRecord} = records; const {fileRecord} = records;
const shimSf = this.typeCheckingStrategy.getProgram().getSourceFile(absoluteFrom(shimPath)); const shimSf = this.programDriver.getProgram().getSourceFile(absoluteFrom(shimPath));
if (shimSf === undefined) { if (shimSf === undefined) {
return null; return null;
} }
@ -187,7 +188,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
const sfPath = absoluteFromSourceFile(sf); const sfPath = absoluteFromSourceFile(sf);
const fileRecord = this.state.get(sfPath)!; const fileRecord = this.state.get(sfPath)!;
const typeCheckProgram = this.typeCheckingStrategy.getProgram(); const typeCheckProgram = this.programDriver.getProgram();
const diagnostics: (ts.Diagnostic|null)[] = []; const diagnostics: (ts.Diagnostic|null)[] = [];
if (fileRecord.hasInlines) { if (fileRecord.hasInlines) {
@ -217,7 +218,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
return this.perf.inPhase(PerfPhase.TtcDiagnostics, () => { return this.perf.inPhase(PerfPhase.TtcDiagnostics, () => {
const sf = component.getSourceFile(); const sf = component.getSourceFile();
const sfPath = absoluteFromSourceFile(sf); const sfPath = absoluteFromSourceFile(sf);
const shimPath = this.typeCheckingStrategy.shimPathForComponent(component); const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileRecord = this.getFileData(sfPath); const fileRecord = this.getFileData(sfPath);
@ -228,7 +229,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
const templateId = fileRecord.sourceManager.getTemplateId(component); const templateId = fileRecord.sourceManager.getTemplateId(component);
const shimRecord = fileRecord.shimData.get(shimPath)!; const shimRecord = fileRecord.shimData.get(shimPath)!;
const typeCheckProgram = this.typeCheckingStrategy.getProgram(); const typeCheckProgram = this.programDriver.getProgram();
const diagnostics: (TemplateDiagnostic|null)[] = []; const diagnostics: (TemplateDiagnostic|null)[] = [];
if (shimRecord.hasInlines) { if (shimRecord.hasInlines) {
@ -285,7 +286,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
const sf = clazz.getSourceFile(); const sf = clazz.getSourceFile();
const sfPath = absoluteFromSourceFile(sf); const sfPath = absoluteFromSourceFile(sf);
const shimPath = this.typeCheckingStrategy.shimPathForComponent(clazz); const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileData = this.getFileData(sfPath); const fileData = this.getFileData(sfPath);
const templateId = fileData.sourceManager.getTemplateId(clazz); const templateId = fileData.sourceManager.getTemplateId(clazz);
@ -374,8 +375,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
return; return;
} }
const host = const host = new SingleFileTypeCheckingHost(sfPath, fileData, this);
new SingleFileTypeCheckingHost(sfPath, fileData, this.typeCheckingStrategy, this);
const ctx = this.newContext(host); const ctx = this.newContext(host);
this.typeCheckAdapter.typeCheck(sf, ctx); this.typeCheckAdapter.typeCheck(sf, ctx);
@ -389,19 +389,18 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
private ensureShimForComponent(component: ts.ClassDeclaration): void { private ensureShimForComponent(component: ts.ClassDeclaration): void {
const sf = component.getSourceFile(); const sf = component.getSourceFile();
const sfPath = absoluteFromSourceFile(sf); const sfPath = absoluteFromSourceFile(sf);
const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
this.maybeAdoptPriorResultsForFile(sf); this.maybeAdoptPriorResultsForFile(sf);
const fileData = this.getFileData(sfPath); const fileData = this.getFileData(sfPath);
const shimPath = this.typeCheckingStrategy.shimPathForComponent(component);
if (fileData.shimData.has(shimPath)) { if (fileData.shimData.has(shimPath)) {
// All data for this component is available. // All data for this component is available.
return; return;
} }
const host = const host = new SingleShimTypeCheckingHost(sfPath, fileData, this, shimPath);
new SingleShimTypeCheckingHost(sfPath, fileData, this.typeCheckingStrategy, this, shimPath);
const ctx = this.newContext(host); const ctx = this.newContext(host);
this.typeCheckAdapter.typeCheck(sf, ctx); this.typeCheckAdapter.typeCheck(sf, ctx);
@ -409,11 +408,10 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
} }
private newContext(host: TypeCheckingHost): TypeCheckContextImpl { private newContext(host: TypeCheckingHost): TypeCheckContextImpl {
const inlining = this.typeCheckingStrategy.supportsInlineOperations ? InliningMode.InlineOps : const inlining =
InliningMode.Error; this.programDriver.supportsInlineOperations ? InliningMode.InlineOps : InliningMode.Error;
return new TypeCheckContextImpl( return new TypeCheckContextImpl(
this.config, this.compilerHost, this.typeCheckingStrategy, this.refEmitter, this.reflector, this.config, this.compilerHost, this.refEmitter, this.reflector, host, inlining, this.perf);
host, inlining, this.perf);
} }
/** /**
@ -446,7 +444,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
if (updates.size > 0) { if (updates.size > 0) {
this.perf.eventCount(PerfEvent.UpdateTypeCheckProgram); this.perf.eventCount(PerfEvent.UpdateTypeCheckProgram);
} }
this.typeCheckingStrategy.updateFiles(updates, UpdateMode.Incremental); this.programDriver.updateFiles(updates, UpdateMode.Incremental);
this.priorBuild.recordSuccessfulTypeCheck(this.state); this.priorBuild.recordSuccessfulTypeCheck(this.state);
this.perf.memory(PerfCheckpoint.TtcUpdateProgram); this.perf.memory(PerfCheckpoint.TtcUpdateProgram);
}); });
@ -485,7 +483,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
const builder = new SymbolBuilder( const builder = new SymbolBuilder(
shimPath, tcb, data, this.componentScopeReader, shimPath, tcb, data, this.componentScopeReader,
() => this.typeCheckingStrategy.getProgram().getTypeChecker()); () => this.programDriver.getProgram().getTypeChecker());
this.symbolBuilderCache.set(component, builder); this.symbolBuilderCache.set(component, builder);
return builder; return builder;
} }
@ -571,7 +569,7 @@ export class TemplateTypeCheckerImpl implements TemplateTypeChecker {
isPoisoned: scope.compilation.isPoisoned, isPoisoned: scope.compilation.isPoisoned,
}; };
const typeChecker = this.typeCheckingStrategy.getProgram().getTypeChecker(); const typeChecker = this.programDriver.getProgram().getTypeChecker();
for (const dir of scope.compilation.directives) { for (const dir of scope.compilation.directives) {
if (dir.selector === null) { if (dir.selector === null) {
// Skip this directive, it can't be added to a template anyway. // Skip this directive, it can't be added to a template anyway.
@ -664,8 +662,9 @@ class WholeProgramTypeCheckingHost implements TypeCheckingHost {
} }
shouldCheckComponent(node: ts.ClassDeclaration): boolean { shouldCheckComponent(node: ts.ClassDeclaration): boolean {
const fileData = this.impl.getFileData(absoluteFromSourceFile(node.getSourceFile())); const sfPath = absoluteFromSourceFile(node.getSourceFile());
const shimPath = this.impl.typeCheckingStrategy.shimPathForComponent(node); const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileData = this.impl.getFileData(sfPath);
// The component needs to be checked unless the shim which would contain it already exists. // The component needs to be checked unless the shim which would contain it already exists.
return !fileData.shimData.has(shimPath); return !fileData.shimData.has(shimPath);
} }
@ -691,7 +690,7 @@ class SingleFileTypeCheckingHost implements TypeCheckingHost {
constructor( constructor(
protected sfPath: AbsoluteFsPath, protected fileData: FileTypeCheckingData, protected sfPath: AbsoluteFsPath, protected fileData: FileTypeCheckingData,
protected strategy: TypeCheckingProgramStrategy, protected impl: TemplateTypeCheckerImpl) {} protected impl: TemplateTypeCheckerImpl) {}
private assertPath(sfPath: AbsoluteFsPath): void { private assertPath(sfPath: AbsoluteFsPath): void {
if (this.sfPath !== sfPath) { if (this.sfPath !== sfPath) {
@ -708,7 +707,7 @@ class SingleFileTypeCheckingHost implements TypeCheckingHost {
if (this.sfPath !== absoluteFromSourceFile(node.getSourceFile())) { if (this.sfPath !== absoluteFromSourceFile(node.getSourceFile())) {
return false; return false;
} }
const shimPath = this.strategy.shimPathForComponent(node); const shimPath = TypeCheckShimGenerator.shimFor(this.sfPath);
// Only need to generate a TCB for the class if no shim exists for it currently. // Only need to generate a TCB for the class if no shim exists for it currently.
return !this.fileData.shimData.has(shimPath); return !this.fileData.shimData.has(shimPath);
@ -747,9 +746,9 @@ class SingleFileTypeCheckingHost implements TypeCheckingHost {
*/ */
class SingleShimTypeCheckingHost extends SingleFileTypeCheckingHost { class SingleShimTypeCheckingHost extends SingleFileTypeCheckingHost {
constructor( constructor(
sfPath: AbsoluteFsPath, fileData: FileTypeCheckingData, strategy: TypeCheckingProgramStrategy, sfPath: AbsoluteFsPath, fileData: FileTypeCheckingData, impl: TemplateTypeCheckerImpl,
impl: TemplateTypeCheckerImpl, private shimPath: AbsoluteFsPath) { private shimPath: AbsoluteFsPath) {
super(sfPath, fileData, strategy, impl); super(sfPath, fileData, impl);
} }
shouldCheckNode(node: ts.ClassDeclaration): boolean { shouldCheckNode(node: ts.ClassDeclaration): boolean {
@ -758,7 +757,7 @@ class SingleShimTypeCheckingHost extends SingleFileTypeCheckingHost {
} }
// Only generate a TCB for the component if it maps to the requested shim file. // Only generate a TCB for the component if it maps to the requested shim file.
const shimPath = this.strategy.shimPathForComponent(node); const shimPath = TypeCheckShimGenerator.shimFor(this.sfPath);
if (shimPath !== this.shimPath) { if (shimPath !== this.shimPath) {
return false; return false;
} }

View File

@ -15,12 +15,13 @@ import {NoopImportRewriter, Reference, ReferenceEmitter} from '../../imports';
import {PerfEvent, PerfRecorder} from '../../perf'; import {PerfEvent, PerfRecorder} from '../../perf';
import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {ClassDeclaration, ReflectionHost} from '../../reflection';
import {ImportManager} from '../../translator'; import {ImportManager} from '../../translator';
import {ComponentToShimMappingStrategy, TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckContext, TypeCheckingConfig, TypeCtorMetadata} from '../api'; import {TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckContext, TypeCheckingConfig, TypeCtorMetadata} from '../api';
import {makeTemplateDiagnostic, TemplateDiagnostic} from '../diagnostics'; import {makeTemplateDiagnostic, TemplateDiagnostic} from '../diagnostics';
import {DomSchemaChecker, RegistryDomSchemaChecker} from './dom'; import {DomSchemaChecker, RegistryDomSchemaChecker} from './dom';
import {Environment} from './environment'; import {Environment} from './environment';
import {OutOfBandDiagnosticRecorder, OutOfBandDiagnosticRecorderImpl} from './oob'; import {OutOfBandDiagnosticRecorder, OutOfBandDiagnosticRecorderImpl} from './oob';
import {TypeCheckShimGenerator} from './shim';
import {TemplateSourceManager} from './source'; import {TemplateSourceManager} from './source';
import {requiresInlineTypeCheckBlock} from './tcb_util'; import {requiresInlineTypeCheckBlock} from './tcb_util';
import {generateTypeCheckBlock} from './type_check_block'; import {generateTypeCheckBlock} from './type_check_block';
@ -178,7 +179,6 @@ export class TypeCheckContextImpl implements TypeCheckContext {
constructor( constructor(
private config: TypeCheckingConfig, private config: TypeCheckingConfig,
private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>,
private componentMappingStrategy: ComponentToShimMappingStrategy,
private refEmitter: ReferenceEmitter, private reflector: ReflectionHost, private refEmitter: ReferenceEmitter, private reflector: ReflectionHost,
private host: TypeCheckingHost, private inlining: InliningMode, private perf: PerfRecorder) { private host: TypeCheckingHost, private inlining: InliningMode, private perf: PerfRecorder) {
if (inlining === InliningMode.Error && config.useInlineTypeConstructors) { if (inlining === InliningMode.Error && config.useInlineTypeConstructors) {
@ -410,7 +410,7 @@ export class TypeCheckContextImpl implements TypeCheckContext {
private pendingShimForComponent(node: ts.ClassDeclaration): PendingShimData { private pendingShimForComponent(node: ts.ClassDeclaration): PendingShimData {
const fileData = this.dataForFile(node.getSourceFile()); const fileData = this.dataForFile(node.getSourceFile());
const shimPath = this.componentMappingStrategy.shimPathForComponent(node); const shimPath = TypeCheckShimGenerator.shimFor(absoluteFromSourceFile(node.getSourceFile()));
if (!fileData.shimData.has(shimPath)) { if (!fileData.shimData.has(shimPath)) {
fileData.shimData.set(shimPath, { fileData.shimData.set(shimPath, {
domSchemaChecker: new RegistryDomSchemaChecker(fileData.sourceManager), domSchemaChecker: new RegistryDomSchemaChecker(fileData.sourceManager),

View File

@ -18,6 +18,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/shims",

View File

@ -10,10 +10,10 @@ import * as ts from 'typescript';
import {absoluteFrom, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {absoluteFrom, AbsoluteFsPath, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing'; import {runInEachFileSystem} from '../../file_system/testing';
import {TsCreateProgramDriver, UpdateMode} from '../../program_driver';
import {sfExtensionData, ShimReferenceTagger} from '../../shims'; import {sfExtensionData, ShimReferenceTagger} from '../../shims';
import {expectCompleteReuse, makeProgram} from '../../testing'; import {expectCompleteReuse, makeProgram} from '../../testing';
import {OptimizeFor, UpdateMode} from '../api'; import {OptimizeFor} from '../api';
import {ReusedProgramStrategy} from '../src/augmented_program';
import {setup} from './test_utils'; import {setup} from './test_utils';
@ -37,7 +37,7 @@ runInEachFileSystem(() => {
it('should have complete reuse if no structural changes are made to shims', () => { it('should have complete reuse if no structural changes are made to shims', () => {
const {program, host, options, typecheckPath} = makeSingleFileProgramWithTypecheckShim(); const {program, host, options, typecheckPath} = makeSingleFileProgramWithTypecheckShim();
const programStrategy = new ReusedProgramStrategy(program, host, options, ['ngtypecheck']); const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']);
// Update /main.ngtypecheck.ts without changing its shape. Verify that the old program was // Update /main.ngtypecheck.ts without changing its shape. Verify that the old program was
// reused completely. // reused completely.
@ -49,7 +49,7 @@ runInEachFileSystem(() => {
it('should have complete reuse if no structural changes are made to input files', () => { it('should have complete reuse if no structural changes are made to input files', () => {
const {program, host, options, mainPath} = makeSingleFileProgramWithTypecheckShim(); const {program, host, options, mainPath} = makeSingleFileProgramWithTypecheckShim();
const programStrategy = new ReusedProgramStrategy(program, host, options, ['ngtypecheck']); const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']);
// Update /main.ts without changing its shape. Verify that the old program was reused // Update /main.ts without changing its shape. Verify that the old program was reused
// completely. // completely.

View File

@ -15,14 +15,14 @@ import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy,
import {NOOP_INCREMENTAL_BUILD} from '../../incremental'; import {NOOP_INCREMENTAL_BUILD} from '../../incremental';
import {ClassPropertyMapping, CompoundMetadataReader} from '../../metadata'; import {ClassPropertyMapping, CompoundMetadataReader} from '../../metadata';
import {NOOP_PERF_RECORDER} from '../../perf'; import {NOOP_PERF_RECORDER} from '../../perf';
import {TsCreateProgramDriver} from '../../program_driver';
import {ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {ComponentScopeReader, LocalModuleScope, ScopeData, TypeCheckScopeRegistry} from '../../scope'; import {ComponentScopeReader, LocalModuleScope, ScopeData, TypeCheckScopeRegistry} from '../../scope';
import {makeProgram} from '../../testing'; import {makeProgram} from '../../testing';
import {getRootDirs} from '../../util/src/typescript'; import {getRootDirs} from '../../util/src/typescript';
import {ProgramTypeCheckAdapter, TemplateTypeChecker, TypeCheckContext} from '../api'; import {ProgramTypeCheckAdapter, TemplateTypeChecker, TypeCheckContext} from '../api';
import {TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckingConfig, UpdateMode} from '../api/api'; import {TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckingConfig} from '../api/api';
import {TemplateDiagnostic} from '../diagnostics'; import {TemplateDiagnostic} from '../diagnostics';
import {ReusedProgramStrategy} from '../src/augmented_program';
import {TemplateTypeCheckerImpl} from '../src/checker'; import {TemplateTypeCheckerImpl} from '../src/checker';
import {DomSchemaChecker} from '../src/dom'; import {DomSchemaChecker} from '../src/dom';
import {Environment} from '../src/environment'; import {Environment} from '../src/environment';
@ -347,7 +347,7 @@ export function setup(targets: TypeCheckingTarget[], overrides: {
} = {}): { } = {}): {
templateTypeChecker: TemplateTypeChecker, templateTypeChecker: TemplateTypeChecker,
program: ts.Program, program: ts.Program,
programStrategy: ReusedProgramStrategy, programStrategy: TsCreateProgramDriver,
} { } {
const files = [ const files = [
typescriptLibDts(), typescriptLibDts(),
@ -462,7 +462,7 @@ export function setup(targets: TypeCheckingTarget[], overrides: {
} }
}); });
const programStrategy = new ReusedProgramStrategy(program, host, options, ['ngtypecheck']); const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']);
if (overrides.inlining !== undefined) { if (overrides.inlining !== undefined) {
(programStrategy as any).supportsInlineOperations = overrides.inlining; (programStrategy as any).supportsInlineOperations = overrides.inlining;
} }

View File

@ -11,11 +11,10 @@ import {absoluteFrom, AbsoluteFsPath, getFileSystem, getSourceFileOrError, Logic
import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import {runInEachFileSystem, TestFile} from '../../file_system/testing';
import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reference, ReferenceEmitter} from '../../imports'; import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reference, ReferenceEmitter} from '../../imports';
import {NOOP_PERF_RECORDER} from '../../perf'; import {NOOP_PERF_RECORDER} from '../../perf';
import {TsCreateProgramDriver, UpdateMode} from '../../program_driver';
import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {getDeclaration, makeProgram} from '../../testing'; import {getDeclaration, makeProgram} from '../../testing';
import {getRootDirs} from '../../util/src/typescript'; import {getRootDirs} from '../../util/src/typescript';
import {ComponentToShimMappingStrategy, UpdateMode} from '../api';
import {ReusedProgramStrategy} from '../src/augmented_program';
import {InliningMode, PendingFileTypeCheckingData, TypeCheckContextImpl, TypeCheckingHost} from '../src/context'; import {InliningMode, PendingFileTypeCheckingData, TypeCheckContextImpl, TypeCheckingHost} from '../src/context';
import {TemplateSourceManager} from '../src/source'; import {TemplateSourceManager} from '../src/source';
import {TypeCheckFile} from '../src/type_check_file'; import {TypeCheckFile} from '../src/type_check_file';
@ -74,8 +73,8 @@ TestClass.ngTypeCtor({value: 'test'});
new LogicalProjectStrategy(reflectionHost, logicalFs), new LogicalProjectStrategy(reflectionHost, logicalFs),
]); ]);
const ctx = new TypeCheckContextImpl( const ctx = new TypeCheckContextImpl(
ALL_ENABLED_CONFIG, host, new TestMappingStrategy(), emitter, reflectionHost, ALL_ENABLED_CONFIG, host, emitter, reflectionHost, new TestTypeCheckingHost(),
new TestTypeCheckingHost(), InliningMode.InlineOps, NOOP_PERF_RECORDER); InliningMode.InlineOps, NOOP_PERF_RECORDER);
const TestClass = const TestClass =
getDeclaration(program, _('/main.ts'), 'TestClass', isNamedClassDeclaration); getDeclaration(program, _('/main.ts'), 'TestClass', isNamedClassDeclaration);
const pendingFile = makePendingFile(); const pendingFile = makePendingFile();
@ -113,8 +112,8 @@ TestClass.ngTypeCtor({value: 'test'});
]); ]);
const pendingFile = makePendingFile(); const pendingFile = makePendingFile();
const ctx = new TypeCheckContextImpl( const ctx = new TypeCheckContextImpl(
ALL_ENABLED_CONFIG, host, new TestMappingStrategy(), emitter, reflectionHost, ALL_ENABLED_CONFIG, host, emitter, reflectionHost, new TestTypeCheckingHost(),
new TestTypeCheckingHost(), InliningMode.InlineOps, NOOP_PERF_RECORDER); InliningMode.InlineOps, NOOP_PERF_RECORDER);
const TestClass = const TestClass =
getDeclaration(program, _('/main.ts'), 'TestClass', isNamedClassDeclaration); getDeclaration(program, _('/main.ts'), 'TestClass', isNamedClassDeclaration);
ctx.addInlineTypeCtor( ctx.addInlineTypeCtor(
@ -128,7 +127,7 @@ TestClass.ngTypeCtor({value: 'test'});
}, },
coercedInputFields: new Set(), coercedInputFields: new Set(),
}); });
const programStrategy = new ReusedProgramStrategy(program, host, options, []); const programStrategy = new TsCreateProgramDriver(program, host, options, []);
programStrategy.updateFiles(ctx.finalize(), UpdateMode.Complete); programStrategy.updateFiles(ctx.finalize(), UpdateMode.Complete);
const TestClassWithCtor = getDeclaration( const TestClassWithCtor = getDeclaration(
programStrategy.getProgram(), _('/main.ts'), 'TestClass', isNamedClassDeclaration); programStrategy.getProgram(), _('/main.ts'), 'TestClass', isNamedClassDeclaration);
@ -158,8 +157,8 @@ TestClass.ngTypeCtor({value: 'test'});
]); ]);
const pendingFile = makePendingFile(); const pendingFile = makePendingFile();
const ctx = new TypeCheckContextImpl( const ctx = new TypeCheckContextImpl(
ALL_ENABLED_CONFIG, host, new TestMappingStrategy(), emitter, reflectionHost, ALL_ENABLED_CONFIG, host, emitter, reflectionHost, new TestTypeCheckingHost(),
new TestTypeCheckingHost(), InliningMode.InlineOps, NOOP_PERF_RECORDER); InliningMode.InlineOps, NOOP_PERF_RECORDER);
const TestClass = const TestClass =
getDeclaration(program, _('/main.ts'), 'TestClass', isNamedClassDeclaration); getDeclaration(program, _('/main.ts'), 'TestClass', isNamedClassDeclaration);
ctx.addInlineTypeCtor( ctx.addInlineTypeCtor(
@ -173,7 +172,7 @@ TestClass.ngTypeCtor({value: 'test'});
}, },
coercedInputFields: new Set(['bar']), coercedInputFields: new Set(['bar']),
}); });
const programStrategy = new ReusedProgramStrategy(program, host, options, []); const programStrategy = new TsCreateProgramDriver(program, host, options, []);
programStrategy.updateFiles(ctx.finalize(), UpdateMode.Complete); programStrategy.updateFiles(ctx.finalize(), UpdateMode.Complete);
const TestClassWithCtor = getDeclaration( const TestClassWithCtor = getDeclaration(
programStrategy.getProgram(), _('/main.ts'), 'TestClass', isNamedClassDeclaration); programStrategy.getProgram(), _('/main.ts'), 'TestClass', isNamedClassDeclaration);
@ -216,9 +215,3 @@ class TestTypeCheckingHost implements TypeCheckingHost {
recordComplete(): void {} recordComplete(): void {}
} }
class TestMappingStrategy implements ComponentToShimMappingStrategy {
shimPathForComponent(): AbsoluteFsPath {
return absoluteFrom('/typecheck.ts');
}
}

View File

@ -16,6 +16,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck",

View File

@ -9,8 +9,7 @@
import {CompilationTicket, freshCompilationTicket, incrementalFromCompilerTicket, NgCompiler, resourceChangeTicket} from '@angular/compiler-cli/src/ngtsc/core'; import {CompilationTicket, freshCompilationTicket, incrementalFromCompilerTicket, NgCompiler, resourceChangeTicket} from '@angular/compiler-cli/src/ngtsc/core';
import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api'; import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api';
import {TrackedIncrementalBuildStrategy} from '@angular/compiler-cli/src/ngtsc/incremental'; import {TrackedIncrementalBuildStrategy} from '@angular/compiler-cli/src/ngtsc/incremental';
import {ActivePerfRecorder} from '@angular/compiler-cli/src/ngtsc/perf'; import {ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import * as ts from 'typescript/lib/tsserverlibrary'; import * as ts from 'typescript/lib/tsserverlibrary';
import {LanguageServiceAdapter} from './adapters'; import {LanguageServiceAdapter} from './adapters';
@ -32,7 +31,7 @@ export class CompilerFactory {
constructor( constructor(
private readonly adapter: LanguageServiceAdapter, private readonly adapter: LanguageServiceAdapter,
private readonly programStrategy: TypeCheckingProgramStrategy, private readonly programStrategy: ProgramDriver,
private readonly options: NgCompilerOptions, private readonly options: NgCompilerOptions,
) {} ) {}

View File

@ -47,7 +47,7 @@ export enum CompletionNodeContext {
* @param N type of the template node in question, narrowed accordingly. * @param N type of the template node in question, narrowed accordingly.
*/ */
export class CompletionBuilder<N extends TmplAstNode|AST> { export class CompletionBuilder<N extends TmplAstNode|AST> {
private readonly typeChecker = this.compiler.getNextProgram().getTypeChecker(); private readonly typeChecker = this.compiler.getCurrentProgram().getTypeChecker();
private readonly templateTypeChecker = this.compiler.getTemplateTypeChecker(); private readonly templateTypeChecker = this.compiler.getTemplateTypeChecker();
private readonly nodeParent = this.targetDetails.parent; private readonly nodeParent = this.targetDetails.parent;
private readonly nodeContext = nodeContextFromTarget(this.targetDetails.context); private readonly nodeContext = nodeContextFromTarget(this.targetDetails.context);

View File

@ -282,7 +282,7 @@ export class DefinitionBuilder {
function getDefinitionForExpressionAtPosition( function getDefinitionForExpressionAtPosition(
fileName: string, position: number, compiler: NgCompiler): ts.DefinitionInfoAndBoundSpan| fileName: string, position: number, compiler: NgCompiler): ts.DefinitionInfoAndBoundSpan|
undefined { undefined {
const sf = compiler.getNextProgram().getSourceFile(fileName); const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) { if (sf === undefined) {
return; return;
} }

View File

@ -12,9 +12,10 @@ import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics'; import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import {absoluteFrom, absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system'; import {absoluteFrom, absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf'; import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf';
import {ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection'; import {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection';
import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck'; import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck';
import {OptimizeFor, TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import {OptimizeFor} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import {findFirstMatchingNode} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments'; import {findFirstMatchingNode} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments';
import * as ts from 'typescript/lib/tsserverlibrary'; import * as ts from 'typescript/lib/tsserverlibrary';
@ -41,7 +42,7 @@ interface LanguageServiceConfig {
export class LanguageService { export class LanguageService {
private options: CompilerOptions; private options: CompilerOptions;
readonly compilerFactory: CompilerFactory; readonly compilerFactory: CompilerFactory;
private readonly strategy: TypeCheckingProgramStrategy; private readonly programDriver: ProgramDriver;
private readonly adapter: LanguageServiceAdapter; private readonly adapter: LanguageServiceAdapter;
private readonly parseConfigHost: LSParseConfigHost; private readonly parseConfigHost: LSParseConfigHost;
@ -53,9 +54,9 @@ export class LanguageService {
this.parseConfigHost = new LSParseConfigHost(project.projectService.host); this.parseConfigHost = new LSParseConfigHost(project.projectService.host);
this.options = parseNgCompilerOptions(project, this.parseConfigHost, config); this.options = parseNgCompilerOptions(project, this.parseConfigHost, config);
logCompilerOptions(project, this.options); logCompilerOptions(project, this.options);
this.strategy = createTypeCheckingProgramStrategy(project); this.programDriver = createProgramDriver(project);
this.adapter = new LanguageServiceAdapter(project); this.adapter = new LanguageServiceAdapter(project);
this.compilerFactory = new CompilerFactory(this.adapter, this.strategy, this.options); this.compilerFactory = new CompilerFactory(this.adapter, this.programDriver, this.options);
this.watchConfigFile(project); this.watchConfigFile(project);
} }
@ -68,7 +69,7 @@ export class LanguageService {
const ttc = compiler.getTemplateTypeChecker(); const ttc = compiler.getTemplateTypeChecker();
const diagnostics: ts.Diagnostic[] = []; const diagnostics: ts.Diagnostic[] = [];
if (isTypeScriptFile(fileName)) { if (isTypeScriptFile(fileName)) {
const program = compiler.getNextProgram(); const program = compiler.getCurrentProgram();
const sourceFile = program.getSourceFile(fileName); const sourceFile = program.getSourceFile(fileName);
if (sourceFile) { if (sourceFile) {
const ngDiagnostics = compiler.getDiagnosticsForFile(sourceFile, OptimizeFor.SingleFile); const ngDiagnostics = compiler.getDiagnosticsForFile(sourceFile, OptimizeFor.SingleFile);
@ -112,7 +113,7 @@ export class LanguageService {
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|undefined { |undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsDefinition, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsDefinition, (compiler) => {
if (!isInAngularContext(compiler.getNextProgram(), fileName, position)) { if (!isInAngularContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined; return undefined;
} }
return new DefinitionBuilder(this.tsLS, compiler) return new DefinitionBuilder(this.tsLS, compiler)
@ -123,7 +124,7 @@ export class LanguageService {
getTypeDefinitionAtPosition(fileName: string, position: number): getTypeDefinitionAtPosition(fileName: string, position: number):
readonly ts.DefinitionInfo[]|undefined { readonly ts.DefinitionInfo[]|undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsDefinition, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsDefinition, (compiler) => {
if (!isTemplateContext(compiler.getNextProgram(), fileName, position)) { if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined; return undefined;
} }
return new DefinitionBuilder(this.tsLS, compiler) return new DefinitionBuilder(this.tsLS, compiler)
@ -142,7 +143,7 @@ export class LanguageService {
position: number, position: number,
compiler: NgCompiler, compiler: NgCompiler,
): ts.QuickInfo|undefined { ): ts.QuickInfo|undefined {
if (!isTemplateContext(compiler.getNextProgram(), fileName, position)) { if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined; return undefined;
} }
@ -166,14 +167,14 @@ export class LanguageService {
getReferencesAtPosition(fileName: string, position: number): ts.ReferenceEntry[]|undefined { getReferencesAtPosition(fileName: string, position: number): ts.ReferenceEntry[]|undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => {
return new ReferencesAndRenameBuilder(this.strategy, this.tsLS, compiler) return new ReferencesAndRenameBuilder(this.programDriver, this.tsLS, compiler)
.getReferencesAtPosition(fileName, position); .getReferencesAtPosition(fileName, position);
}); });
} }
getRenameInfo(fileName: string, position: number): ts.RenameInfo { getRenameInfo(fileName: string, position: number): ts.RenameInfo {
return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => {
const renameInfo = new ReferencesAndRenameBuilder(this.strategy, this.tsLS, compiler) const renameInfo = new ReferencesAndRenameBuilder(this.programDriver, this.tsLS, compiler)
.getRenameInfo(absoluteFrom(fileName), position); .getRenameInfo(absoluteFrom(fileName), position);
if (!renameInfo.canRename) { if (!renameInfo.canRename) {
return renameInfo; return renameInfo;
@ -189,7 +190,7 @@ export class LanguageService {
findRenameLocations(fileName: string, position: number): readonly ts.RenameLocation[]|undefined { findRenameLocations(fileName: string, position: number): readonly ts.RenameLocation[]|undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => {
return new ReferencesAndRenameBuilder(this.strategy, this.tsLS, compiler) return new ReferencesAndRenameBuilder(this.programDriver, this.tsLS, compiler)
.findRenameLocations(fileName, position); .findRenameLocations(fileName, position);
}); });
} }
@ -225,7 +226,7 @@ export class LanguageService {
private getCompletionsAtPositionImpl( private getCompletionsAtPositionImpl(
fileName: string, position: number, options: ts.GetCompletionsAtPositionOptions|undefined, fileName: string, position: number, options: ts.GetCompletionsAtPositionOptions|undefined,
compiler: NgCompiler): ts.WithMetadata<ts.CompletionInfo>|undefined { compiler: NgCompiler): ts.WithMetadata<ts.CompletionInfo>|undefined {
if (!isTemplateContext(compiler.getNextProgram(), fileName, position)) { if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined; return undefined;
} }
@ -241,7 +242,7 @@ export class LanguageService {
formatOptions: ts.FormatCodeOptions|ts.FormatCodeSettings|undefined, formatOptions: ts.FormatCodeOptions|ts.FormatCodeSettings|undefined,
preferences: ts.UserPreferences|undefined): ts.CompletionEntryDetails|undefined { preferences: ts.UserPreferences|undefined): ts.CompletionEntryDetails|undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => {
if (!isTemplateContext(compiler.getNextProgram(), fileName, position)) { if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined; return undefined;
} }
@ -256,7 +257,7 @@ export class LanguageService {
getCompletionEntrySymbol(fileName: string, position: number, entryName: string): ts.Symbol getCompletionEntrySymbol(fileName: string, position: number, entryName: string): ts.Symbol
|undefined { |undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => { return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => {
if (!isTemplateContext(compiler.getNextProgram(), fileName, position)) { if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined; return undefined;
} }
@ -457,13 +458,9 @@ function parseNgCompilerOptions(
return options; return options;
} }
function createTypeCheckingProgramStrategy(project: ts.server.Project): function createProgramDriver(project: ts.server.Project): ProgramDriver {
TypeCheckingProgramStrategy {
return { return {
supportsInlineOperations: false, supportsInlineOperations: false,
shimPathForComponent(component: ts.ClassDeclaration): AbsoluteFsPath {
return TypeCheckShimGenerator.shimFor(absoluteFromSourceFile(component.getSourceFile()));
},
getProgram(): ts.Program { getProgram(): ts.Program {
const program = project.getLanguageService().getProgram(); const program = project.getLanguageService().getProgram();
if (!program) { if (!program) {

View File

@ -14,7 +14,7 @@ import {createDisplayParts, DisplayInfoKind, SYMBOL_PUNC, SYMBOL_SPACE, SYMBOL_T
import {filterAliasImports, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTextSpanOfNode} from './utils'; import {filterAliasImports, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTextSpanOfNode} from './utils';
export class QuickInfoBuilder { export class QuickInfoBuilder {
private readonly typeChecker = this.compiler.getNextProgram().getTypeChecker(); private readonly typeChecker = this.compiler.getCurrentProgram().getTypeChecker();
constructor( constructor(
private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler, private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler,

View File

@ -9,7 +9,8 @@ import {AbsoluteSourceSpan, AST, BindingPipe, LiteralPrimitive, MethodCall, Pars
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core'; import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {absoluteFrom, absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system'; import {absoluteFrom, absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf'; import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf';
import {DirectiveSymbol, ShimLocation, SymbolKind, TemplateTypeChecker, TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import {ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {DirectiveSymbol, ShimLocation, SymbolKind, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import {ExpressionIdentifier, hasExpressionIdentifier} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments'; import {ExpressionIdentifier, hasExpressionIdentifier} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments';
import * as ts from 'typescript'; import * as ts from 'typescript';
@ -62,8 +63,8 @@ export class ReferencesAndRenameBuilder {
private readonly ttc = this.compiler.getTemplateTypeChecker(); private readonly ttc = this.compiler.getTemplateTypeChecker();
constructor( constructor(
private readonly strategy: TypeCheckingProgramStrategy, private readonly driver: ProgramDriver, private readonly tsLS: ts.LanguageService,
private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler) {} private readonly compiler: NgCompiler) {}
getRenameInfo(filePath: string, position: number): getRenameInfo(filePath: string, position: number):
Omit<ts.RenameInfoSuccess, 'kind'|'kindModifiers'>|ts.RenameInfoFailure { Omit<ts.RenameInfoSuccess, 'kind'|'kindModifiers'>|ts.RenameInfoFailure {
@ -146,7 +147,7 @@ export class ReferencesAndRenameBuilder {
} }
private getTsNodeAtPosition(filePath: string, position: number): ts.Node|null { private getTsNodeAtPosition(filePath: string, position: number): ts.Node|null {
const sf = this.strategy.getProgram().getSourceFile(filePath); const sf = this.driver.getProgram().getSourceFile(filePath);
if (!sf) { if (!sf) {
return null; return null;
} }
@ -376,7 +377,7 @@ export class ReferencesAndRenameBuilder {
private convertToTemplateDocumentSpan<T extends ts.DocumentSpan>( private convertToTemplateDocumentSpan<T extends ts.DocumentSpan>(
shimDocumentSpan: T, templateTypeChecker: TemplateTypeChecker, requiredNodeText?: string): T shimDocumentSpan: T, templateTypeChecker: TemplateTypeChecker, requiredNodeText?: string): T
|null { |null {
const sf = this.strategy.getProgram().getSourceFile(shimDocumentSpan.fileName); const sf = this.driver.getProgram().getSourceFile(shimDocumentSpan.fileName);
if (sf === undefined) { if (sf === undefined) {
return null; return null;
} }

View File

@ -121,7 +121,7 @@ function getInlineTemplateInfoAtPosition(
export function getTemplateInfoAtPosition( export function getTemplateInfoAtPosition(
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined { fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
if (isTypeScriptFile(fileName)) { if (isTypeScriptFile(fileName)) {
const sf = compiler.getNextProgram().getSourceFile(fileName); const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) { if (sf === undefined) {
return undefined; return undefined;
} }