_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts_9832_17961
getDiagnosticsForFile(sf: ts.SourceFile, optimizeFor: OptimizeFor): ts.Diagnostic[] { switch (optimizeFor) { case OptimizeFor.WholeProgram: this.ensureAllShimsForAllFiles(); break; case OptimizeFor.SingleFile: this.ensureAllShimsForOneFile(sf); break; } return this.perf.inPhase(PerfPhase.TtcDiagnostics, () => { const sfPath = absoluteFromSourceFile(sf); const fileRecord = this.state.get(sfPath)!; const typeCheckProgram = this.programDriver.getProgram(); const diagnostics: (ts.Diagnostic | null)[] = []; if (fileRecord.hasInlines) { const inlineSf = getSourceFileOrError(typeCheckProgram, sfPath); diagnostics.push( ...typeCheckProgram .getSemanticDiagnostics(inlineSf) .map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)), ); } for (const [shimPath, shimRecord] of fileRecord.shimData) { const shimSf = getSourceFileOrError(typeCheckProgram, shimPath); diagnostics.push( ...typeCheckProgram .getSemanticDiagnostics(shimSf) .map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)), ); diagnostics.push(...shimRecord.genesisDiagnostics); for (const templateData of shimRecord.templates.values()) { diagnostics.push(...templateData.templateDiagnostics); } } return diagnostics.filter( (diag: ts.Diagnostic | null): diag is ts.Diagnostic => diag !== null, ); }); } getDiagnosticsForComponent(component: ts.ClassDeclaration): ts.Diagnostic[] { this.ensureShimForComponent(component); return this.perf.inPhase(PerfPhase.TtcDiagnostics, () => { const sf = component.getSourceFile(); const sfPath = absoluteFromSourceFile(sf); const shimPath = TypeCheckShimGenerator.shimFor(sfPath); const fileRecord = this.getFileData(sfPath); if (!fileRecord.shimData.has(shimPath)) { return []; } const templateId = fileRecord.sourceManager.getTemplateId(component); const shimRecord = fileRecord.shimData.get(shimPath)!; const typeCheckProgram = this.programDriver.getProgram(); const diagnostics: (TemplateDiagnostic | null)[] = []; if (shimRecord.hasInlines) { const inlineSf = getSourceFileOrError(typeCheckProgram, sfPath); diagnostics.push( ...typeCheckProgram .getSemanticDiagnostics(inlineSf) .map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)), ); } const shimSf = getSourceFileOrError(typeCheckProgram, shimPath); diagnostics.push( ...typeCheckProgram .getSemanticDiagnostics(shimSf) .map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)), ); diagnostics.push(...shimRecord.genesisDiagnostics); for (const templateData of shimRecord.templates.values()) { diagnostics.push(...templateData.templateDiagnostics); } return diagnostics.filter( (diag: TemplateDiagnostic | null): diag is TemplateDiagnostic => diag !== null && diag.templateId === templateId, ); }); } getTypeCheckBlock(component: ts.ClassDeclaration): ts.Node | null { return this.getLatestComponentState(component).tcb; } getGlobalCompletions( context: TmplAstTemplate | null, component: ts.ClassDeclaration, node: AST | TmplAstNode, ): GlobalCompletion | null { const engine = this.getOrCreateCompletionEngine(component); if (engine === null) { return null; } return this.perf.inPhase(PerfPhase.TtcAutocompletion, () => engine.getGlobalCompletions(context, node), ); } getExpressionCompletionLocation( ast: PropertyRead | SafePropertyRead, component: ts.ClassDeclaration, ): TcbLocation | null { const engine = this.getOrCreateCompletionEngine(component); if (engine === null) { return null; } return this.perf.inPhase(PerfPhase.TtcAutocompletion, () => engine.getExpressionCompletionLocation(ast), ); } getLiteralCompletionLocation( node: LiteralPrimitive | TmplAstTextAttribute, component: ts.ClassDeclaration, ): TcbLocation | null { const engine = this.getOrCreateCompletionEngine(component); if (engine === null) { return null; } return this.perf.inPhase(PerfPhase.TtcAutocompletion, () => engine.getLiteralCompletionLocation(node), ); } invalidateClass(clazz: ts.ClassDeclaration): void { this.completionCache.delete(clazz); this.symbolBuilderCache.delete(clazz); this.scopeCache.delete(clazz); this.elementTagCache.delete(clazz); const sf = clazz.getSourceFile(); const sfPath = absoluteFromSourceFile(sf); const shimPath = TypeCheckShimGenerator.shimFor(sfPath); const fileData = this.getFileData(sfPath); const templateId = fileData.sourceManager.getTemplateId(clazz); fileData.shimData.delete(shimPath); fileData.isComplete = false; this.isComplete = false; } getExpressionTarget(expression: AST, clazz: ts.ClassDeclaration): TemplateEntity | null { return ( this.getLatestComponentState(clazz).data?.boundTarget.getExpressionTarget(expression) || null ); } makeTemplateDiagnostic<T extends ErrorCode>( clazz: ts.ClassDeclaration, sourceSpan: ParseSourceSpan, category: ts.DiagnosticCategory, errorCode: T, message: string, relatedInformation?: { text: string; start: number; end: number; sourceFile: ts.SourceFile; }[], ): NgTemplateDiagnostic<T> { const sfPath = absoluteFromSourceFile(clazz.getSourceFile()); const fileRecord = this.state.get(sfPath)!; const templateId = fileRecord.sourceManager.getTemplateId(clazz); const mapping = fileRecord.sourceManager.getSourceMapping(templateId); return { ...makeTemplateDiagnostic( templateId, mapping, sourceSpan, category, ngErrorCode(errorCode), message, relatedInformation, ), __ngCode: errorCode, }; } private getOrCreateCompletionEngine(component: ts.ClassDeclaration): CompletionEngine | null { if (this.completionCache.has(component)) { return this.completionCache.get(component)!; } const {tcb, data, tcbPath, tcbIsShim} = this.getLatestComponentState(component); if (tcb === null || data === null) { return null; } const engine = new CompletionEngine(tcb, data, tcbPath, tcbIsShim); this.completionCache.set(component, engine); return engine; } private maybeAdoptPriorResultsForFile(sf: ts.SourceFile): void { const sfPath = absoluteFromSourceFile(sf); if (this.state.has(sfPath)) { const existingResults = this.state.get(sfPath)!; if (existingResults.isComplete) { // All data for this file has already been generated, so no need to adopt anything. return; } } const previousResults = this.priorBuild.priorTypeCheckingResultsFor(sf); if (previousResults === null || !previousResults.isComplete) { return; } this.perf.eventCount(PerfEvent.ReuseTypeCheckFile); this.state.set(sfPath, previousResults); } private ensureAllShimsForAllFiles(): void { if (this.isComplete) { return; } this.perf.inPhase(PerfPhase.TcbGeneration, () => { const host = new WholeProgramTypeCheckingHost(this); const ctx = this.newContext(host); for (const sf of this.originalProgram.getSourceFiles()) { if (sf.isDeclarationFile || isShim(sf)) { continue; } this.maybeAdoptPriorResultsForFile(sf); const sfPath = absoluteFromSourceFile(sf); const fileData = this.getFileData(sfPath); if (fileData.isComplete) { continue; } this.typeCheckAdapter.typeCheck(sf, ctx); fileData.isComplete = true; } this.updateFromContext(ctx); this.isComplete = true; }); }
{ "end_byte": 17961, "start_byte": 9832, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts_17965_26555
private ensureAllShimsForOneFile(sf: ts.SourceFile): void { this.perf.inPhase(PerfPhase.TcbGeneration, () => { this.maybeAdoptPriorResultsForFile(sf); const sfPath = absoluteFromSourceFile(sf); const fileData = this.getFileData(sfPath); if (fileData.isComplete) { // All data for this file is present and accounted for already. return; } const host = new SingleFileTypeCheckingHost(sfPath, fileData, this); const ctx = this.newContext(host); this.typeCheckAdapter.typeCheck(sf, ctx); fileData.isComplete = true; this.updateFromContext(ctx); }); } private ensureShimForComponent(component: ts.ClassDeclaration): void { const sf = component.getSourceFile(); const sfPath = absoluteFromSourceFile(sf); const shimPath = TypeCheckShimGenerator.shimFor(sfPath); this.maybeAdoptPriorResultsForFile(sf); const fileData = this.getFileData(sfPath); if (fileData.shimData.has(shimPath)) { // All data for this component is available. return; } const host = new SingleShimTypeCheckingHost(sfPath, fileData, this, shimPath); const ctx = this.newContext(host); this.typeCheckAdapter.typeCheck(sf, ctx); this.updateFromContext(ctx); } private newContext(host: TypeCheckingHost): TypeCheckContextImpl { const inlining = this.programDriver.supportsInlineOperations ? InliningMode.InlineOps : InliningMode.Error; return new TypeCheckContextImpl( this.config, this.compilerHost, this.refEmitter, this.reflector, host, inlining, this.perf, ); } /** * Remove any shim data that depends on inline operations applied to the type-checking program. * * This can be useful if new inlines need to be applied, and it's not possible to guarantee that * they won't overwrite or corrupt existing inlines that are used by such shims. */ clearAllShimDataUsingInlines(): void { for (const fileData of this.state.values()) { if (!fileData.hasInlines) { continue; } for (const [shimFile, shimData] of fileData.shimData.entries()) { if (shimData.hasInlines) { fileData.shimData.delete(shimFile); } } fileData.hasInlines = false; fileData.isComplete = false; this.isComplete = false; } } private updateFromContext(ctx: TypeCheckContextImpl): void { const updates = ctx.finalize(); return this.perf.inPhase(PerfPhase.TcbUpdateProgram, () => { if (updates.size > 0) { this.perf.eventCount(PerfEvent.UpdateTypeCheckProgram); } this.programDriver.updateFiles(updates, UpdateMode.Incremental); this.priorBuild.recordSuccessfulTypeCheck(this.state); this.perf.memory(PerfCheckpoint.TtcUpdateProgram); }); } getFileData(path: AbsoluteFsPath): FileTypeCheckingData { if (!this.state.has(path)) { this.state.set(path, { hasInlines: false, sourceManager: new TemplateSourceManager(), isComplete: false, shimData: new Map(), }); } return this.state.get(path)!; } getSymbolOfNode(node: TmplAstTemplate, component: ts.ClassDeclaration): TemplateSymbol | null; getSymbolOfNode(node: TmplAstElement, component: ts.ClassDeclaration): ElementSymbol | null; getSymbolOfNode(node: AST | TmplAstNode, component: ts.ClassDeclaration): Symbol | null { const builder = this.getOrCreateSymbolBuilder(component); if (builder === null) { return null; } return this.perf.inPhase(PerfPhase.TtcSymbol, () => builder.getSymbol(node)); } private getOrCreateSymbolBuilder(component: ts.ClassDeclaration): SymbolBuilder | null { if (this.symbolBuilderCache.has(component)) { return this.symbolBuilderCache.get(component)!; } const {tcb, data, tcbPath, tcbIsShim} = this.getLatestComponentState(component); if (tcb === null || data === null) { return null; } const builder = new SymbolBuilder( tcbPath, tcbIsShim, tcb, data, this.componentScopeReader, () => this.programDriver.getProgram().getTypeChecker(), ); this.symbolBuilderCache.set(component, builder); return builder; } getPotentialTemplateDirectives(component: ts.ClassDeclaration): PotentialDirective[] { const typeChecker = this.programDriver.getProgram().getTypeChecker(); const inScopeDirectives = this.getScopeData(component)?.directives ?? []; const resultingDirectives = new Map<ClassDeclaration<DeclarationNode>, PotentialDirective>(); // First, all in scope directives can be used. for (const d of inScopeDirectives) { resultingDirectives.set(d.ref.node, d); } // Any additional directives found from the global registry can be used, but are not in scope. // In the future, we can also walk other registries for .d.ts files, or traverse the // import/export graph. for (const directiveClass of this.localMetaReader.getKnown(MetaKind.Directive)) { const directiveMeta = this.metaReader.getDirectiveMetadata(new Reference(directiveClass)); if (directiveMeta === null) continue; if (resultingDirectives.has(directiveClass)) continue; const withScope = this.scopeDataOfDirectiveMeta(typeChecker, directiveMeta); if (withScope === null) continue; resultingDirectives.set(directiveClass, {...withScope, isInScope: false}); } return Array.from(resultingDirectives.values()); } getPotentialPipes(component: ts.ClassDeclaration): PotentialPipe[] { // Very similar to the above `getPotentialTemplateDirectives`, but on pipes. const typeChecker = this.programDriver.getProgram().getTypeChecker(); const inScopePipes = this.getScopeData(component)?.pipes ?? []; const resultingPipes = new Map<ClassDeclaration<DeclarationNode>, PotentialPipe>(); for (const p of inScopePipes) { resultingPipes.set(p.ref.node, p); } for (const pipeClass of this.localMetaReader.getKnown(MetaKind.Pipe)) { const pipeMeta = this.metaReader.getPipeMetadata(new Reference(pipeClass)); if (pipeMeta === null) continue; if (resultingPipes.has(pipeClass)) continue; const withScope = this.scopeDataOfPipeMeta(typeChecker, pipeMeta); if (withScope === null) continue; resultingPipes.set(pipeClass, {...withScope, isInScope: false}); } return Array.from(resultingPipes.values()); } getDirectiveMetadata(dir: ts.ClassDeclaration): TypeCheckableDirectiveMeta | null { if (!isNamedClassDeclaration(dir)) { return null; } return this.typeCheckScopeRegistry.getTypeCheckDirectiveMetadata(new Reference(dir)); } getNgModuleMetadata(module: ts.ClassDeclaration): NgModuleMeta | null { if (!isNamedClassDeclaration(module)) { return null; } return this.metaReader.getNgModuleMetadata(new Reference(module)); } getPipeMetadata(pipe: ts.ClassDeclaration): PipeMeta | null { if (!isNamedClassDeclaration(pipe)) { return null; } return this.metaReader.getPipeMetadata(new Reference(pipe)); } getPotentialElementTags(component: ts.ClassDeclaration): Map<string, PotentialDirective | null> { if (this.elementTagCache.has(component)) { return this.elementTagCache.get(component)!; } const tagMap = new Map<string, PotentialDirective | null>(); for (const tag of REGISTRY.allKnownElementNames()) { tagMap.set(tag, null); } const potentialDirectives = this.getPotentialTemplateDirectives(component); for (const directive of potentialDirectives) { if (directive.selector === null) { continue; } for (const selector of CssSelector.parse(directive.selector)) { if (selector.element === null || tagMap.has(selector.element)) { // Skip this directive if it doesn't match an element tag, or if another directive has // already been included with the same element name. continue; } tagMap.set(selector.element, directive); } } this.elementTagCache.set(component, tagMap); return tagMap; } getPotentialDomBindings(tagName: string): {attribute: string; property: string}[] { const attributes = REGISTRY.allKnownAttributesOfElement(tagName); return attributes.map((attribute) => ({ attribute, property: REGISTRY.getMappedPropName(attribute), })); } getPotentialDomEvents(tagName: string): string[] { return REGISTRY.allKnownEventsOfElement(tagName); }
{ "end_byte": 26555, "start_byte": 17965, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts_26559_34247
getPrimaryAngularDecorator(target: ts.ClassDeclaration): ts.Decorator | null { this.ensureAllShimsForOneFile(target.getSourceFile()); if (!isNamedClassDeclaration(target)) { return null; } const ref = new Reference(target); const dirMeta = this.metaReader.getDirectiveMetadata(ref); if (dirMeta !== null) { return dirMeta.decorator; } const pipeMeta = this.metaReader.getPipeMetadata(ref); if (pipeMeta !== null) { return pipeMeta.decorator; } const ngModuleMeta = this.metaReader.getNgModuleMetadata(ref); if (ngModuleMeta !== null) { return ngModuleMeta.decorator; } return null; } getOwningNgModule(component: ts.ClassDeclaration): ts.ClassDeclaration | null { if (!isNamedClassDeclaration(component)) { return null; } const dirMeta = this.metaReader.getDirectiveMetadata(new Reference(component)); if (dirMeta !== null && dirMeta.isStandalone) { return null; } const scope = this.componentScopeReader.getScopeForComponent(component); if ( scope === null || scope.kind !== ComponentScopeKind.NgModule || !isNamedClassDeclaration(scope.ngModule) ) { return null; } return scope.ngModule; } private emit( kind: PotentialImportKind, refTo: Reference<ClassDeclaration>, inContext: ts.ClassDeclaration, ): PotentialImport | null { const emittedRef = this.refEmitter.emit(refTo, inContext.getSourceFile()); if (emittedRef.kind === ReferenceEmitKind.Failed) { return null; } const emitted = emittedRef.expression; if (emitted instanceof WrappedNodeExpr) { if (refTo.node === inContext) { // Suppress self-imports since components do not have to import themselves. return null; } let isForwardReference = false; if (emitted.node.getStart() > inContext.getStart()) { const declaration = this.programDriver .getProgram() .getTypeChecker() .getTypeAtLocation(emitted.node) .getSymbol()?.declarations?.[0]; if (declaration && declaration.getSourceFile() === inContext.getSourceFile()) { isForwardReference = true; } } // An appropriate identifier is already in scope. return {kind, symbolName: emitted.node.text, isForwardReference}; } else if ( emitted instanceof ExternalExpr && emitted.value.moduleName !== null && emitted.value.name !== null ) { return { kind, moduleSpecifier: emitted.value.moduleName, symbolName: emitted.value.name, isForwardReference: false, }; } return null; } getPotentialImportsFor( toImport: Reference<ClassDeclaration>, inContext: ts.ClassDeclaration, importMode: PotentialImportMode, ): ReadonlyArray<PotentialImport> { const imports: PotentialImport[] = []; const meta = this.metaReader.getDirectiveMetadata(toImport) ?? this.metaReader.getPipeMetadata(toImport); if (meta === null) { return imports; } if (meta.isStandalone || importMode === PotentialImportMode.ForceDirect) { const emitted = this.emit(PotentialImportKind.Standalone, toImport, inContext); if (emitted !== null) { imports.push(emitted); } } const exportingNgModules = this.ngModuleIndex.getNgModulesExporting(meta.ref.node); if (exportingNgModules !== null) { for (const exporter of exportingNgModules) { const emittedRef = this.emit(PotentialImportKind.NgModule, exporter, inContext); if (emittedRef !== null) { imports.push(emittedRef); } } } return imports; } private getScopeData(component: ts.ClassDeclaration): ScopeData | null { if (this.scopeCache.has(component)) { return this.scopeCache.get(component)!; } if (!isNamedClassDeclaration(component)) { throw new Error(`AssertionError: components must have names`); } const scope = this.componentScopeReader.getScopeForComponent(component); if (scope === null) { return null; } const dependencies = scope.kind === ComponentScopeKind.NgModule ? scope.compilation.dependencies : scope.dependencies; const data: ScopeData = { directives: [], pipes: [], isPoisoned: scope.kind === ComponentScopeKind.NgModule ? scope.compilation.isPoisoned : scope.isPoisoned, }; const typeChecker = this.programDriver.getProgram().getTypeChecker(); for (const dep of dependencies) { if (dep.kind === MetaKind.Directive) { const dirScope = this.scopeDataOfDirectiveMeta(typeChecker, dep); if (dirScope === null) continue; data.directives.push({...dirScope, isInScope: true}); } else if (dep.kind === MetaKind.Pipe) { const pipeScope = this.scopeDataOfPipeMeta(typeChecker, dep); if (pipeScope === null) continue; data.pipes.push({...pipeScope, isInScope: true}); } } this.scopeCache.set(component, data); return data; } private scopeDataOfDirectiveMeta( typeChecker: ts.TypeChecker, dep: DirectiveMeta, ): Omit<PotentialDirective, 'isInScope'> | null { if (dep.selector === null) { // Skip this directive, it can't be added to a template anyway. return null; } const tsSymbol = typeChecker.getSymbolAtLocation(dep.ref.node.name); if (!isSymbolWithValueDeclaration(tsSymbol)) { return null; } let ngModule: ClassDeclaration | null = null; const moduleScopeOfDir = this.componentScopeReader.getScopeForComponent(dep.ref.node); if (moduleScopeOfDir !== null && moduleScopeOfDir.kind === ComponentScopeKind.NgModule) { ngModule = moduleScopeOfDir.ngModule; } return { ref: dep.ref, isComponent: dep.isComponent, isStructural: dep.isStructural, selector: dep.selector, tsSymbol, ngModule, }; } private scopeDataOfPipeMeta( typeChecker: ts.TypeChecker, dep: PipeMeta, ): Omit<PotentialPipe, 'isInScope'> | null { const tsSymbol = typeChecker.getSymbolAtLocation(dep.ref.node.name); if (tsSymbol === undefined) { return null; } return { ref: dep.ref, name: dep.name, tsSymbol, }; } } function convertDiagnostic( diag: ts.Diagnostic, sourceResolver: TemplateSourceResolver, ): TemplateDiagnostic | null { if (!shouldReportDiagnostic(diag)) { return null; } return translateDiagnostic(diag, sourceResolver); } /** * Data for template type-checking related to a specific input file in the user's program (which * contains components to be checked). */ export interface FileTypeCheckingData { /** * Whether the type-checking shim required any inline changes to the original file, which affects * whether the shim can be reused. */ hasInlines: boolean; /** * Source mapping information for mapping diagnostics from inlined type check blocks back to the * original template. */ sourceManager: TemplateSourceManager; /** * Data for each shim generated from this input file. * * A single input file will generate one or more shim files that actually contain template * type-checking code. */ shimData: Map<AbsoluteFsPath, ShimTypeCheckingData>; /** * Whether the template type-checker is certain that all components from this input file have had * type-checking code generated into shims. */ isComplete: boolean; } /** * Drives a `TypeCheckContext` to generate type-checking code for every component in the program. */
{ "end_byte": 34247, "start_byte": 26559, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts_34248_38422
class WholeProgramTypeCheckingHost implements TypeCheckingHost { constructor(private impl: TemplateTypeCheckerImpl) {} getSourceManager(sfPath: AbsoluteFsPath): TemplateSourceManager { return this.impl.getFileData(sfPath).sourceManager; } shouldCheckComponent(node: ts.ClassDeclaration): boolean { const sfPath = absoluteFromSourceFile(node.getSourceFile()); 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. return !fileData.shimData.has(shimPath); } recordShimData(sfPath: AbsoluteFsPath, data: ShimTypeCheckingData): void { const fileData = this.impl.getFileData(sfPath); fileData.shimData.set(data.path, data); if (data.hasInlines) { fileData.hasInlines = true; } } recordComplete(sfPath: AbsoluteFsPath): void { this.impl.getFileData(sfPath).isComplete = true; } } /** * Drives a `TypeCheckContext` to generate type-checking code efficiently for a single input file. */ class SingleFileTypeCheckingHost implements TypeCheckingHost { private seenInlines = false; constructor( protected sfPath: AbsoluteFsPath, protected fileData: FileTypeCheckingData, protected impl: TemplateTypeCheckerImpl, ) {} private assertPath(sfPath: AbsoluteFsPath): void { if (this.sfPath !== sfPath) { throw new Error(`AssertionError: querying TypeCheckingHost outside of assigned file`); } } getSourceManager(sfPath: AbsoluteFsPath): TemplateSourceManager { this.assertPath(sfPath); return this.fileData.sourceManager; } shouldCheckComponent(node: ts.ClassDeclaration): boolean { if (this.sfPath !== absoluteFromSourceFile(node.getSourceFile())) { return false; } const shimPath = TypeCheckShimGenerator.shimFor(this.sfPath); // Only need to generate a TCB for the class if no shim exists for it currently. return !this.fileData.shimData.has(shimPath); } recordShimData(sfPath: AbsoluteFsPath, data: ShimTypeCheckingData): void { this.assertPath(sfPath); // Previous type-checking state may have required the use of inlines (assuming they were // supported). If the current operation also requires inlines, this presents a problem: // generating new inlines may invalidate any old inlines that old state depends on. // // Rather than resolve this issue by tracking specific dependencies on inlines, if the new state // relies on inlines, any old state that relied on them is simply cleared. This happens when the // first new state that uses inlines is encountered. if (data.hasInlines && !this.seenInlines) { this.impl.clearAllShimDataUsingInlines(); this.seenInlines = true; } this.fileData.shimData.set(data.path, data); if (data.hasInlines) { this.fileData.hasInlines = true; } } recordComplete(sfPath: AbsoluteFsPath): void { this.assertPath(sfPath); this.fileData.isComplete = true; } } /** * Drives a `TypeCheckContext` to generate type-checking code efficiently for only those components * which map to a single shim of a single input file. */ class SingleShimTypeCheckingHost extends SingleFileTypeCheckingHost { constructor( sfPath: AbsoluteFsPath, fileData: FileTypeCheckingData, impl: TemplateTypeCheckerImpl, private shimPath: AbsoluteFsPath, ) { super(sfPath, fileData, impl); } shouldCheckNode(node: ts.ClassDeclaration): boolean { if (this.sfPath !== absoluteFromSourceFile(node.getSourceFile())) { return false; } // Only generate a TCB for the component if it maps to the requested shim file. const shimPath = TypeCheckShimGenerator.shimFor(this.sfPath); if (shimPath !== this.shimPath) { return false; } // Only need to generate a TCB for the class if no shim exists for it currently. return !this.fileData.shimData.has(shimPath); } } /** * Cached scope information for a component. */ interface ScopeData { directives: PotentialDirective[]; pipes: PotentialPipe[]; isPoisoned: boolean; }
{ "end_byte": 38422, "start_byte": 34248, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/dom.ts_0_6347
/** * @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.dev/license */ import { DomElementSchemaRegistry, ParseSourceSpan, SchemaMetadata, TmplAstElement, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; import {TemplateDiagnostic, TemplateId} from '../api'; import {makeTemplateDiagnostic} from '../diagnostics'; import {TemplateSourceResolver} from './tcb_util'; const REGISTRY = new DomElementSchemaRegistry(); const REMOVE_XHTML_REGEX = /^:xhtml:/; /** * Checks every non-Angular element/property processed in a template and potentially produces * `ts.Diagnostic`s related to improper usage. * * A `DomSchemaChecker`'s job is to check DOM nodes and their attributes written used in templates * and produce `ts.Diagnostic`s if the nodes don't conform to the DOM specification. It acts as a * collector for these diagnostics, and can be queried later to retrieve the list of any that have * been generated. */ export interface DomSchemaChecker { /** * Get the `ts.Diagnostic`s that have been generated via `checkElement` and `checkProperty` calls * thus far. */ readonly diagnostics: ReadonlyArray<TemplateDiagnostic>; /** * Check a non-Angular element and record any diagnostics about it. * * @param id the template ID, suitable for resolution with a `TcbSourceResolver`. * @param element the element node in question. * @param schemas any active schemas for the template, which might affect the validity of the * element. * @param hostIsStandalone boolean indicating whether the element's host is a standalone * component. */ checkElement( id: string, element: TmplAstElement, schemas: SchemaMetadata[], hostIsStandalone: boolean, ): void; /** * Check a property binding on an element and record any diagnostics about it. * * @param id the template ID, suitable for resolution with a `TcbSourceResolver`. * @param element the element node in question. * @param name the name of the property being checked. * @param span the source span of the binding. This is redundant with `element.attributes` but is * passed separately to avoid having to look up the particular property name. * @param schemas any active schemas for the template, which might affect the validity of the * property. */ checkProperty( id: string, element: TmplAstElement, name: string, span: ParseSourceSpan, schemas: SchemaMetadata[], hostIsStandalone: boolean, ): void; } /** * Checks non-Angular elements and properties against the `DomElementSchemaRegistry`, a schema * maintained by the Angular team via extraction from a browser IDL. */ export class RegistryDomSchemaChecker implements DomSchemaChecker { private _diagnostics: TemplateDiagnostic[] = []; get diagnostics(): ReadonlyArray<TemplateDiagnostic> { return this._diagnostics; } constructor(private resolver: TemplateSourceResolver) {} checkElement( id: TemplateId, element: TmplAstElement, schemas: SchemaMetadata[], hostIsStandalone: boolean, ): void { // HTML elements inside an SVG `foreignObject` are declared in the `xhtml` namespace. // We need to strip it before handing it over to the registry because all HTML tag names // in the registry are without a namespace. const name = element.name.replace(REMOVE_XHTML_REGEX, ''); if (!REGISTRY.hasElement(name, schemas)) { const mapping = this.resolver.getSourceMapping(id); const schemas = `'${hostIsStandalone ? '@Component' : '@NgModule'}.schemas'`; let errorMsg = `'${name}' is not a known element:\n`; errorMsg += `1. If '${name}' is an Angular component, then verify that it is ${ hostIsStandalone ? "included in the '@Component.imports' of this component" : 'part of this module' }.\n`; if (name.indexOf('-') > -1) { errorMsg += `2. If '${name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.`; } else { errorMsg += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`; } const diag = makeTemplateDiagnostic( id, mapping, element.startSourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.SCHEMA_INVALID_ELEMENT), errorMsg, ); this._diagnostics.push(diag); } } checkProperty( id: TemplateId, element: TmplAstElement, name: string, span: ParseSourceSpan, schemas: SchemaMetadata[], hostIsStandalone: boolean, ): void { if (!REGISTRY.hasProperty(element.name, name, schemas)) { const mapping = this.resolver.getSourceMapping(id); const decorator = hostIsStandalone ? '@Component' : '@NgModule'; const schemas = `'${decorator}.schemas'`; let errorMsg = `Can't bind to '${name}' since it isn't a known property of '${element.name}'.`; if (element.name.startsWith('ng-')) { errorMsg += `\n1. If '${name}' is an Angular directive, then add 'CommonModule' to the '${decorator}.imports' of this component.` + `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`; } else if (element.name.indexOf('-') > -1) { errorMsg += `\n1. If '${ element.name }' is an Angular component and it has '${name}' input, then verify that it is ${ hostIsStandalone ? "included in the '@Component.imports' of this component" : 'part of this module' }.` + `\n2. If '${element.name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.` + `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`; } const diag = makeTemplateDiagnostic( id, mapping, span, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.SCHEMA_INVALID_ATTRIBUTE), errorMsg, ); this._diagnostics.push(diag); } } }
{ "end_byte": 6347, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/dom.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/shim.ts_0_1897
/** * @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.dev/license */ import ts from 'typescript'; import {absoluteFrom, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {PerFileShimGenerator, TopLevelShimGenerator} from '../../shims/api'; /** * A `ShimGenerator` which adds type-checking files to the `ts.Program`. * * This is a requirement for performant template type-checking, as TypeScript will only reuse * information in the main program when creating the type-checking program if the set of files in * each are exactly the same. Thus, the main program also needs the synthetic type-checking files. */ export class TypeCheckShimGenerator implements PerFileShimGenerator { readonly extensionPrefix = 'ngtypecheck'; readonly shouldEmit = false; generateShimForFile( sf: ts.SourceFile, genFilePath: AbsoluteFsPath, priorShimSf: ts.SourceFile | null, ): ts.SourceFile { if (priorShimSf !== null) { // If this shim existed in the previous program, reuse it now. It might not be correct, but // reusing it in the main program allows the shape of its imports to potentially remain the // same and TS can then use the fastest path for incremental program creation. Later during // the type-checking phase it's going to either be reused, or replaced anyways. Thus there's // no harm in reuse here even if it's out of date. return priorShimSf; } return ts.createSourceFile( genFilePath, 'export const USED_FOR_NG_TYPE_CHECKING = true;', ts.ScriptTarget.Latest, true, ts.ScriptKind.TS, ); } static shimFor(fileName: AbsoluteFsPath): AbsoluteFsPath { return absoluteFrom(fileName.replace(/\.tsx?$/, '.ngtypecheck.ts')); } }
{ "end_byte": 1897, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/shim.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts_0_6460
/** * @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.dev/license */ import { AbsoluteSourceSpan, BindingPipe, PropertyRead, PropertyWrite, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstElement, TmplAstForLoopBlock, TmplAstForLoopBlockEmpty, TmplAstHoverDeferredTrigger, TmplAstIfBlockBranch, TmplAstInteractionDeferredTrigger, TmplAstLetDeclaration, TmplAstReference, TmplAstSwitchBlockCase, TmplAstTemplate, TmplAstVariable, TmplAstViewportDeferredTrigger, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, makeDiagnostic, makeRelatedInformation, ngErrorCode} from '../../diagnostics'; import {ClassDeclaration} from '../../reflection'; import {TemplateDiagnostic, TemplateId} from '../api'; import {makeTemplateDiagnostic} from '../diagnostics'; import {TemplateSourceResolver} from './tcb_util'; /** * Collects `ts.Diagnostic`s on problems which occur in the template which aren't directly sourced * from Type Check Blocks. * * During the creation of a Type Check Block, the template is traversed and the * `OutOfBandDiagnosticRecorder` is called to record cases when a correct interpretation for the * template cannot be found. These operations create `ts.Diagnostic`s which are stored by the * recorder for later display. */ export interface OutOfBandDiagnosticRecorder { readonly diagnostics: ReadonlyArray<TemplateDiagnostic>; /** * Reports a `#ref="target"` expression in the template for which a target directive could not be * found. * * @param templateId the template type-checking ID of the template which contains the broken * reference. * @param ref the `TmplAstReference` which could not be matched to a directive. */ missingReferenceTarget(templateId: TemplateId, ref: TmplAstReference): void; /** * Reports usage of a `| pipe` expression in the template for which the named pipe could not be * found. * * @param templateId the template type-checking ID of the template which contains the unknown * pipe. * @param ast the `BindingPipe` invocation of the pipe which could not be found. */ missingPipe(templateId: TemplateId, ast: BindingPipe): void; /** * Reports usage of a pipe imported via `@Component.deferredImports` outside * of a `@defer` block in a template. * * @param templateId the template type-checking ID of the template which contains the unknown * pipe. * @param ast the `BindingPipe` invocation of the pipe which could not be found. */ deferredPipeUsedEagerly(templateId: TemplateId, ast: BindingPipe): void; /** * Reports usage of a component/directive imported via `@Component.deferredImports` outside * of a `@defer` block in a template. * * @param templateId the template type-checking ID of the template which contains the unknown * pipe. * @param element the element which hosts a component that was defer-loaded. */ deferredComponentUsedEagerly(templateId: TemplateId, element: TmplAstElement): void; /** * Reports a duplicate declaration of a template variable. * * @param templateId the template type-checking ID of the template which contains the duplicate * declaration. * @param variable the `TmplAstVariable` which duplicates a previously declared variable. * @param firstDecl the first variable declaration which uses the same name as `variable`. */ duplicateTemplateVar( templateId: TemplateId, variable: TmplAstVariable, firstDecl: TmplAstVariable, ): void; requiresInlineTcb(templateId: TemplateId, node: ClassDeclaration): void; requiresInlineTypeConstructors( templateId: TemplateId, node: ClassDeclaration, directives: ClassDeclaration[], ): void; /** * Report a warning when structural directives support context guards, but the current * type-checking configuration prohibits their usage. */ suboptimalTypeInference(templateId: TemplateId, variables: TmplAstVariable[]): void; /** * Reports a split two way binding error message. */ splitTwoWayBinding( templateId: TemplateId, input: TmplAstBoundAttribute, output: TmplAstBoundEvent, inputConsumer: ClassDeclaration, outputConsumer: ClassDeclaration | TmplAstElement, ): void; /** Reports required inputs that haven't been bound. */ missingRequiredInputs( templateId: TemplateId, element: TmplAstElement | TmplAstTemplate, directiveName: string, isComponent: boolean, inputAliases: string[], ): void; /** * Reports accesses of properties that aren't available in a `for` block's tracking expression. */ illegalForLoopTrackAccess( templateId: TemplateId, block: TmplAstForLoopBlock, access: PropertyRead, ): void; /** * Reports deferred triggers that cannot access the element they're referring to. */ inaccessibleDeferredTriggerElement( templateId: TemplateId, trigger: | TmplAstHoverDeferredTrigger | TmplAstInteractionDeferredTrigger | TmplAstViewportDeferredTrigger, ): void; /** * Reports cases where control flow nodes prevent content projection. */ controlFlowPreventingContentProjection( templateId: TemplateId, category: ts.DiagnosticCategory, projectionNode: TmplAstElement | TmplAstTemplate, componentName: string, slotSelector: string, controlFlowNode: | TmplAstIfBlockBranch | TmplAstSwitchBlockCase | TmplAstForLoopBlock | TmplAstForLoopBlockEmpty, preservesWhitespaces: boolean, ): void; /** Reports cases where users are writing to `@let` declarations. */ illegalWriteToLetDeclaration( templateId: TemplateId, node: PropertyWrite, target: TmplAstLetDeclaration, ): void; /** Reports cases where users are accessing an `@let` before it is defined.. */ letUsedBeforeDefinition( templateId: TemplateId, node: PropertyRead, target: TmplAstLetDeclaration, ): void; /** * Reports a `@let` declaration that conflicts with another symbol in the same scope. * * @param templateId the template type-checking ID of the template which contains the declaration. * @param current the `TmplAstLetDeclaration` which is invalid. */ conflictingDeclaration(templateId: TemplateId, current: TmplAstLetDeclaration): void; }
{ "end_byte": 6460, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts_6462_14382
export class OutOfBandDiagnosticRecorderImpl implements OutOfBandDiagnosticRecorder { private _diagnostics: TemplateDiagnostic[] = []; /** * Tracks which `BindingPipe` nodes have already been recorded as invalid, so only one diagnostic * is ever produced per node. */ private recordedPipes = new Set<BindingPipe>(); constructor(private resolver: TemplateSourceResolver) {} get diagnostics(): ReadonlyArray<TemplateDiagnostic> { return this._diagnostics; } missingReferenceTarget(templateId: TemplateId, ref: TmplAstReference): void { const mapping = this.resolver.getSourceMapping(templateId); const value = ref.value.trim(); const errorMsg = `No directive found with exportAs '${value}'.`; this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, ref.valueSpan || ref.sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.MISSING_REFERENCE_TARGET), errorMsg, ), ); } missingPipe(templateId: TemplateId, ast: BindingPipe): void { if (this.recordedPipes.has(ast)) { return; } const mapping = this.resolver.getSourceMapping(templateId); const errorMsg = `No pipe found with name '${ast.name}'.`; const sourceSpan = this.resolver.toParseSourceSpan(templateId, ast.nameSpan); if (sourceSpan === null) { throw new Error( `Assertion failure: no SourceLocation found for usage of pipe '${ast.name}'.`, ); } this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.MISSING_PIPE), errorMsg, ), ); this.recordedPipes.add(ast); } deferredPipeUsedEagerly(templateId: TemplateId, ast: BindingPipe): void { if (this.recordedPipes.has(ast)) { return; } const mapping = this.resolver.getSourceMapping(templateId); const errorMsg = `Pipe '${ast.name}' was imported via \`@Component.deferredImports\`, ` + `but was used outside of a \`@defer\` block in a template. To fix this, either ` + `use the '${ast.name}' pipe inside of a \`@defer\` block or import this dependency ` + `using the \`@Component.imports\` field.`; const sourceSpan = this.resolver.toParseSourceSpan(templateId, ast.nameSpan); if (sourceSpan === null) { throw new Error( `Assertion failure: no SourceLocation found for usage of pipe '${ast.name}'.`, ); } this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.DEFERRED_PIPE_USED_EAGERLY), errorMsg, ), ); this.recordedPipes.add(ast); } deferredComponentUsedEagerly(templateId: TemplateId, element: TmplAstElement): void { const mapping = this.resolver.getSourceMapping(templateId); const errorMsg = `Element '${element.name}' contains a component or a directive that ` + `was imported via \`@Component.deferredImports\`, but the element itself is located ` + `outside of a \`@defer\` block in a template. To fix this, either ` + `use the '${element.name}' element inside of a \`@defer\` block or ` + `import referenced component/directive dependency using the \`@Component.imports\` field.`; const {start, end} = element.startSourceSpan; const absoluteSourceSpan = new AbsoluteSourceSpan(start.offset, end.offset); const sourceSpan = this.resolver.toParseSourceSpan(templateId, absoluteSourceSpan); if (sourceSpan === null) { throw new Error( `Assertion failure: no SourceLocation found for usage of pipe '${element.name}'.`, ); } this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.DEFERRED_DIRECTIVE_USED_EAGERLY), errorMsg, ), ); } duplicateTemplateVar( templateId: TemplateId, variable: TmplAstVariable, firstDecl: TmplAstVariable, ): void { const mapping = this.resolver.getSourceMapping(templateId); const errorMsg = `Cannot redeclare variable '${variable.name}' as it was previously declared elsewhere for the same template.`; // The allocation of the error here is pretty useless for variables declared in microsyntax, // since the sourceSpan refers to the entire microsyntax property, not a span for the specific // variable in question. // // TODO(alxhub): allocate to a tighter span once one is available. this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, variable.sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.DUPLICATE_VARIABLE_DECLARATION), errorMsg, [ { text: `The variable '${firstDecl.name}' was first declared here.`, start: firstDecl.sourceSpan.start.offset, end: firstDecl.sourceSpan.end.offset, sourceFile: mapping.node.getSourceFile(), }, ], ), ); } requiresInlineTcb(templateId: TemplateId, node: ClassDeclaration): void { this._diagnostics.push( makeInlineDiagnostic( templateId, ErrorCode.INLINE_TCB_REQUIRED, node.name, `This component requires inline template type-checking, which is not supported by the current environment.`, ), ); } requiresInlineTypeConstructors( templateId: TemplateId, node: ClassDeclaration, directives: ClassDeclaration[], ): void { let message: string; if (directives.length > 1) { message = `This component uses directives which require inline type constructors, which are not supported by the current environment.`; } else { message = `This component uses a directive which requires an inline type constructor, which is not supported by the current environment.`; } this._diagnostics.push( makeInlineDiagnostic( templateId, ErrorCode.INLINE_TYPE_CTOR_REQUIRED, node.name, message, directives.map((dir) => makeRelatedInformation(dir.name, `Requires an inline type constructor.`), ), ), ); } suboptimalTypeInference(templateId: TemplateId, variables: TmplAstVariable[]): void { const mapping = this.resolver.getSourceMapping(templateId); // Select one of the template variables that's most suitable for reporting the diagnostic. Any // variable will do, but prefer one bound to the context's $implicit if present. let diagnosticVar: TmplAstVariable | null = null; for (const variable of variables) { if (diagnosticVar === null || variable.value === '' || variable.value === '$implicit') { diagnosticVar = variable; } } if (diagnosticVar === null) { // There is no variable on which to report the diagnostic. return; } let varIdentification = `'${diagnosticVar.name}'`; if (variables.length === 2) { varIdentification += ` (and 1 other)`; } else if (variables.length > 2) { varIdentification += ` (and ${variables.length - 1} others)`; } const message = `This structural directive supports advanced type inference, but the current compiler configuration prevents its usage. The variable ${varIdentification} will have type 'any' as a result.\n\nConsider enabling the 'strictTemplates' option in your tsconfig.json for better type inference within this template.`; this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, diagnosticVar.keySpan, ts.DiagnosticCategory.Suggestion, ngErrorCode(ErrorCode.SUGGEST_SUBOPTIMAL_TYPE_INFERENCE), message, ), ); }
{ "end_byte": 14382, "start_byte": 6462, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts_14386_23008
splitTwoWayBinding( templateId: TemplateId, input: TmplAstBoundAttribute, output: TmplAstBoundEvent, inputConsumer: ClassDeclaration, outputConsumer: ClassDeclaration | TmplAstElement, ): void { const mapping = this.resolver.getSourceMapping(templateId); const errorMsg = `The property and event halves of the two-way binding '${input.name}' are not bound to the same target. Find more at https://angular.dev/guide/templates/two-way-binding#how-two-way-binding-works`; const relatedMessages: {text: string; start: number; end: number; sourceFile: ts.SourceFile}[] = []; relatedMessages.push({ text: `The property half of the binding is to the '${inputConsumer.name.text}' component.`, start: inputConsumer.name.getStart(), end: inputConsumer.name.getEnd(), sourceFile: inputConsumer.name.getSourceFile(), }); if (outputConsumer instanceof TmplAstElement) { let message = `The event half of the binding is to a native event called '${input.name}' on the <${outputConsumer.name}> DOM element.`; if (!mapping.node.getSourceFile().isDeclarationFile) { message += `\n \n Are you missing an output declaration called '${output.name}'?`; } relatedMessages.push({ text: message, start: outputConsumer.sourceSpan.start.offset + 1, end: outputConsumer.sourceSpan.start.offset + outputConsumer.name.length + 1, sourceFile: mapping.node.getSourceFile(), }); } else { relatedMessages.push({ text: `The event half of the binding is to the '${outputConsumer.name.text}' component.`, start: outputConsumer.name.getStart(), end: outputConsumer.name.getEnd(), sourceFile: outputConsumer.name.getSourceFile(), }); } this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, input.keySpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.SPLIT_TWO_WAY_BINDING), errorMsg, relatedMessages, ), ); } missingRequiredInputs( templateId: TemplateId, element: TmplAstElement | TmplAstTemplate, directiveName: string, isComponent: boolean, inputAliases: string[], ): void { const message = `Required input${inputAliases.length === 1 ? '' : 's'} ${inputAliases .map((n) => `'${n}'`) .join(', ')} from ${ isComponent ? 'component' : 'directive' } ${directiveName} must be specified.`; this._diagnostics.push( makeTemplateDiagnostic( templateId, this.resolver.getSourceMapping(templateId), element.startSourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.MISSING_REQUIRED_INPUTS), message, ), ); } illegalForLoopTrackAccess( templateId: TemplateId, block: TmplAstForLoopBlock, access: PropertyRead, ): void { const sourceSpan = this.resolver.toParseSourceSpan(templateId, access.sourceSpan); if (sourceSpan === null) { throw new Error(`Assertion failure: no SourceLocation found for property read.`); } const messageVars = [block.item, ...block.contextVariables.filter((v) => v.value === '$index')] .map((v) => `'${v.name}'`) .join(', '); const message = `Cannot access '${access.name}' inside of a track expression. ` + `Only ${messageVars} and properties on the containing component are available to this expression.`; this._diagnostics.push( makeTemplateDiagnostic( templateId, this.resolver.getSourceMapping(templateId), sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.ILLEGAL_FOR_LOOP_TRACK_ACCESS), message, ), ); } inaccessibleDeferredTriggerElement( templateId: TemplateId, trigger: | TmplAstHoverDeferredTrigger | TmplAstInteractionDeferredTrigger | TmplAstViewportDeferredTrigger, ): void { let message: string; if (trigger.reference === null) { message = `Trigger cannot find reference. Make sure that the @defer block has a ` + `@placeholder with at least one root element node.`; } else { message = `Trigger cannot find reference "${trigger.reference}".\nCheck that an element with #${trigger.reference} exists in the same template and it's accessible from the ` + `@defer block.\nDeferred blocks can only access triggers in same view, a parent ` + `embedded view or the root view of the @placeholder block.`; } this._diagnostics.push( makeTemplateDiagnostic( templateId, this.resolver.getSourceMapping(templateId), trigger.sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.INACCESSIBLE_DEFERRED_TRIGGER_ELEMENT), message, ), ); } controlFlowPreventingContentProjection( templateId: TemplateId, category: ts.DiagnosticCategory, projectionNode: TmplAstElement | TmplAstTemplate, componentName: string, slotSelector: string, controlFlowNode: | TmplAstIfBlockBranch | TmplAstSwitchBlockCase | TmplAstForLoopBlock | TmplAstForLoopBlockEmpty, preservesWhitespaces: boolean, ): void { const blockName = controlFlowNode.nameSpan.toString().trim(); const lines = [ `Node matches the "${slotSelector}" slot of the "${componentName}" component, but will not be projected into the specific slot because the surrounding ${blockName} has more than one node at its root. To project the node in the right slot, you can:\n`, `1. Wrap the content of the ${blockName} block in an <ng-container/> that matches the "${slotSelector}" selector.`, `2. Split the content of the ${blockName} block across multiple ${blockName} blocks such that each one only has a single projectable node at its root.`, `3. Remove all content from the ${blockName} block, except for the node being projected.`, ]; if (preservesWhitespaces) { lines.push( 'Note: the host component has `preserveWhitespaces: true` which may ' + 'cause whitespace to affect content projection.', ); } lines.push( '', 'This check can be disabled using the `extendedDiagnostics.checks.' + 'controlFlowPreventingContentProjection = "suppress" compiler option.`', ); this._diagnostics.push( makeTemplateDiagnostic( templateId, this.resolver.getSourceMapping(templateId), projectionNode.startSourceSpan, category, ngErrorCode(ErrorCode.CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION), lines.join('\n'), ), ); } illegalWriteToLetDeclaration( templateId: TemplateId, node: PropertyWrite, target: TmplAstLetDeclaration, ): void { const sourceSpan = this.resolver.toParseSourceSpan(templateId, node.sourceSpan); if (sourceSpan === null) { throw new Error(`Assertion failure: no SourceLocation found for property write.`); } this._diagnostics.push( makeTemplateDiagnostic( templateId, this.resolver.getSourceMapping(templateId), sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.ILLEGAL_LET_WRITE), `Cannot assign to @let declaration '${target.name}'.`, ), ); } letUsedBeforeDefinition( templateId: TemplateId, node: PropertyRead, target: TmplAstLetDeclaration, ): void { const sourceSpan = this.resolver.toParseSourceSpan(templateId, node.sourceSpan); if (sourceSpan === null) { throw new Error(`Assertion failure: no SourceLocation found for property read.`); } this._diagnostics.push( makeTemplateDiagnostic( templateId, this.resolver.getSourceMapping(templateId), sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.LET_USED_BEFORE_DEFINITION), `Cannot read @let declaration '${target.name}' before it has been defined.`, ), ); } conflictingDeclaration(templateId: TemplateId, decl: TmplAstLetDeclaration): void { const mapping = this.resolver.getSourceMapping(templateId); const errorMsg = `Cannot declare @let called '${decl.name}' as there is another symbol in the template with the same name.`; this._diagnostics.push( makeTemplateDiagnostic( templateId, mapping, decl.sourceSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.CONFLICTING_LET_DECLARATION), errorMsg, ), ); } }
{ "end_byte": 23008, "start_byte": 14386, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts_23010_23436
function makeInlineDiagnostic( templateId: TemplateId, code: ErrorCode.INLINE_TCB_REQUIRED | ErrorCode.INLINE_TYPE_CTOR_REQUIRED, node: ts.Node, messageText: string | ts.DiagnosticMessageChain, relatedInformation?: ts.DiagnosticRelatedInformation[], ): TemplateDiagnostic { return { ...makeDiagnostic(code, node, messageText, relatedInformation), componentFile: node.getSourceFile(), templateId, }; }
{ "end_byte": 23436, "start_byte": 23010, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts_0_3070
/** * @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.dev/license */ import { AST, AstVisitor, ASTWithSource, Binary, BindingPipe, Call, Chain, Conditional, EmptyExpr, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, NonNullAssert, PrefixNot, TypeofExpression, PropertyRead, PropertyWrite, SafeCall, SafeKeyedRead, SafePropertyRead, ThisReceiver, Unary, } from '@angular/compiler'; import ts from 'typescript'; import {TypeCheckingConfig} from '../api'; import {addParseSpanInfo, wrapForDiagnostics, wrapForTypeChecker} from './diagnostics'; import {tsCastToAny, tsNumericExpression} from './ts_util'; /** * Expression that is cast to any. Currently represented as `0 as any`. * * Historically this expression was using `null as any`, but a newly-added check in TypeScript 5.6 * (https://devblogs.microsoft.com/typescript/announcing-typescript-5-6-beta/#disallowed-nullish-and-truthy-checks) * started flagging it as always being nullish. Other options that were considered: * - `NaN as any` or `Infinity as any` - not used, because they don't work if the `noLib` compiler * option is enabled. Also they require more characters. * - Some flavor of function call, like `isNan(0) as any` - requires even more characters than the * NaN option and has the same issue with `noLib`. */ export const ANY_EXPRESSION = ts.factory.createAsExpression( ts.factory.createNumericLiteral('0'), ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); const UNDEFINED = ts.factory.createIdentifier('undefined'); const UNARY_OPS = new Map<string, ts.PrefixUnaryOperator>([ ['+', ts.SyntaxKind.PlusToken], ['-', ts.SyntaxKind.MinusToken], ]); const BINARY_OPS = new Map<string, ts.BinaryOperator>([ ['+', ts.SyntaxKind.PlusToken], ['-', ts.SyntaxKind.MinusToken], ['<', ts.SyntaxKind.LessThanToken], ['>', ts.SyntaxKind.GreaterThanToken], ['<=', ts.SyntaxKind.LessThanEqualsToken], ['>=', ts.SyntaxKind.GreaterThanEqualsToken], ['==', ts.SyntaxKind.EqualsEqualsToken], ['===', ts.SyntaxKind.EqualsEqualsEqualsToken], ['*', ts.SyntaxKind.AsteriskToken], ['/', ts.SyntaxKind.SlashToken], ['%', ts.SyntaxKind.PercentToken], ['!=', ts.SyntaxKind.ExclamationEqualsToken], ['!==', ts.SyntaxKind.ExclamationEqualsEqualsToken], ['||', ts.SyntaxKind.BarBarToken], ['&&', ts.SyntaxKind.AmpersandAmpersandToken], ['&', ts.SyntaxKind.AmpersandToken], ['|', ts.SyntaxKind.BarToken], ['??', ts.SyntaxKind.QuestionQuestionToken], ]); /** * Convert an `AST` to TypeScript code directly, without going through an intermediate `Expression` * AST. */ export function astToTypescript( ast: AST, maybeResolve: (ast: AST) => ts.Expression | null, config: TypeCheckingConfig, ): ts.Expression { const translator = new AstTranslator(maybeResolve, config); return translator.translate(ast); }
{ "end_byte": 3070, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts_3072_10885
class AstTranslator implements AstVisitor { constructor( private maybeResolve: (ast: AST) => ts.Expression | null, private config: TypeCheckingConfig, ) {} translate(ast: AST): ts.Expression { // Skip over an `ASTWithSource` as its `visit` method calls directly into its ast's `visit`, // which would prevent any custom resolution through `maybeResolve` for that node. if (ast instanceof ASTWithSource) { ast = ast.ast; } // The `EmptyExpr` doesn't have a dedicated method on `AstVisitor`, so it's special cased here. if (ast instanceof EmptyExpr) { const res = ts.factory.createIdentifier('undefined'); addParseSpanInfo(res, ast.sourceSpan); return res; } // First attempt to let any custom resolution logic provide a translation for the given node. const resolved = this.maybeResolve(ast); if (resolved !== null) { return resolved; } return ast.visit(this); } visitUnary(ast: Unary): ts.Expression { const expr = this.translate(ast.expr); const op = UNARY_OPS.get(ast.operator); if (op === undefined) { throw new Error(`Unsupported Unary.operator: ${ast.operator}`); } const node = wrapForDiagnostics(ts.factory.createPrefixUnaryExpression(op, expr)); addParseSpanInfo(node, ast.sourceSpan); return node; } visitBinary(ast: Binary): ts.Expression { const lhs = wrapForDiagnostics(this.translate(ast.left)); const rhs = wrapForDiagnostics(this.translate(ast.right)); const op = BINARY_OPS.get(ast.operation); if (op === undefined) { throw new Error(`Unsupported Binary.operation: ${ast.operation}`); } const node = ts.factory.createBinaryExpression(lhs, op, rhs); addParseSpanInfo(node, ast.sourceSpan); return node; } visitChain(ast: Chain): ts.Expression { const elements = ast.expressions.map((expr) => this.translate(expr)); const node = wrapForDiagnostics(ts.factory.createCommaListExpression(elements)); addParseSpanInfo(node, ast.sourceSpan); return node; } visitConditional(ast: Conditional): ts.Expression { const condExpr = this.translate(ast.condition); const trueExpr = this.translate(ast.trueExp); // Wrap `falseExpr` in parens so that the trailing parse span info is not attributed to the // whole conditional. // In the following example, the last source span comment (5,6) could be seen as the // trailing comment for _either_ the whole conditional expression _or_ just the `falseExpr` that // is immediately before it: // `conditional /*1,2*/ ? trueExpr /*3,4*/ : falseExpr /*5,6*/` // This should be instead be `conditional /*1,2*/ ? trueExpr /*3,4*/ : (falseExpr /*5,6*/)` const falseExpr = wrapForTypeChecker(this.translate(ast.falseExp)); const node = ts.factory.createParenthesizedExpression( ts.factory.createConditionalExpression(condExpr, undefined, trueExpr, undefined, falseExpr), ); addParseSpanInfo(node, ast.sourceSpan); return node; } visitImplicitReceiver(ast: ImplicitReceiver): never { throw new Error('Method not implemented.'); } visitThisReceiver(ast: ThisReceiver): never { throw new Error('Method not implemented.'); } visitInterpolation(ast: Interpolation): ts.Expression { // Build up a chain of binary + operations to simulate the string concatenation of the // interpolation's expressions. The chain is started using an actual string literal to ensure // the type is inferred as 'string'. return ast.expressions.reduce( (lhs: ts.Expression, ast: AST) => ts.factory.createBinaryExpression( lhs, ts.SyntaxKind.PlusToken, wrapForTypeChecker(this.translate(ast)), ), ts.factory.createStringLiteral(''), ); } visitKeyedRead(ast: KeyedRead): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const key = this.translate(ast.key); const node = ts.factory.createElementAccessExpression(receiver, key); addParseSpanInfo(node, ast.sourceSpan); return node; } visitKeyedWrite(ast: KeyedWrite): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const left = ts.factory.createElementAccessExpression(receiver, this.translate(ast.key)); // TODO(joost): annotate `left` with the span of the element access, which is not currently // available on `ast`. const right = wrapForTypeChecker(this.translate(ast.value)); const node = wrapForDiagnostics( ts.factory.createBinaryExpression(left, ts.SyntaxKind.EqualsToken, right), ); addParseSpanInfo(node, ast.sourceSpan); return node; } visitLiteralArray(ast: LiteralArray): ts.Expression { const elements = ast.expressions.map((expr) => this.translate(expr)); const literal = ts.factory.createArrayLiteralExpression(elements); // If strictLiteralTypes is disabled, array literals are cast to `any`. const node = this.config.strictLiteralTypes ? literal : tsCastToAny(literal); addParseSpanInfo(node, ast.sourceSpan); return node; } visitLiteralMap(ast: LiteralMap): ts.Expression { const properties = ast.keys.map(({key}, idx) => { const value = this.translate(ast.values[idx]); return ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(key), value); }); const literal = ts.factory.createObjectLiteralExpression(properties, true); // If strictLiteralTypes is disabled, object literals are cast to `any`. const node = this.config.strictLiteralTypes ? literal : tsCastToAny(literal); addParseSpanInfo(node, ast.sourceSpan); return node; } visitLiteralPrimitive(ast: LiteralPrimitive): ts.Expression { let node: ts.Expression; if (ast.value === undefined) { node = ts.factory.createIdentifier('undefined'); } else if (ast.value === null) { node = ts.factory.createNull(); } else if (typeof ast.value === 'string') { node = ts.factory.createStringLiteral(ast.value); } else if (typeof ast.value === 'number') { node = tsNumericExpression(ast.value); } else if (typeof ast.value === 'boolean') { node = ast.value ? ts.factory.createTrue() : ts.factory.createFalse(); } else { throw Error(`Unsupported AST value of type ${typeof ast.value}`); } addParseSpanInfo(node, ast.sourceSpan); return node; } visitNonNullAssert(ast: NonNullAssert): ts.Expression { const expr = wrapForDiagnostics(this.translate(ast.expression)); const node = ts.factory.createNonNullExpression(expr); addParseSpanInfo(node, ast.sourceSpan); return node; } visitPipe(ast: BindingPipe): never { throw new Error('Method not implemented.'); } visitPrefixNot(ast: PrefixNot): ts.Expression { const expression = wrapForDiagnostics(this.translate(ast.expression)); const node = ts.factory.createLogicalNot(expression); addParseSpanInfo(node, ast.sourceSpan); return node; } visitTypeofExpresion(ast: TypeofExpression): ts.Expression { const expression = wrapForDiagnostics(this.translate(ast.expression)); const node = ts.factory.createTypeOfExpression(expression); addParseSpanInfo(node, ast.sourceSpan); return node; } visitPropertyRead(ast: PropertyRead): ts.Expression { // This is a normal property read - convert the receiver to an expression and emit the correct // TypeScript expression to read the property. const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const name = ts.factory.createPropertyAccessExpression(receiver, ast.name); addParseSpanInfo(name, ast.nameSpan); const node = wrapForDiagnostics(name); addParseSpanInfo(node, ast.sourceSpan); return node; }
{ "end_byte": 10885, "start_byte": 3072, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts_10889_19082
visitPropertyWrite(ast: PropertyWrite): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const left = ts.factory.createPropertyAccessExpression(receiver, ast.name); addParseSpanInfo(left, ast.nameSpan); // TypeScript reports assignment errors on the entire lvalue expression. Annotate the lvalue of // the assignment with the sourceSpan, which includes receivers, rather than nameSpan for // consistency of the diagnostic location. // a.b.c = 1 // ^^^^^^^^^ sourceSpan // ^ nameSpan const leftWithPath = wrapForDiagnostics(left); addParseSpanInfo(leftWithPath, ast.sourceSpan); // The right needs to be wrapped in parens as well or we cannot accurately match its // span to just the RHS. For example, the span in `e = $event /*0,10*/` is ambiguous. // It could refer to either the whole binary expression or just the RHS. // We should instead generate `e = ($event /*0,10*/)` so we know the span 0,10 matches RHS. const right = wrapForTypeChecker(this.translate(ast.value)); const node = wrapForDiagnostics( ts.factory.createBinaryExpression(leftWithPath, ts.SyntaxKind.EqualsToken, right), ); addParseSpanInfo(node, ast.sourceSpan); return node; } visitSafePropertyRead(ast: SafePropertyRead): ts.Expression { let node: ts.Expression; const receiver = wrapForDiagnostics(this.translate(ast.receiver)); // The form of safe property reads depends on whether strictness is in use. if (this.config.strictSafeNavigationTypes) { // Basically, the return here is either the type of the complete expression with a null-safe // property read, or `undefined`. So a ternary is used to create an "or" type: // "a?.b" becomes (0 as any ? a!.b : undefined) // The type of this expression is (typeof a!.b) | undefined, which is exactly as desired. const expr = ts.factory.createPropertyAccessExpression( ts.factory.createNonNullExpression(receiver), ast.name, ); addParseSpanInfo(expr, ast.nameSpan); node = ts.factory.createParenthesizedExpression( ts.factory.createConditionalExpression( ANY_EXPRESSION, undefined, expr, undefined, UNDEFINED, ), ); } else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) { // Emulate a View Engine bug where 'any' is inferred for the left-hand side of the safe // navigation operation. With this bug, the type of the left-hand side is regarded as any. // Therefore, the left-hand side only needs repeating in the output (to validate it), and then // 'any' is used for the rest of the expression. This is done using a comma operator: // "a?.b" becomes (a as any).b, which will of course have type 'any'. node = ts.factory.createPropertyAccessExpression(tsCastToAny(receiver), ast.name); } else { // The View Engine bug isn't active, so check the entire type of the expression, but the final // result is still inferred as `any`. // "a?.b" becomes (a!.b as any) const expr = ts.factory.createPropertyAccessExpression( ts.factory.createNonNullExpression(receiver), ast.name, ); addParseSpanInfo(expr, ast.nameSpan); node = tsCastToAny(expr); } addParseSpanInfo(node, ast.sourceSpan); return node; } visitSafeKeyedRead(ast: SafeKeyedRead): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const key = this.translate(ast.key); let node: ts.Expression; // The form of safe property reads depends on whether strictness is in use. if (this.config.strictSafeNavigationTypes) { // "a?.[...]" becomes (0 as any ? a![...] : undefined) const expr = ts.factory.createElementAccessExpression( ts.factory.createNonNullExpression(receiver), key, ); addParseSpanInfo(expr, ast.sourceSpan); node = ts.factory.createParenthesizedExpression( ts.factory.createConditionalExpression( ANY_EXPRESSION, undefined, expr, undefined, UNDEFINED, ), ); } else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) { // "a?.[...]" becomes (a as any)[...] node = ts.factory.createElementAccessExpression(tsCastToAny(receiver), key); } else { // "a?.[...]" becomes (a!.[...] as any) const expr = ts.factory.createElementAccessExpression( ts.factory.createNonNullExpression(receiver), key, ); addParseSpanInfo(expr, ast.sourceSpan); node = tsCastToAny(expr); } addParseSpanInfo(node, ast.sourceSpan); return node; } visitCall(ast: Call): ts.Expression { const args = ast.args.map((expr) => this.translate(expr)); let expr: ts.Expression; const receiver = ast.receiver; // For calls that have a property read as receiver, we have to special-case their emit to avoid // inserting superfluous parenthesis as they prevent TypeScript from applying a narrowing effect // if the method acts as a type guard. if (receiver instanceof PropertyRead) { const resolved = this.maybeResolve(receiver); if (resolved !== null) { expr = resolved; } else { const propertyReceiver = wrapForDiagnostics(this.translate(receiver.receiver)); expr = ts.factory.createPropertyAccessExpression(propertyReceiver, receiver.name); addParseSpanInfo(expr, receiver.nameSpan); } } else { expr = this.translate(receiver); } let node: ts.Expression; // Safe property/keyed reads will produce a ternary whose value is nullable. // We have to generate a similar ternary around the call. if (ast.receiver instanceof SafePropertyRead || ast.receiver instanceof SafeKeyedRead) { node = this.convertToSafeCall(ast, expr, args); } else { node = ts.factory.createCallExpression(expr, undefined, args); } addParseSpanInfo(node, ast.sourceSpan); return node; } visitSafeCall(ast: SafeCall): ts.Expression { const args = ast.args.map((expr) => this.translate(expr)); const expr = wrapForDiagnostics(this.translate(ast.receiver)); const node = this.convertToSafeCall(ast, expr, args); addParseSpanInfo(node, ast.sourceSpan); return node; } private convertToSafeCall( ast: Call | SafeCall, expr: ts.Expression, args: ts.Expression[], ): ts.Expression { if (this.config.strictSafeNavigationTypes) { // "a?.method(...)" becomes (0 as any ? a!.method(...) : undefined) const call = ts.factory.createCallExpression( ts.factory.createNonNullExpression(expr), undefined, args, ); return ts.factory.createParenthesizedExpression( ts.factory.createConditionalExpression( ANY_EXPRESSION, undefined, call, undefined, UNDEFINED, ), ); } if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) { // "a?.method(...)" becomes (a as any).method(...) return ts.factory.createCallExpression(tsCastToAny(expr), undefined, args); } // "a?.method(...)" becomes (a!.method(...) as any) return tsCastToAny( ts.factory.createCallExpression(ts.factory.createNonNullExpression(expr), undefined, args), ); } } /** * Checks whether View Engine will infer a type of 'any' for the left-hand side of a safe navigation * operation. * * In View Engine's template type-checker, certain receivers of safe navigation operations will * cause a temporary variable to be allocated as part of the checking expression, to save the value * of the receiver and use it more than once in the expression. This temporary variable has type * 'any'. In practice, this means certain receivers cause View Engine to not check the full * expression, and other receivers will receive more complete checking. * * For compatibility, this logic is adapted from View Engine's expression_converter.ts so that the * Ivy checker can emulate this bug when needed. */
{ "end_byte": 19082, "start_byte": 10889, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts_19083_21193
class VeSafeLhsInferenceBugDetector implements AstVisitor { private static SINGLETON = new VeSafeLhsInferenceBugDetector(); static veWillInferAnyFor(ast: Call | SafeCall | SafePropertyRead | SafeKeyedRead) { const visitor = VeSafeLhsInferenceBugDetector.SINGLETON; return ast instanceof Call ? ast.visit(visitor) : ast.receiver.visit(visitor); } visitUnary(ast: Unary): boolean { return ast.expr.visit(this); } visitBinary(ast: Binary): boolean { return ast.left.visit(this) || ast.right.visit(this); } visitChain(ast: Chain): boolean { return false; } visitConditional(ast: Conditional): boolean { return ast.condition.visit(this) || ast.trueExp.visit(this) || ast.falseExp.visit(this); } visitCall(ast: Call): boolean { return true; } visitSafeCall(ast: SafeCall): boolean { return false; } visitImplicitReceiver(ast: ImplicitReceiver): boolean { return false; } visitThisReceiver(ast: ThisReceiver): boolean { return false; } visitInterpolation(ast: Interpolation): boolean { return ast.expressions.some((exp) => exp.visit(this)); } visitKeyedRead(ast: KeyedRead): boolean { return false; } visitKeyedWrite(ast: KeyedWrite): boolean { return false; } visitLiteralArray(ast: LiteralArray): boolean { return true; } visitLiteralMap(ast: LiteralMap): boolean { return true; } visitLiteralPrimitive(ast: LiteralPrimitive): boolean { return false; } visitPipe(ast: BindingPipe): boolean { return true; } visitPrefixNot(ast: PrefixNot): boolean { return ast.expression.visit(this); } visitTypeofExpresion(ast: PrefixNot): boolean { return ast.expression.visit(this); } visitNonNullAssert(ast: PrefixNot): boolean { return ast.expression.visit(this); } visitPropertyRead(ast: PropertyRead): boolean { return false; } visitPropertyWrite(ast: PropertyWrite): boolean { return false; } visitSafePropertyRead(ast: SafePropertyRead): boolean { return false; } visitSafeKeyedRead(ast: SafeKeyedRead): boolean { return false; } }
{ "end_byte": 21193, "start_byte": 19083, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.ts_0_4562
/** * @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.dev/license */ import ts from 'typescript'; import {OwningModule, Reference} from '../../imports'; import {AmbientImport, DeclarationNode, ReflectionHost} from '../../reflection'; import {canEmitType, TypeEmitter} from '../../translator'; /** * See `TypeEmitter` for more information on the emitting process. */ export class TypeParameterEmitter { constructor( private typeParameters: ts.NodeArray<ts.TypeParameterDeclaration> | undefined, private reflector: ReflectionHost, ) {} /** * Determines whether the type parameters can be emitted. If this returns true, then a call to * `emit` is known to succeed. Vice versa, if false is returned then `emit` should not be * called, as it would fail. */ canEmit(canEmitReference: (ref: Reference) => boolean): boolean { if (this.typeParameters === undefined) { return true; } return this.typeParameters.every((typeParam) => { return ( this.canEmitType(typeParam.constraint, canEmitReference) && this.canEmitType(typeParam.default, canEmitReference) ); }); } private canEmitType( type: ts.TypeNode | undefined, canEmitReference: (ref: Reference) => boolean, ): boolean { if (type === undefined) { return true; } return canEmitType(type, (typeReference) => { const reference = this.resolveTypeReference(typeReference); if (reference === null) { return false; } if (reference instanceof Reference) { return canEmitReference(reference); } return true; }); } /** * Emits the type parameters using the provided emitter function for `Reference`s. */ emit(emitReference: (ref: Reference) => ts.TypeNode): ts.TypeParameterDeclaration[] | undefined { if (this.typeParameters === undefined) { return undefined; } const emitter = new TypeEmitter((type) => this.translateTypeReference(type, emitReference)); return this.typeParameters.map((typeParam) => { const constraint = typeParam.constraint !== undefined ? emitter.emitType(typeParam.constraint) : undefined; const defaultType = typeParam.default !== undefined ? emitter.emitType(typeParam.default) : undefined; return ts.factory.updateTypeParameterDeclaration( typeParam, typeParam.modifiers, typeParam.name, constraint, defaultType, ); }); } private resolveTypeReference( type: ts.TypeReferenceNode, ): Reference | ts.TypeReferenceNode | null { const target = ts.isIdentifier(type.typeName) ? type.typeName : type.typeName.right; const declaration = this.reflector.getDeclarationOfIdentifier(target); // If no declaration could be resolved or does not have a `ts.Declaration`, the type cannot be // resolved. if (declaration === null || declaration.node === null) { return null; } // If the declaration corresponds with a local type parameter, the type reference can be used // as is. if (this.isLocalTypeParameter(declaration.node)) { return type; } let owningModule: OwningModule | null = null; if (typeof declaration.viaModule === 'string') { owningModule = { specifier: declaration.viaModule, resolutionContext: type.getSourceFile().fileName, }; } return new Reference( declaration.node, declaration.viaModule === AmbientImport ? AmbientImport : owningModule, ); } private translateTypeReference( type: ts.TypeReferenceNode, emitReference: (ref: Reference) => ts.TypeNode | null, ): ts.TypeReferenceNode | null { const reference = this.resolveTypeReference(type); if (!(reference instanceof Reference)) { return reference; } const typeNode = emitReference(reference); if (typeNode === null) { return null; } if (!ts.isTypeReferenceNode(typeNode)) { throw new Error( `Expected TypeReferenceNode for emitted reference, got ${ts.SyntaxKind[typeNode.kind]}.`, ); } return typeNode; } private isLocalTypeParameter(decl: DeclarationNode): boolean { // Checking for local type parameters only occurs during resolution of type parameters, so it is // guaranteed that type parameters are present. return this.typeParameters!.some((param) => param === decl); } }
{ "end_byte": 4562, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/source.ts_0_3082
/** * @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.dev/license */ import { AbsoluteSourceSpan, ParseLocation, ParseSourceFile, ParseSourceSpan, } from '@angular/compiler'; import ts from 'typescript'; import {TemplateId, TemplateSourceMapping} from '../api'; import {getTemplateId} from '../diagnostics'; import {computeLineStartsMap, getLineAndCharacterFromPosition} from './line_mappings'; import {TemplateSourceResolver} from './tcb_util'; /** * Represents the source of a template that was processed during type-checking. This information is * used when translating parse offsets in diagnostics back to their original line/column location. */ export class TemplateSource { private lineStarts: number[] | null = null; constructor( readonly mapping: TemplateSourceMapping, private file: ParseSourceFile, ) {} toParseSourceSpan(start: number, end: number): ParseSourceSpan { const startLoc = this.toParseLocation(start); const endLoc = this.toParseLocation(end); return new ParseSourceSpan(startLoc, endLoc); } private toParseLocation(position: number) { const lineStarts = this.acquireLineStarts(); const {line, character} = getLineAndCharacterFromPosition(lineStarts, position); return new ParseLocation(this.file, position, line, character); } private acquireLineStarts(): number[] { if (this.lineStarts === null) { this.lineStarts = computeLineStartsMap(this.file.content); } return this.lineStarts; } } /** * Assigns IDs to templates and keeps track of their origins. * * Implements `TemplateSourceResolver` to resolve the source of a template based on these IDs. */ export class TemplateSourceManager implements TemplateSourceResolver { /** * This map keeps track of all template sources that have been type-checked by the id that is * attached to a TCB's function declaration as leading trivia. This enables translation of * diagnostics produced for TCB code to their source location in the template. */ private templateSources = new Map<TemplateId, TemplateSource>(); getTemplateId(node: ts.ClassDeclaration): TemplateId { return getTemplateId(node); } captureSource( node: ts.ClassDeclaration, mapping: TemplateSourceMapping, file: ParseSourceFile, ): TemplateId { const id = getTemplateId(node); this.templateSources.set(id, new TemplateSource(mapping, file)); return id; } getSourceMapping(id: TemplateId): TemplateSourceMapping { if (!this.templateSources.has(id)) { throw new Error(`Unexpected unknown template ID: ${id}`); } return this.templateSources.get(id)!.mapping; } toParseSourceSpan(id: TemplateId, span: AbsoluteSourceSpan): ParseSourceSpan | null { if (!this.templateSources.has(id)) { return null; } const templateSource = this.templateSources.get(id)!; return templateSource.toParseSourceSpan(span.start, span.end); } }
{ "end_byte": 3082, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/source.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.ts_0_8710
/** * @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.dev/license */ import {AbsoluteSourceSpan, ParseSourceSpan, R3Identifiers} from '@angular/compiler'; import ts from 'typescript'; import {ClassDeclaration, ReflectionHost} from '../../../../src/ngtsc/reflection'; import {Reference} from '../../imports'; import {getTokenAtPosition} from '../../util/src/typescript'; import {FullTemplateMapping, SourceLocation, TemplateId, TemplateSourceMapping} from '../api'; import {hasIgnoreForDiagnosticsMarker, readSpanComment} from './comments'; import {ReferenceEmitEnvironment} from './reference_emit_environment'; import {TypeParameterEmitter} from './type_parameter_emitter'; /** * External modules/identifiers that always should exist for type check * block files. * * Importing the modules in preparation helps ensuring a stable import graph * that would not degrade TypeScript's incremental program structure re-use. * * Note: For inline type check blocks, or type constructors, we cannot add preparation * imports, but ideally the required modules are already imported and can be re-used * to not incur a structural TypeScript program re-use discarding. */ const TCB_FILE_IMPORT_GRAPH_PREPARE_IDENTIFIERS = [ // Imports may be added for signal input checking. We wouldn't want to change the // import graph for incremental compilations when suddenly a signal input is used, // or removed. R3Identifiers.InputSignalBrandWriteType, ]; /** * Adapter interface which allows the template type-checking diagnostics code to interpret offsets * in a TCB and map them back to original locations in the template. */ export interface TemplateSourceResolver { getTemplateId(node: ts.ClassDeclaration): TemplateId; /** * For the given template id, retrieve the original source mapping which describes how the offsets * in the template should be interpreted. */ getSourceMapping(id: TemplateId): TemplateSourceMapping; /** * Convert an absolute source span associated with the given template id into a full * `ParseSourceSpan`. The returned parse span has line and column numbers in addition to only * absolute offsets and gives access to the original template source. */ toParseSourceSpan(id: TemplateId, span: AbsoluteSourceSpan): ParseSourceSpan | null; } /** * Indicates whether a particular component requires an inline type check block. * * This is not a boolean state as inlining might only be required to get the best possible * type-checking, but the component could theoretically still be checked without it. */ export enum TcbInliningRequirement { /** * There is no way to type check this component without inlining. */ MustInline, /** * Inlining should be used due to the component's generic bounds, but a non-inlining fallback * method can be used if that's not possible. */ ShouldInlineForGenericBounds, /** * There is no requirement for this component's TCB to be inlined. */ None, } export function requiresInlineTypeCheckBlock( ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, env: ReferenceEmitEnvironment, usedPipes: Reference<ClassDeclaration<ts.ClassDeclaration>>[], reflector: ReflectionHost, ): TcbInliningRequirement { // In order to qualify for a declared TCB (not inline) two conditions must be met: // 1) the class must be suitable to be referenced from `env` (e.g. it must be exported) // 2) it must not have contextual generic type bounds if (!env.canReferenceType(ref)) { // Condition 1 is false, the class is not exported. return TcbInliningRequirement.MustInline; } else if (!checkIfGenericTypeBoundsCanBeEmitted(ref.node, reflector, env)) { // Condition 2 is false, the class has constrained generic types. It should be checked with an // inline TCB if possible, but can potentially use fallbacks to avoid inlining if not. return TcbInliningRequirement.ShouldInlineForGenericBounds; } else if (usedPipes.some((pipeRef) => !env.canReferenceType(pipeRef))) { // If one of the pipes used by the component is not exported, a non-inline TCB will not be able // to import it, so this requires an inline TCB. return TcbInliningRequirement.MustInline; } else { return TcbInliningRequirement.None; } } /** Maps a shim position back to a template location. */ export function getTemplateMapping( shimSf: ts.SourceFile, position: number, resolver: TemplateSourceResolver, isDiagnosticRequest: boolean, ): FullTemplateMapping | null { const node = getTokenAtPosition(shimSf, position); const sourceLocation = findSourceLocation(node, shimSf, isDiagnosticRequest); if (sourceLocation === null) { return null; } const mapping = resolver.getSourceMapping(sourceLocation.id); const span = resolver.toParseSourceSpan(sourceLocation.id, sourceLocation.span); if (span === null) { return null; } // TODO(atscott): Consider adding a context span by walking up from `node` until we get a // different span. return {sourceLocation, templateSourceMapping: mapping, span}; } export function findTypeCheckBlock( file: ts.SourceFile, id: TemplateId, isDiagnosticRequest: boolean, ): ts.Node | null { for (const stmt of file.statements) { if (ts.isFunctionDeclaration(stmt) && getTemplateId(stmt, file, isDiagnosticRequest) === id) { return stmt; } } return null; } /** * Traverses up the AST starting from the given node to extract the source location from comments * that have been emitted into the TCB. If the node does not exist within a TCB, or if an ignore * marker comment is found up the tree (and this is part of a diagnostic request), this function * returns null. */ export function findSourceLocation( node: ts.Node, sourceFile: ts.SourceFile, isDiagnosticsRequest: boolean, ): SourceLocation | null { // Search for comments until the TCB's function declaration is encountered. while (node !== undefined && !ts.isFunctionDeclaration(node)) { if (hasIgnoreForDiagnosticsMarker(node, sourceFile) && isDiagnosticsRequest) { // There's an ignore marker on this node, so the diagnostic should not be reported. return null; } const span = readSpanComment(node, sourceFile); if (span !== null) { // Once the positional information has been extracted, search further up the TCB to extract // the unique id that is attached with the TCB's function declaration. const id = getTemplateId(node, sourceFile, isDiagnosticsRequest); if (id === null) { return null; } return {id, span}; } node = node.parent; } return null; } function getTemplateId( node: ts.Node, sourceFile: ts.SourceFile, isDiagnosticRequest: boolean, ): TemplateId | null { // Walk up to the function declaration of the TCB, the file information is attached there. while (!ts.isFunctionDeclaration(node)) { if (hasIgnoreForDiagnosticsMarker(node, sourceFile) && isDiagnosticRequest) { // There's an ignore marker on this node, so the diagnostic should not be reported. return null; } node = node.parent; // Bail once we have reached the root. if (node === undefined) { return null; } } const start = node.getFullStart(); return ( (ts.forEachLeadingCommentRange(sourceFile.text, start, (pos, end, kind) => { if (kind !== ts.SyntaxKind.MultiLineCommentTrivia) { return null; } const commentText = sourceFile.text.substring(pos + 2, end - 2); return commentText; }) as TemplateId) || null ); } /** * Ensure imports for certain external modules that should always * exist are generated. These are ensured to exist to avoid frequent * import graph changes whenever e.g. a signal input is introduced in user code. */ export function ensureTypeCheckFilePreparationImports(env: ReferenceEmitEnvironment): void { for (const identifier of TCB_FILE_IMPORT_GRAPH_PREPARE_IDENTIFIERS) { env.importManager.addImport({ exportModuleSpecifier: identifier.moduleName, exportSymbolName: identifier.name, requestedFile: env.contextFile, }); } } export function checkIfGenericTypeBoundsCanBeEmitted( node: ClassDeclaration<ts.ClassDeclaration>, reflector: ReflectionHost, env: ReferenceEmitEnvironment, ): boolean { // Generic type parameters are considered context free if they can be emitted into any context. const emitter = new TypeParameterEmitter(node.typeParameters, reflector); return emitter.canEmit((ref) => env.canReferenceType(ref)); }
{ "end_byte": 8710, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/reference_emit_environment.ts_0_3666
/** * @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.dev/license */ import { ExpressionType, ExternalExpr, TransplantedType, Type, TypeModifier, } from '@angular/compiler'; import ts from 'typescript'; import { assertSuccessfulReferenceEmit, ImportFlags, Reference, ReferenceEmitKind, ReferenceEmitter, } from '../../imports'; import {ReflectionHost} from '../../reflection'; import {ImportManager, translateExpression, translateType} from '../../translator'; /** * An environment for a given source file that can be used to emit references. * * This can be used by the type-checking block, or constructor logic to generate * references to directives or other symbols or types. */ export class ReferenceEmitEnvironment { constructor( readonly importManager: ImportManager, protected refEmitter: ReferenceEmitter, readonly reflector: ReflectionHost, public contextFile: ts.SourceFile, ) {} canReferenceType( ref: Reference, flags: ImportFlags = ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowRelativeDtsImports, ): boolean { const result = this.refEmitter.emit(ref, this.contextFile, flags); return result.kind === ReferenceEmitKind.Success; } /** * Generate a `ts.TypeNode` that references the given node as a type. * * This may involve importing the node into the file if it's not declared there already. */ referenceType( ref: Reference, flags: ImportFlags = ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowRelativeDtsImports, ): ts.TypeNode { const ngExpr = this.refEmitter.emit(ref, this.contextFile, flags); assertSuccessfulReferenceEmit(ngExpr, this.contextFile, 'symbol'); // Create an `ExpressionType` from the `Expression` and translate it via `translateType`. // TODO(alxhub): support references to types with generic arguments in a clean way. return translateType( new ExpressionType(ngExpr.expression), this.contextFile, this.reflector, this.refEmitter, this.importManager, ); } /** * Generate a `ts.Expression` that refers to the external symbol. This * may result in new imports being generated. */ referenceExternalSymbol(moduleName: string, name: string): ts.Expression { const external = new ExternalExpr({moduleName, name}); return translateExpression(this.contextFile, external, this.importManager); } /** * Generate a `ts.TypeNode` that references a given type from the provided module. * * This will involve importing the type into the file, and will also add type parameters if * provided. */ referenceExternalType(moduleName: string, name: string, typeParams?: Type[]): ts.TypeNode { const external = new ExternalExpr({moduleName, name}); return translateType( new ExpressionType(external, TypeModifier.None, typeParams), this.contextFile, this.reflector, this.refEmitter, this.importManager, ); } /** * Generates a `ts.TypeNode` representing a type that is being referenced from a different place * in the program. Any type references inside the transplanted type will be rewritten so that * they can be imported in the context file. */ referenceTransplantedType(type: TransplantedType<Reference<ts.TypeNode>>): ts.TypeNode { return translateType( type, this.contextFile, this.reflector, this.refEmitter, this.importManager, ); } }
{ "end_byte": 3666, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/reference_emit_environment.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts_0_1787
/** * @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.dev/license */ import { AST, ASTWithName, ASTWithSource, BindingPipe, ParseSourceSpan, PropertyRead, PropertyWrite, R3Identifiers, SafePropertyRead, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstElement, TmplAstLetDeclaration, TmplAstNode, TmplAstReference, TmplAstTemplate, TmplAstTextAttribute, TmplAstVariable, } from '@angular/compiler'; import ts from 'typescript'; import {AbsoluteFsPath} from '../../file_system'; import {Reference} from '../../imports'; import {HostDirectiveMeta, isHostDirectiveMetaForGlobalMode} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {ComponentScopeKind, ComponentScopeReader} from '../../scope'; import {isAssignment, isSymbolWithValueDeclaration} from '../../util/src/typescript'; import { BindingSymbol, DirectiveSymbol, DomBindingSymbol, ElementSymbol, ExpressionSymbol, InputBindingSymbol, LetDeclarationSymbol, OutputBindingSymbol, PipeSymbol, ReferenceSymbol, Symbol, SymbolKind, TcbLocation, TemplateSymbol, TsNodeSymbolInfo, TypeCheckableDirectiveMeta, VariableSymbol, } from '../api'; import { ExpressionIdentifier, findAllMatchingNodes, findFirstMatchingNode, hasExpressionIdentifier, } from './comments'; import {TemplateData} from './context'; import {isAccessExpression} from './ts_util'; /** * Generates and caches `Symbol`s for various template structures for a given component. * * The `SymbolBuilder` internally caches the `Symbol`s it creates, and must be destroyed and * replaced if the component's template changes. */
{ "end_byte": 1787, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts_1788_10195
export class SymbolBuilder { private symbolCache = new Map<AST | TmplAstNode, Symbol | null>(); constructor( private readonly tcbPath: AbsoluteFsPath, private readonly tcbIsShim: boolean, private readonly typeCheckBlock: ts.Node, private readonly templateData: TemplateData, private readonly componentScopeReader: ComponentScopeReader, // The `ts.TypeChecker` depends on the current type-checking program, and so must be requested // on-demand instead of cached. private readonly getTypeChecker: () => ts.TypeChecker, ) {} getSymbol(node: TmplAstTemplate | TmplAstElement): TemplateSymbol | ElementSymbol | null; getSymbol( node: TmplAstReference | TmplAstVariable | TmplAstLetDeclaration, ): ReferenceSymbol | VariableSymbol | LetDeclarationSymbol | null; getSymbol(node: AST | TmplAstNode): Symbol | null; getSymbol(node: AST | TmplAstNode): Symbol | null { if (this.symbolCache.has(node)) { return this.symbolCache.get(node)!; } let symbol: Symbol | null = null; if (node instanceof TmplAstBoundAttribute || node instanceof TmplAstTextAttribute) { // TODO(atscott): input and output bindings only return the first directive match but should // return a list of bindings for all of them. symbol = this.getSymbolOfInputBinding(node); } else if (node instanceof TmplAstBoundEvent) { symbol = this.getSymbolOfBoundEvent(node); } else if (node instanceof TmplAstElement) { symbol = this.getSymbolOfElement(node); } else if (node instanceof TmplAstTemplate) { symbol = this.getSymbolOfAstTemplate(node); } else if (node instanceof TmplAstVariable) { symbol = this.getSymbolOfVariable(node); } else if (node instanceof TmplAstLetDeclaration) { symbol = this.getSymbolOfLetDeclaration(node); } else if (node instanceof TmplAstReference) { symbol = this.getSymbolOfReference(node); } else if (node instanceof BindingPipe) { symbol = this.getSymbolOfPipe(node); } else if (node instanceof AST) { symbol = this.getSymbolOfTemplateExpression(node); } else { // TODO(atscott): TmplAstContent, TmplAstIcu } this.symbolCache.set(node, symbol); return symbol; } private getSymbolOfAstTemplate(template: TmplAstTemplate): TemplateSymbol | null { const directives = this.getDirectivesOfNode(template); return {kind: SymbolKind.Template, directives, templateNode: template}; } private getSymbolOfElement(element: TmplAstElement): ElementSymbol | null { const elementSourceSpan = element.startSourceSpan ?? element.sourceSpan; const node = findFirstMatchingNode(this.typeCheckBlock, { withSpan: elementSourceSpan, filter: ts.isVariableDeclaration, }); if (node === null) { return null; } const symbolFromDeclaration = this.getSymbolOfTsNode(node); if (symbolFromDeclaration === null || symbolFromDeclaration.tsSymbol === null) { return null; } const directives = this.getDirectivesOfNode(element); // All statements in the TCB are `Expression`s that optionally include more information. // An `ElementSymbol` uses the information returned for the variable declaration expression, // adds the directives for the element, and updates the `kind` to be `SymbolKind.Element`. return { ...symbolFromDeclaration, kind: SymbolKind.Element, directives, templateNode: element, }; } private getDirectivesOfNode(element: TmplAstElement | TmplAstTemplate): DirectiveSymbol[] { const elementSourceSpan = element.startSourceSpan ?? element.sourceSpan; const tcbSourceFile = this.typeCheckBlock.getSourceFile(); // directives could be either: // - var _t1: TestDir /*T:D*/ = null! as TestDir; // - var _t1 /*T:D*/ = _ctor1({}); const isDirectiveDeclaration = (node: ts.Node): node is ts.TypeNode | ts.Identifier => (ts.isTypeNode(node) || ts.isIdentifier(node)) && ts.isVariableDeclaration(node.parent) && hasExpressionIdentifier(tcbSourceFile, node, ExpressionIdentifier.DIRECTIVE); const nodes = findAllMatchingNodes(this.typeCheckBlock, { withSpan: elementSourceSpan, filter: isDirectiveDeclaration, }); const symbols: DirectiveSymbol[] = []; for (const node of nodes) { const symbol = this.getSymbolOfTsNode(node.parent); if ( symbol === null || !isSymbolWithValueDeclaration(symbol.tsSymbol) || !ts.isClassDeclaration(symbol.tsSymbol.valueDeclaration) ) { continue; } const meta = this.getDirectiveMeta(element, symbol.tsSymbol.valueDeclaration); if (meta !== null && meta.selector !== null) { const ref = new Reference<ClassDeclaration>(symbol.tsSymbol.valueDeclaration as any); if (meta.hostDirectives !== null) { this.addHostDirectiveSymbols(element, meta.hostDirectives, symbols); } const directiveSymbol: DirectiveSymbol = { ...symbol, ref, tsSymbol: symbol.tsSymbol, selector: meta.selector, isComponent: meta.isComponent, ngModule: this.getDirectiveModule(symbol.tsSymbol.valueDeclaration), kind: SymbolKind.Directive, isStructural: meta.isStructural, isInScope: true, isHostDirective: false, }; symbols.push(directiveSymbol); } } return symbols; } private addHostDirectiveSymbols( host: TmplAstTemplate | TmplAstElement, hostDirectives: HostDirectiveMeta[], symbols: DirectiveSymbol[], ): void { for (const current of hostDirectives) { if (!isHostDirectiveMetaForGlobalMode(current)) { throw new Error('Impossible state: typecheck code path in local compilation mode.'); } if (!ts.isClassDeclaration(current.directive.node)) { continue; } const symbol = this.getSymbolOfTsNode(current.directive.node); const meta = this.getDirectiveMeta(host, current.directive.node); if (meta !== null && symbol !== null && isSymbolWithValueDeclaration(symbol.tsSymbol)) { if (meta.hostDirectives !== null) { this.addHostDirectiveSymbols(host, meta.hostDirectives, symbols); } const directiveSymbol: DirectiveSymbol = { ...symbol, isHostDirective: true, ref: current.directive, tsSymbol: symbol.tsSymbol, exposedInputs: current.inputs, exposedOutputs: current.outputs, selector: meta.selector, isComponent: meta.isComponent, ngModule: this.getDirectiveModule(current.directive.node), kind: SymbolKind.Directive, isStructural: meta.isStructural, isInScope: true, }; symbols.push(directiveSymbol); } } } private getDirectiveMeta( host: TmplAstTemplate | TmplAstElement, directiveDeclaration: ts.Declaration, ): TypeCheckableDirectiveMeta | null { let directives = this.templateData.boundTarget.getDirectivesOfNode(host); // `getDirectivesOfNode` will not return the directives intended for an element // on a microsyntax template, for example `<div *ngFor="let user of users;" dir>`, // the `dir` will be skipped, but it's needed in language service. const firstChild = host.children[0]; if (firstChild instanceof TmplAstElement) { const isMicrosyntaxTemplate = host instanceof TmplAstTemplate && sourceSpanEqual(firstChild.sourceSpan, host.sourceSpan); if (isMicrosyntaxTemplate) { const firstChildDirectives = this.templateData.boundTarget.getDirectivesOfNode(firstChild); if (firstChildDirectives !== null && directives !== null) { directives = directives.concat(firstChildDirectives); } else { directives = directives ?? firstChildDirectives; } } } if (directives === null) { return null; } return directives.find((m) => m.ref.node === directiveDeclaration) ?? null; } private getDirectiveModule(declaration: ts.ClassDeclaration): ClassDeclaration | null { const scope = this.componentScopeReader.getScopeForComponent(declaration as ClassDeclaration); if (scope === null || scope.kind !== ComponentScopeKind.NgModule) { return null; } return scope.ngModule; }
{ "end_byte": 10195, "start_byte": 1788, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts_10199_18829
private getSymbolOfBoundEvent(eventBinding: TmplAstBoundEvent): OutputBindingSymbol | null { const consumer = this.templateData.boundTarget.getConsumerOfBinding(eventBinding); if (consumer === null) { return null; } // Outputs in the TCB look like one of the two: // * _t1["outputField"].subscribe(handler); // * _t1.addEventListener(handler); // Even with strict null checks disabled, we still produce the access as a separate statement // so that it can be found here. let expectedAccess: string; if (consumer instanceof TmplAstTemplate || consumer instanceof TmplAstElement) { expectedAccess = 'addEventListener'; } else { const bindingPropertyNames = consumer.outputs.getByBindingPropertyName(eventBinding.name); if (bindingPropertyNames === null || bindingPropertyNames.length === 0) { return null; } // Note that we only get the expectedAccess text from a single consumer of the binding. If // there are multiple consumers (not supported in the `boundTarget` API) and one of them has // an alias, it will not get matched here. expectedAccess = bindingPropertyNames[0].classPropertyName; } function filter(n: ts.Node): n is ts.PropertyAccessExpression | ts.ElementAccessExpression { if (!isAccessExpression(n)) { return false; } if (ts.isPropertyAccessExpression(n)) { return n.name.getText() === expectedAccess; } else { return ( ts.isStringLiteral(n.argumentExpression) && n.argumentExpression.text === expectedAccess ); } } const outputFieldAccesses = findAllMatchingNodes(this.typeCheckBlock, { withSpan: eventBinding.keySpan, filter, }); const bindings: BindingSymbol[] = []; for (const outputFieldAccess of outputFieldAccesses) { if (consumer instanceof TmplAstTemplate || consumer instanceof TmplAstElement) { if (!ts.isPropertyAccessExpression(outputFieldAccess)) { continue; } const addEventListener = outputFieldAccess.name; const tsSymbol = this.getTypeChecker().getSymbolAtLocation(addEventListener); const tsType = this.getTypeChecker().getTypeAtLocation(addEventListener); const positionInFile = this.getTcbPositionForNode(addEventListener); const target = this.getSymbol(consumer); if (target === null || tsSymbol === undefined) { continue; } bindings.push({ kind: SymbolKind.Binding, tsSymbol, tsType, target, tcbLocation: { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile, }, }); } else { if (!ts.isElementAccessExpression(outputFieldAccess)) { continue; } const tsSymbol = this.getTypeChecker().getSymbolAtLocation( outputFieldAccess.argumentExpression, ); if (tsSymbol === undefined) { continue; } const target = this.getDirectiveSymbolForAccessExpression(outputFieldAccess, consumer); if (target === null) { continue; } const positionInFile = this.getTcbPositionForNode(outputFieldAccess); const tsType = this.getTypeChecker().getTypeAtLocation(outputFieldAccess); bindings.push({ kind: SymbolKind.Binding, tsSymbol, tsType, target, tcbLocation: { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile, }, }); } } if (bindings.length === 0) { return null; } return {kind: SymbolKind.Output, bindings}; } private getSymbolOfInputBinding( binding: TmplAstBoundAttribute | TmplAstTextAttribute, ): InputBindingSymbol | DomBindingSymbol | null { const consumer = this.templateData.boundTarget.getConsumerOfBinding(binding); if (consumer === null) { return null; } if (consumer instanceof TmplAstElement || consumer instanceof TmplAstTemplate) { const host = this.getSymbol(consumer); return host !== null ? {kind: SymbolKind.DomBinding, host} : null; } const nodes = findAllMatchingNodes(this.typeCheckBlock, { withSpan: binding.sourceSpan, filter: isAssignment, }); const bindings: BindingSymbol[] = []; for (const node of nodes) { if (!isAccessExpression(node.left)) { continue; } const signalInputAssignment = unwrapSignalInputWriteTAccessor(node.left); let fieldAccessExpr: ts.PropertyAccessExpression | ts.ElementAccessExpression; let symbolInfo: TsNodeSymbolInfo | null = null; // Signal inputs need special treatment because they are generated with an extra keyed // access. E.g. `_t1.prop[WriteT_ACCESSOR_SYMBOL]`. Observations: // - The keyed access for the write type needs to be resolved for the "input type". // - The definition symbol of the input should be the input class member, and not the // internal write accessor. Symbol should resolve `_t1.prop`. if (signalInputAssignment !== null) { // Note: If the field expression for the input binding refers to just an identifier, // then we are handling the case of a temporary variable being used for the input field. // This is the case with `honorAccessModifiersForInputBindings = false` and in those cases // we cannot resolve the owning directive, similar to how we guard above with `isAccessExpression`. if (ts.isIdentifier(signalInputAssignment.fieldExpr)) { continue; } const fieldSymbol = this.getSymbolOfTsNode(signalInputAssignment.fieldExpr); const typeSymbol = this.getSymbolOfTsNode(signalInputAssignment.typeExpr); fieldAccessExpr = signalInputAssignment.fieldExpr; symbolInfo = fieldSymbol === null || typeSymbol === null ? null : { tcbLocation: fieldSymbol.tcbLocation, tsSymbol: fieldSymbol.tsSymbol, tsType: typeSymbol.tsType, }; } else { fieldAccessExpr = node.left; symbolInfo = this.getSymbolOfTsNode(node.left); } if (symbolInfo === null || symbolInfo.tsSymbol === null) { continue; } const target = this.getDirectiveSymbolForAccessExpression(fieldAccessExpr, consumer); if (target === null) { continue; } bindings.push({ ...symbolInfo, tsSymbol: symbolInfo.tsSymbol, kind: SymbolKind.Binding, target, }); } if (bindings.length === 0) { return null; } return {kind: SymbolKind.Input, bindings}; } private getDirectiveSymbolForAccessExpression( fieldAccessExpr: ts.ElementAccessExpression | ts.PropertyAccessExpression, {isComponent, selector, isStructural}: TypeCheckableDirectiveMeta, ): DirectiveSymbol | null { // In all cases, `_t1["index"]` or `_t1.index`, `node.expression` is _t1. const tsSymbol = this.getTypeChecker().getSymbolAtLocation(fieldAccessExpr.expression); if ( tsSymbol?.declarations === undefined || tsSymbol.declarations.length === 0 || selector === null ) { return null; } const [declaration] = tsSymbol.declarations; if ( !ts.isVariableDeclaration(declaration) || !hasExpressionIdentifier( // The expression identifier could be on the type (for regular directives) or the name // (for generic directives and the ctor op). declaration.getSourceFile(), declaration.type ?? declaration.name, ExpressionIdentifier.DIRECTIVE, ) ) { return null; } const symbol = this.getSymbolOfTsNode(declaration); if ( symbol === null || !isSymbolWithValueDeclaration(symbol.tsSymbol) || !ts.isClassDeclaration(symbol.tsSymbol.valueDeclaration) ) { return null; } const ref: Reference<ClassDeclaration> = new Reference(symbol.tsSymbol.valueDeclaration as any); const ngModule = this.getDirectiveModule(symbol.tsSymbol.valueDeclaration); return { ref, kind: SymbolKind.Directive, tsSymbol: symbol.tsSymbol, tsType: symbol.tsType, tcbLocation: symbol.tcbLocation, isComponent, isStructural, selector, ngModule, isHostDirective: false, isInScope: true, // TODO: this should always be in scope in this context, right? }; }
{ "end_byte": 18829, "start_byte": 10199, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts_18833_26915
private getSymbolOfVariable(variable: TmplAstVariable): VariableSymbol | null { const node = findFirstMatchingNode(this.typeCheckBlock, { withSpan: variable.sourceSpan, filter: ts.isVariableDeclaration, }); if (node === null) { return null; } let nodeValueSymbol: TsNodeSymbolInfo | null = null; if (ts.isForOfStatement(node.parent.parent)) { nodeValueSymbol = this.getSymbolOfTsNode(node); } else if (node.initializer !== undefined) { nodeValueSymbol = this.getSymbolOfTsNode(node.initializer); } if (nodeValueSymbol === null) { return null; } return { tsType: nodeValueSymbol.tsType, tsSymbol: nodeValueSymbol.tsSymbol, initializerLocation: nodeValueSymbol.tcbLocation, kind: SymbolKind.Variable, declaration: variable, localVarLocation: { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: this.getTcbPositionForNode(node.name), }, }; } private getSymbolOfReference(ref: TmplAstReference): ReferenceSymbol | null { const target = this.templateData.boundTarget.getReferenceTarget(ref); // Find the node for the reference declaration, i.e. `var _t2 = _t1;` let node = findFirstMatchingNode(this.typeCheckBlock, { withSpan: ref.sourceSpan, filter: ts.isVariableDeclaration, }); if (node === null || target === null || node.initializer === undefined) { return null; } // Get the original declaration for the references variable, with the exception of template refs // which are of the form var _t3 = (_t2 as any as i2.TemplateRef<any>) // TODO(atscott): Consider adding an `ExpressionIdentifier` to tag variable declaration // initializers as invalid for symbol retrieval. const originalDeclaration = ts.isParenthesizedExpression(node.initializer) && ts.isAsExpression(node.initializer.expression) ? this.getTypeChecker().getSymbolAtLocation(node.name) : this.getTypeChecker().getSymbolAtLocation(node.initializer); if (originalDeclaration === undefined || originalDeclaration.valueDeclaration === undefined) { return null; } const symbol = this.getSymbolOfTsNode(originalDeclaration.valueDeclaration); if (symbol === null || symbol.tsSymbol === null) { return null; } const referenceVarTcbLocation: TcbLocation = { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: this.getTcbPositionForNode(node), }; if (target instanceof TmplAstTemplate || target instanceof TmplAstElement) { return { kind: SymbolKind.Reference, tsSymbol: symbol.tsSymbol, tsType: symbol.tsType, target, declaration: ref, targetLocation: symbol.tcbLocation, referenceVarLocation: referenceVarTcbLocation, }; } else { if (!ts.isClassDeclaration(target.directive.ref.node)) { return null; } return { kind: SymbolKind.Reference, tsSymbol: symbol.tsSymbol, tsType: symbol.tsType, declaration: ref, target: target.directive.ref.node, targetLocation: symbol.tcbLocation, referenceVarLocation: referenceVarTcbLocation, }; } } private getSymbolOfLetDeclaration(decl: TmplAstLetDeclaration): LetDeclarationSymbol | null { const node = findFirstMatchingNode(this.typeCheckBlock, { withSpan: decl.sourceSpan, filter: ts.isVariableDeclaration, }); if (node === null) { return null; } const nodeValueSymbol = this.getSymbolOfTsNode(node.initializer!); if (nodeValueSymbol === null) { return null; } return { tsType: nodeValueSymbol.tsType, tsSymbol: nodeValueSymbol.tsSymbol, initializerLocation: nodeValueSymbol.tcbLocation, kind: SymbolKind.LetDeclaration, declaration: decl, localVarLocation: { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: this.getTcbPositionForNode(node.name), }, }; } private getSymbolOfPipe(expression: BindingPipe): PipeSymbol | null { const methodAccess = findFirstMatchingNode(this.typeCheckBlock, { withSpan: expression.nameSpan, filter: ts.isPropertyAccessExpression, }); if (methodAccess === null) { return null; } const pipeVariableNode = methodAccess.expression; const pipeDeclaration = this.getTypeChecker().getSymbolAtLocation(pipeVariableNode); if (pipeDeclaration === undefined || pipeDeclaration.valueDeclaration === undefined) { return null; } const pipeInstance = this.getSymbolOfTsNode(pipeDeclaration.valueDeclaration); // The instance should never be null, nor should the symbol lack a value declaration. This // is because the node used to look for the `pipeInstance` symbol info is a value // declaration of another symbol (i.e. the `pipeDeclaration` symbol). if (pipeInstance === null || !isSymbolWithValueDeclaration(pipeInstance.tsSymbol)) { return null; } const symbolInfo = this.getSymbolOfTsNode(methodAccess); if (symbolInfo === null) { return null; } return { kind: SymbolKind.Pipe, ...symbolInfo, classSymbol: { ...pipeInstance, tsSymbol: pipeInstance.tsSymbol, }, }; } private getSymbolOfTemplateExpression( expression: AST, ): VariableSymbol | ReferenceSymbol | ExpressionSymbol | LetDeclarationSymbol | null { if (expression instanceof ASTWithSource) { expression = expression.ast; } const expressionTarget = this.templateData.boundTarget.getExpressionTarget(expression); if (expressionTarget !== null) { return this.getSymbol(expressionTarget); } let withSpan = expression.sourceSpan; // The `name` part of a `PropertyWrite` and `ASTWithName` do not have their own // AST so there is no way to retrieve a `Symbol` for just the `name` via a specific node. // Also skipping SafePropertyReads as it breaks nullish coalescing not nullable extended diagnostic if ( expression instanceof PropertyWrite || (expression instanceof ASTWithName && !(expression instanceof SafePropertyRead)) ) { withSpan = expression.nameSpan; } let node: ts.Node | null = null; // Property reads in templates usually map to a `PropertyAccessExpression` // (e.g. `ctx.foo`) so try looking for one first. if (expression instanceof PropertyRead) { node = findFirstMatchingNode(this.typeCheckBlock, { withSpan, filter: ts.isPropertyAccessExpression, }); } // Otherwise fall back to searching for any AST node. if (node === null) { node = findFirstMatchingNode(this.typeCheckBlock, {withSpan, filter: anyNodeFilter}); } if (node === null) { return null; } while (ts.isParenthesizedExpression(node)) { node = node.expression; } // - If we have safe property read ("a?.b") we want to get the Symbol for b, the `whenTrue` // expression. // - If our expression is a pipe binding ("a | test:b:c"), we want the Symbol for the // `transform` on the pipe. // - Otherwise, we retrieve the symbol for the node itself with no special considerations if (expression instanceof SafePropertyRead && ts.isConditionalExpression(node)) { const whenTrueSymbol = this.getSymbolOfTsNode(node.whenTrue); if (whenTrueSymbol === null) { return null; } return { ...whenTrueSymbol, kind: SymbolKind.Expression, // Rather than using the type of only the `whenTrue` part of the expression, we should // still get the type of the whole conditional expression to include `|undefined`. tsType: this.getTypeChecker().getTypeAtLocation(node), }; } else { const symbolInfo = this.getSymbolOfTsNode(node); return symbolInfo === null ? null : {...symbolInfo, kind: SymbolKind.Expression}; } }
{ "end_byte": 26915, "start_byte": 18833, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts_26919_30377
private getSymbolOfTsNode(node: ts.Node): TsNodeSymbolInfo | null { while (ts.isParenthesizedExpression(node)) { node = node.expression; } let tsSymbol: ts.Symbol | undefined; if (ts.isPropertyAccessExpression(node)) { tsSymbol = this.getTypeChecker().getSymbolAtLocation(node.name); } else if (ts.isCallExpression(node)) { tsSymbol = this.getTypeChecker().getSymbolAtLocation(node.expression); } else { tsSymbol = this.getTypeChecker().getSymbolAtLocation(node); } const positionInFile = this.getTcbPositionForNode(node); const type = this.getTypeChecker().getTypeAtLocation(node); return { // If we could not find a symbol, fall back to the symbol on the type for the node. // Some nodes won't have a "symbol at location" but will have a symbol for the type. // Examples of this would be literals and `document.createElement('div')`. tsSymbol: tsSymbol ?? type.symbol ?? null, tsType: type, tcbLocation: { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile, }, }; } private getTcbPositionForNode(node: ts.Node): number { if (ts.isTypeReferenceNode(node)) { return this.getTcbPositionForNode(node.typeName); } else if (ts.isQualifiedName(node)) { return node.right.getStart(); } else if (ts.isPropertyAccessExpression(node)) { return node.name.getStart(); } else if (ts.isElementAccessExpression(node)) { return node.argumentExpression.getStart(); } else { return node.getStart(); } } } /** Filter predicate function that matches any AST node. */ function anyNodeFilter(n: ts.Node): n is ts.Node { return true; } function sourceSpanEqual(a: ParseSourceSpan, b: ParseSourceSpan) { return a.start.offset === b.start.offset && a.end.offset === b.end.offset; } function unwrapSignalInputWriteTAccessor(expr: ts.LeftHandSideExpression): null | { fieldExpr: ts.ElementAccessExpression | ts.PropertyAccessExpression | ts.Identifier; typeExpr: ts.ElementAccessExpression; } { // e.g. `_t2.inputA[i2.ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]` // 1. Assert that we are dealing with an element access expression. // 2. Assert that we are dealing with a signal brand symbol access in the argument expression. if ( !ts.isElementAccessExpression(expr) || !ts.isPropertyAccessExpression(expr.argumentExpression) ) { return null; } // Assert that the property access in the element access is a simple identifier and // refers to `ɵINPUT_SIGNAL_BRAND_WRITE_TYPE`. if ( !ts.isIdentifier(expr.argumentExpression.name) || expr.argumentExpression.name.text !== R3Identifiers.InputSignalBrandWriteType.name ) { return null; } // Assert that the expression is either: // - `_t2.inputA[ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]` or (common case) // - or `_t2['input-A'][ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]` (non-identifier input field names) // - or `_dirInput[ɵINPUT_SIGNAL_BRAND_WRITE_TYPE` (honorAccessModifiersForInputBindings=false) // This is checked for type safety and to catch unexpected cases. if ( !ts.isPropertyAccessExpression(expr.expression) && !ts.isElementAccessExpression(expr.expression) && !ts.isIdentifier(expr.expression) ) { throw new Error('Unexpected expression for signal input write type.'); } return { fieldExpr: expr.expression, typeExpr: expr, }; }
{ "end_byte": 30377, "start_byte": 26919, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/environment.ts_0_5611
/** * @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.dev/license */ import ts from 'typescript'; import { assertSuccessfulReferenceEmit, ImportFlags, Reference, ReferenceEmitter, } from '../../imports'; import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {ImportManager, translateExpression} from '../../translator'; import {TypeCheckableDirectiveMeta, TypeCheckingConfig, TypeCtorMetadata} from '../api'; import {ReferenceEmitEnvironment} from './reference_emit_environment'; import {tsDeclareVariable} from './ts_util'; import {generateTypeCtorDeclarationFn, requiresInlineTypeCtor} from './type_constructor'; import {TypeParameterEmitter} from './type_parameter_emitter'; /** * A context which hosts one or more Type Check Blocks (TCBs). * * An `Environment` supports the generation of TCBs by tracking necessary imports, declarations of * type constructors, and other statements beyond the type-checking code within the TCB itself. * Through method calls on `Environment`, the TCB generator can request `ts.Expression`s which * reference declarations in the `Environment` for these artifacts`. * * `Environment` can be used in a standalone fashion, or can be extended to support more specialized * usage. */ export class Environment extends ReferenceEmitEnvironment { private nextIds = { pipeInst: 1, typeCtor: 1, }; private typeCtors = new Map<ClassDeclaration, ts.Expression>(); protected typeCtorStatements: ts.Statement[] = []; private pipeInsts = new Map<ClassDeclaration, ts.Expression>(); protected pipeInstStatements: ts.Statement[] = []; constructor( readonly config: TypeCheckingConfig, importManager: ImportManager, refEmitter: ReferenceEmitter, reflector: ReflectionHost, contextFile: ts.SourceFile, ) { super(importManager, refEmitter, reflector, contextFile); } /** * Get an expression referring to a type constructor for the given directive. * * Depending on the shape of the directive itself, this could be either a reference to a declared * type constructor, or to an inline type constructor. */ typeCtorFor(dir: TypeCheckableDirectiveMeta): ts.Expression { const dirRef = dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>; const node = dirRef.node; if (this.typeCtors.has(node)) { return this.typeCtors.get(node)!; } if (requiresInlineTypeCtor(node, this.reflector, this)) { // The constructor has already been created inline, we just need to construct a reference to // it. const ref = this.reference(dirRef); const typeCtorExpr = ts.factory.createPropertyAccessExpression(ref, 'ngTypeCtor'); this.typeCtors.set(node, typeCtorExpr); return typeCtorExpr; } else { const fnName = `_ctor${this.nextIds.typeCtor++}`; const nodeTypeRef = this.referenceType(dirRef); if (!ts.isTypeReferenceNode(nodeTypeRef)) { throw new Error(`Expected TypeReferenceNode from reference to ${dirRef.debugName}`); } const meta: TypeCtorMetadata = { fnName, body: true, fields: { inputs: dir.inputs, // TODO: support queries queries: dir.queries, }, coercedInputFields: dir.coercedInputFields, }; const typeParams = this.emitTypeParameters(node); const typeCtor = generateTypeCtorDeclarationFn(this, meta, nodeTypeRef.typeName, typeParams); this.typeCtorStatements.push(typeCtor); const fnId = ts.factory.createIdentifier(fnName); this.typeCtors.set(node, fnId); return fnId; } } /* * Get an expression referring to an instance of the given pipe. */ pipeInst(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.Expression { if (this.pipeInsts.has(ref.node)) { return this.pipeInsts.get(ref.node)!; } const pipeType = this.referenceType(ref); const pipeInstId = ts.factory.createIdentifier(`_pipe${this.nextIds.pipeInst++}`); this.pipeInstStatements.push(tsDeclareVariable(pipeInstId, pipeType)); this.pipeInsts.set(ref.node, pipeInstId); return pipeInstId; } /** * Generate a `ts.Expression` that references the given node. * * This may involve importing the node into the file if it's not declared there already. */ reference(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.Expression { // Disable aliasing for imports generated in a template type-checking context, as there is no // guarantee that any alias re-exports exist in the .d.ts files. It's safe to use direct imports // in these cases as there is no strict dependency checking during the template type-checking // pass. const ngExpr = this.refEmitter.emit(ref, this.contextFile, ImportFlags.NoAliasing); assertSuccessfulReferenceEmit(ngExpr, this.contextFile, 'class'); // Use `translateExpression` to convert the `Expression` into a `ts.Expression`. return translateExpression(this.contextFile, ngExpr.expression, this.importManager); } private emitTypeParameters( declaration: ClassDeclaration<ts.ClassDeclaration>, ): ts.TypeParameterDeclaration[] | undefined { const emitter = new TypeParameterEmitter(declaration.typeParameters, this.reflector); return emitter.emit((ref) => this.referenceType(ref)); } getPreludeStatements(): ts.Statement[] { return [...this.pipeInstStatements, ...this.typeCtorStatements]; } }
{ "end_byte": 5611, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/environment.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/line_mappings.ts_0_2030
/** * @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.dev/license */ const LF_CHAR = 10; const CR_CHAR = 13; const LINE_SEP_CHAR = 8232; const PARAGRAPH_CHAR = 8233; /** Gets the line and character for the given position from the line starts map. */ export function getLineAndCharacterFromPosition(lineStartsMap: number[], position: number) { const lineIndex = findClosestLineStartPosition(lineStartsMap, position); return {character: position - lineStartsMap[lineIndex], line: lineIndex}; } /** * Computes the line start map of the given text. This can be used in order to * retrieve the line and character of a given text position index. */ export function computeLineStartsMap(text: string): number[] { const result: number[] = [0]; let pos = 0; while (pos < text.length) { const char = text.charCodeAt(pos++); // Handles the "CRLF" line break. In that case we peek the character // after the "CR" and check if it is a line feed. if (char === CR_CHAR) { if (text.charCodeAt(pos) === LF_CHAR) { pos++; } result.push(pos); } else if (char === LF_CHAR || char === LINE_SEP_CHAR || char === PARAGRAPH_CHAR) { result.push(pos); } } result.push(pos); return result; } /** Finds the closest line start for the given position. */ function findClosestLineStartPosition<T>( linesMap: T[], position: T, low = 0, high = linesMap.length - 1, ) { while (low <= high) { const pivotIdx = Math.floor((low + high) / 2); const pivotEl = linesMap[pivotIdx]; if (pivotEl === position) { return pivotIdx; } else if (position > pivotEl) { low = pivotIdx + 1; } else { high = pivotIdx - 1; } } // In case there was no exact match, return the closest "lower" line index. We also // subtract the index by one because want the index of the previous line start. return low - 1; }
{ "end_byte": 2030, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/line_mappings.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts_0_5863
/** * @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.dev/license */ import { BoundTarget, ParseError, ParseSourceFile, R3TargetBinder, SchemaMetadata, TmplAstNode, } from '@angular/compiler'; import MagicString from 'magic-string'; import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../../../src/ngtsc/diagnostics'; import {absoluteFromSourceFile, AbsoluteFsPath} from '../../file_system'; import {Reference, ReferenceEmitter} from '../../imports'; import {PipeMeta} from '../../metadata'; import {PerfEvent, PerfRecorder} from '../../perf'; import {FileUpdate} from '../../program_driver'; import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {ImportManager} from '../../translator'; import { TemplateDiagnostic, TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckContext, TypeCheckingConfig, TypeCtorMetadata, } from '../api'; import {makeTemplateDiagnostic} from '../diagnostics'; import {DomSchemaChecker, RegistryDomSchemaChecker} from './dom'; import {Environment} from './environment'; import {OutOfBandDiagnosticRecorder, OutOfBandDiagnosticRecorderImpl} from './oob'; import {ReferenceEmitEnvironment} from './reference_emit_environment'; import {TypeCheckShimGenerator} from './shim'; import {TemplateSourceManager} from './source'; import {requiresInlineTypeCheckBlock, TcbInliningRequirement} from './tcb_util'; import {generateTypeCheckBlock, TcbGenericContextBehavior} from './type_check_block'; import {TypeCheckFile} from './type_check_file'; import {generateInlineTypeCtor, requiresInlineTypeCtor} from './type_constructor'; export interface ShimTypeCheckingData { /** * Path to the shim file. */ path: AbsoluteFsPath; /** * Any `ts.Diagnostic`s which were produced during the generation of this shim. * * Some diagnostics are produced during creation time and are tracked here. */ genesisDiagnostics: TemplateDiagnostic[]; /** * Whether any inline operations for the input file were required to generate this shim. */ hasInlines: boolean; /** * Map of `TemplateId` to information collected about the template during the template * type-checking process. */ templates: Map<TemplateId, TemplateData>; } /** * Data tracked for each template processed by the template type-checking system. */ export interface TemplateData { /** * Template nodes for which the TCB was generated. */ template: TmplAstNode[]; /** * `BoundTarget` which was used to generate the TCB, and contains bindings for the associated * template nodes. */ boundTarget: BoundTarget<TypeCheckableDirectiveMeta>; /** * Errors found while parsing them template, which have been converted to diagnostics. */ templateDiagnostics: TemplateDiagnostic[]; } /** * Data for an input file which is still in the process of template type-checking code generation. */ export interface PendingFileTypeCheckingData { /** * Whether any inline code has been required by the shim yet. */ hasInlines: boolean; /** * Source mapping information for mapping diagnostics from inlined type check blocks back to the * original template. */ sourceManager: TemplateSourceManager; /** * Map of in-progress shim data for shims generated from this input file. */ shimData: Map<AbsoluteFsPath, PendingShimData>; } export interface PendingShimData { /** * Recorder for out-of-band diagnostics which are raised during generation. */ oobRecorder: OutOfBandDiagnosticRecorder; /** * The `DomSchemaChecker` in use for this template, which records any schema-related diagnostics. */ domSchemaChecker: DomSchemaChecker; /** * Shim file in the process of being generated. */ file: TypeCheckFile; /** * Map of `TemplateId` to information collected about the template as it's ingested. */ templates: Map<TemplateId, TemplateData>; } /** * Adapts the `TypeCheckContextImpl` to the larger template type-checking system. * * Through this interface, a single `TypeCheckContextImpl` (which represents one "pass" of template * type-checking) requests information about the larger state of type-checking, as well as reports * back its results once finalized. */ export interface TypeCheckingHost { /** * Retrieve the `TemplateSourceManager` responsible for components in the given input file path. */ getSourceManager(sfPath: AbsoluteFsPath): TemplateSourceManager; /** * Whether a particular component class should be included in the current type-checking pass. * * Not all components offered to the `TypeCheckContext` for checking may require processing. For * example, the component may have results already available from a prior pass or from a previous * program. */ shouldCheckComponent(node: ts.ClassDeclaration): boolean; /** * Report data from a shim generated from the given input file path. */ recordShimData(sfPath: AbsoluteFsPath, data: ShimTypeCheckingData): void; /** * Record that all of the components within the given input file path had code generated - that * is, coverage for the file can be considered complete. */ recordComplete(sfPath: AbsoluteFsPath): void; } /** * How a type-checking context should handle operations which would require inlining. */ export enum InliningMode { /** * Use inlining operations when required. */ InlineOps, /** * Produce diagnostics if an operation would require inlining. */ Error, } /** * A template type checking context for a program. * * The `TypeCheckContext` allows registration of components and their templates which need to be * type checked. */
{ "end_byte": 5863, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts_5864_13051
export class TypeCheckContextImpl implements TypeCheckContext { private fileMap = new Map<AbsoluteFsPath, PendingFileTypeCheckingData>(); constructor( private config: TypeCheckingConfig, private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, private refEmitter: ReferenceEmitter, private reflector: ReflectionHost, private host: TypeCheckingHost, private inlining: InliningMode, private perf: PerfRecorder, ) { if (inlining === InliningMode.Error && config.useInlineTypeConstructors) { // We cannot use inlining for type checking since this environment does not support it. throw new Error(`AssertionError: invalid inlining configuration.`); } } /** * A `Map` of `ts.SourceFile`s that the context has seen to the operations (additions of methods * or type-check blocks) that need to be eventually performed on that file. */ private opMap = new Map<ts.SourceFile, Op[]>(); /** * Tracks when an a particular class has a pending type constructor patching operation already * queued. */ private typeCtorPending = new Set<ts.ClassDeclaration>(); /** * Register a template to potentially be type-checked. * * Implements `TypeCheckContext.addTemplate`. */ addTemplate( ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, binder: R3TargetBinder<TypeCheckableDirectiveMeta>, template: TmplAstNode[], pipes: Map<string, PipeMeta>, schemas: SchemaMetadata[], sourceMapping: TemplateSourceMapping, file: ParseSourceFile, parseErrors: ParseError[] | null, isStandalone: boolean, preserveWhitespaces: boolean, ): void { if (!this.host.shouldCheckComponent(ref.node)) { return; } const fileData = this.dataForFile(ref.node.getSourceFile()); const shimData = this.pendingShimForComponent(ref.node); const templateId = fileData.sourceManager.getTemplateId(ref.node); const templateDiagnostics: TemplateDiagnostic[] = []; if (parseErrors !== null) { templateDiagnostics.push(...getTemplateDiagnostics(parseErrors, templateId, sourceMapping)); } const boundTarget = binder.bind({template}); if (this.inlining === InliningMode.InlineOps) { // Get all of the directives used in the template and record inline type constructors when // required. for (const dir of boundTarget.getUsedDirectives()) { const dirRef = dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>; const dirNode = dirRef.node; if (!dir.isGeneric || !requiresInlineTypeCtor(dirNode, this.reflector, shimData.file)) { // inlining not required continue; } // Add an inline type constructor operation for the directive. this.addInlineTypeCtor(fileData, dirNode.getSourceFile(), dirRef, { fnName: 'ngTypeCtor', // The constructor should have a body if the directive comes from a .ts file, but not if // it comes from a .d.ts file. .d.ts declarations don't have bodies. body: !dirNode.getSourceFile().isDeclarationFile, fields: { inputs: dir.inputs, // TODO(alxhub): support queries queries: dir.queries, }, coercedInputFields: dir.coercedInputFields, }); } } shimData.templates.set(templateId, { template, boundTarget, templateDiagnostics, }); const usedPipes: Reference<ClassDeclaration<ts.ClassDeclaration>>[] = []; for (const name of boundTarget.getUsedPipes()) { if (!pipes.has(name)) { continue; } usedPipes.push(pipes.get(name)!.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>); } const inliningRequirement = requiresInlineTypeCheckBlock( ref, shimData.file, usedPipes, this.reflector, ); // If inlining is not supported, but is required for either the TCB or one of its directive // dependencies, then exit here with an error. if ( this.inlining === InliningMode.Error && inliningRequirement === TcbInliningRequirement.MustInline ) { // This template cannot be supported because the underlying strategy does not support inlining // and inlining would be required. // Record diagnostics to indicate the issues with this template. shimData.oobRecorder.requiresInlineTcb(templateId, ref.node); // Checking this template would be unsupported, so don't try. this.perf.eventCount(PerfEvent.SkipGenerateTcbNoInline); return; } const meta = { id: fileData.sourceManager.captureSource(ref.node, sourceMapping, file), boundTarget, pipes, schemas, isStandalone, preserveWhitespaces, }; this.perf.eventCount(PerfEvent.GenerateTcb); if ( inliningRequirement !== TcbInliningRequirement.None && this.inlining === InliningMode.InlineOps ) { // This class didn't meet the requirements for external type checking, so generate an inline // TCB for the class. this.addInlineTypeCheckBlock(fileData, shimData, ref, meta); } else if ( inliningRequirement === TcbInliningRequirement.ShouldInlineForGenericBounds && this.inlining === InliningMode.Error ) { // It's suggested that this TCB should be generated inline due to the component's generic // bounds, but inlining is not supported by the current environment. Use a non-inline type // check block, but fall back to `any` generic parameters since the generic bounds can't be // referenced in that context. This will infer a less useful type for the component, but allow // for type-checking it in an environment where that would not be possible otherwise. shimData.file.addTypeCheckBlock( ref, meta, shimData.domSchemaChecker, shimData.oobRecorder, TcbGenericContextBehavior.FallbackToAny, ); } else { shimData.file.addTypeCheckBlock( ref, meta, shimData.domSchemaChecker, shimData.oobRecorder, TcbGenericContextBehavior.UseEmitter, ); } } /** * Record a type constructor for the given `node` with the given `ctorMetadata`. */ addInlineTypeCtor( fileData: PendingFileTypeCheckingData, sf: ts.SourceFile, ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, ctorMeta: TypeCtorMetadata, ): void { if (this.typeCtorPending.has(ref.node)) { return; } this.typeCtorPending.add(ref.node); // Lazily construct the operation map. if (!this.opMap.has(sf)) { this.opMap.set(sf, []); } const ops = this.opMap.get(sf)!; // Push a `TypeCtorOp` into the operation queue for the source file. ops.push(new TypeCtorOp(ref, this.reflector, ctorMeta)); fileData.hasInlines = true; } /** * Transform a `ts.SourceFile` into a version that includes type checking code. * * If this particular `ts.SourceFile` requires changes, the text representing its new contents * will be returned. Otherwise, a `null` return indicates no changes were necessary. */
{ "end_byte": 13051, "start_byte": 5864, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts_13054_21401
transform(sf: ts.SourceFile): string | null { // If there are no operations pending for this particular file, return `null` to indicate no // changes. if (!this.opMap.has(sf)) { return null; } // Use a `ts.Printer` to generate source code. const printer = ts.createPrinter({omitTrailingSemicolon: true}); // Imports may need to be added to the file to support type-checking of directives // used in the template within it. const importManager = new ImportManager({ // This minimizes noticeable changes with older versions of `ImportManager`. forceGenerateNamespacesForNewImports: true, // Type check block code affects code completion and fix suggestions. // We want to encourage single quotes for now, like we always did. shouldUseSingleQuotes: () => true, }); // Execute ops. // Each Op has a splitPoint index into the text where it needs to be inserted. const updates: {pos: number; deletePos?: number; text: string}[] = this.opMap .get(sf)! .map((op) => { return { pos: op.splitPoint, text: op.execute(importManager, sf, this.refEmitter, printer), }; }); const {newImports, updatedImports} = importManager.finalize(); // Capture new imports if (newImports.has(sf.fileName)) { newImports.get(sf.fileName)!.forEach((newImport) => { updates.push({ pos: 0, text: printer.printNode(ts.EmitHint.Unspecified, newImport, sf), }); }); } // Capture updated imports for (const [oldBindings, newBindings] of updatedImports.entries()) { if (oldBindings.getSourceFile() !== sf) { throw new Error('Unexpected updates to unrelated source files.'); } updates.push({ pos: oldBindings.getStart(), deletePos: oldBindings.getEnd(), text: printer.printNode(ts.EmitHint.Unspecified, newBindings, sf), }); } const result = new MagicString(sf.text, {filename: sf.fileName}); for (const update of updates) { if (update.deletePos !== undefined) { result.remove(update.pos, update.deletePos); } result.appendLeft(update.pos, update.text); } return result.toString(); } finalize(): Map<AbsoluteFsPath, FileUpdate> { // First, build the map of updates to source files. const updates = new Map<AbsoluteFsPath, FileUpdate>(); for (const originalSf of this.opMap.keys()) { const newText = this.transform(originalSf); if (newText !== null) { updates.set(absoluteFromSourceFile(originalSf), { newText, originalFile: originalSf, }); } } // Then go through each input file that has pending code generation operations. for (const [sfPath, pendingFileData] of this.fileMap) { // For each input file, consider generation operations for each of its shims. for (const pendingShimData of pendingFileData.shimData.values()) { this.host.recordShimData(sfPath, { genesisDiagnostics: [ ...pendingShimData.domSchemaChecker.diagnostics, ...pendingShimData.oobRecorder.diagnostics, ], hasInlines: pendingFileData.hasInlines, path: pendingShimData.file.fileName, templates: pendingShimData.templates, }); const sfText = pendingShimData.file.render(false /* removeComments */); updates.set(pendingShimData.file.fileName, { newText: sfText, // Shim files do not have an associated original file. originalFile: null, }); } } return updates; } private addInlineTypeCheckBlock( fileData: PendingFileTypeCheckingData, shimData: PendingShimData, ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, tcbMeta: TypeCheckBlockMetadata, ): void { const sf = ref.node.getSourceFile(); if (!this.opMap.has(sf)) { this.opMap.set(sf, []); } const ops = this.opMap.get(sf)!; ops.push( new InlineTcbOp( ref, tcbMeta, this.config, this.reflector, shimData.domSchemaChecker, shimData.oobRecorder, ), ); fileData.hasInlines = true; } private pendingShimForComponent(node: ts.ClassDeclaration): PendingShimData { const fileData = this.dataForFile(node.getSourceFile()); const shimPath = TypeCheckShimGenerator.shimFor(absoluteFromSourceFile(node.getSourceFile())); if (!fileData.shimData.has(shimPath)) { fileData.shimData.set(shimPath, { domSchemaChecker: new RegistryDomSchemaChecker(fileData.sourceManager), oobRecorder: new OutOfBandDiagnosticRecorderImpl(fileData.sourceManager), file: new TypeCheckFile( shimPath, this.config, this.refEmitter, this.reflector, this.compilerHost, ), templates: new Map<TemplateId, TemplateData>(), }); } return fileData.shimData.get(shimPath)!; } private dataForFile(sf: ts.SourceFile): PendingFileTypeCheckingData { const sfPath = absoluteFromSourceFile(sf); if (!this.fileMap.has(sfPath)) { const data: PendingFileTypeCheckingData = { hasInlines: false, sourceManager: this.host.getSourceManager(sfPath), shimData: new Map(), }; this.fileMap.set(sfPath, data); } return this.fileMap.get(sfPath)!; } } export function getTemplateDiagnostics( parseErrors: ParseError[], templateId: TemplateId, sourceMapping: TemplateSourceMapping, ): TemplateDiagnostic[] { return parseErrors.map((error) => { const span = error.span; if (span.start.offset === span.end.offset) { // Template errors can contain zero-length spans, if the error occurs at a single point. // However, TypeScript does not handle displaying a zero-length diagnostic very well, so // increase the ending offset by 1 for such errors, to ensure the position is shown in the // diagnostic. span.end.offset++; } return makeTemplateDiagnostic( templateId, sourceMapping, span, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.TEMPLATE_PARSE_ERROR), error.msg, ); }); } /** * A code generation operation that needs to happen within a given source file. */ interface Op { /** * The node in the file which will have code generated for it. */ readonly ref: Reference<ClassDeclaration<ts.ClassDeclaration>>; /** * Index into the source text where the code generated by the operation should be inserted. */ readonly splitPoint: number; /** * Execute the operation and return the generated code as text. */ execute( im: ImportManager, sf: ts.SourceFile, refEmitter: ReferenceEmitter, printer: ts.Printer, ): string; } /** * A type check block operation which produces inline type check code for a particular component. */ class InlineTcbOp implements Op { constructor( readonly ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, readonly meta: TypeCheckBlockMetadata, readonly config: TypeCheckingConfig, readonly reflector: ReflectionHost, readonly domSchemaChecker: DomSchemaChecker, readonly oobRecorder: OutOfBandDiagnosticRecorder, ) {} /** * Type check blocks are inserted immediately after the end of the component class. */ get splitPoint(): number { return this.ref.node.end + 1; } execute( im: ImportManager, sf: ts.SourceFile, refEmitter: ReferenceEmitter, printer: ts.Printer, ): string { const env = new Environment(this.config, im, refEmitter, this.reflector, sf); const fnName = ts.factory.createIdentifier(`_tcb_${this.ref.node.pos}`); // Inline TCBs should copy any generic type parameter nodes directly, as the TCB code is // inlined into the class in a context where that will always be legal. const fn = generateTypeCheckBlock( env, this.ref, fnName, this.meta, this.domSchemaChecker, this.oobRecorder, TcbGenericContextBehavior.CopyClassNodes, ); return printer.printNode(ts.EmitHint.Unspecified, fn, sf); } } /** * A type constructor operation which produces type constructor code for a particular directive. */
{ "end_byte": 21401, "start_byte": 13054, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts_21402_22692
class TypeCtorOp implements Op { constructor( readonly ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, readonly reflector: ReflectionHost, readonly meta: TypeCtorMetadata, ) {} /** * Type constructor operations are inserted immediately before the end of the directive class. */ get splitPoint(): number { return this.ref.node.end - 1; } execute( im: ImportManager, sf: ts.SourceFile, refEmitter: ReferenceEmitter, printer: ts.Printer, ): string { const emitEnv = new ReferenceEmitEnvironment(im, refEmitter, this.reflector, sf); const tcb = generateInlineTypeCtor(emitEnv, this.ref.node, this.meta); return printer.printNode(ts.EmitHint.Unspecified, tcb, sf); } } /** * Compare two operations and return their split point ordering. */ function orderOps(op1: Op, op2: Op): number { return op1.splitPoint - op2.splitPoint; } /** * Split a string into chunks at any number of split points. */ function splitStringAtPoints(str: string, points: number[]): string[] { const splits: string[] = []; let start = 0; for (let i = 0; i < points.length; i++) { const point = points[i]; splits.push(str.substring(start, point)); start = point; } splits.push(str.substring(start)); return splits; }
{ "end_byte": 22692, "start_byte": 21402, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/context.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts_0_8619
/** * @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.dev/license */ import {ExpressionType, R3Identifiers, WrappedNodeExpr} from '@angular/compiler'; import ts from 'typescript'; import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {TypeCtorMetadata} from '../api'; import {ReferenceEmitEnvironment} from './reference_emit_environment'; import {checkIfGenericTypeBoundsCanBeEmitted} from './tcb_util'; import {tsCreateTypeQueryForCoercedInput} from './ts_util'; export function generateTypeCtorDeclarationFn( env: ReferenceEmitEnvironment, meta: TypeCtorMetadata, nodeTypeRef: ts.EntityName, typeParams: ts.TypeParameterDeclaration[] | undefined, ): ts.Statement { const rawTypeArgs = typeParams !== undefined ? generateGenericArgs(typeParams) : undefined; const rawType = ts.factory.createTypeReferenceNode(nodeTypeRef, rawTypeArgs); const initParam = constructTypeCtorParameter(env, meta, rawType); const typeParameters = typeParametersWithDefaultTypes(typeParams); if (meta.body) { const fnType = ts.factory.createFunctionTypeNode( /* typeParameters */ typeParameters, /* parameters */ [initParam], /* type */ rawType, ); const decl = ts.factory.createVariableDeclaration( /* name */ meta.fnName, /* exclamationToken */ undefined, /* type */ fnType, /* body */ ts.factory.createNonNullExpression(ts.factory.createNull()), ); const declList = ts.factory.createVariableDeclarationList([decl], ts.NodeFlags.Const); return ts.factory.createVariableStatement( /* modifiers */ undefined, /* declarationList */ declList, ); } else { return ts.factory.createFunctionDeclaration( /* modifiers */ [ts.factory.createModifier(ts.SyntaxKind.DeclareKeyword)], /* asteriskToken */ undefined, /* name */ meta.fnName, /* typeParameters */ typeParameters, /* parameters */ [initParam], /* type */ rawType, /* body */ undefined, ); } } /** * Generate an inline type constructor for the given class and metadata. * * An inline type constructor is a specially shaped TypeScript static method, intended to be placed * within a directive class itself, that permits type inference of any generic type parameters of * the class from the types of expressions bound to inputs or outputs, and the types of elements * that match queries performed by the directive. It also catches any errors in the types of these * expressions. This method is never called at runtime, but is used in type-check blocks to * construct directive types. * * An inline type constructor for NgFor looks like: * * static ngTypeCtor<T>(init: Pick<NgForOf<T>, 'ngForOf'|'ngForTrackBy'|'ngForTemplate'>): * NgForOf<T>; * * A typical constructor would be: * * NgForOf.ngTypeCtor(init: { * ngForOf: ['foo', 'bar'], * ngForTrackBy: null as any, * ngForTemplate: null as any, * }); // Infers a type of NgForOf<string>. * * Any inputs declared on the type for which no property binding is present are assigned a value of * type `any`, to avoid producing any type errors for unset inputs. * * Inline type constructors are used when the type being created has bounded generic types which * make writing a declared type constructor (via `generateTypeCtorDeclarationFn`) difficult or * impossible. * * @param node the `ClassDeclaration<ts.ClassDeclaration>` for which a type constructor will be * generated. * @param meta additional metadata required to generate the type constructor. * @returns a `ts.MethodDeclaration` for the type constructor. */ export function generateInlineTypeCtor( env: ReferenceEmitEnvironment, node: ClassDeclaration<ts.ClassDeclaration>, meta: TypeCtorMetadata, ): ts.MethodDeclaration { // Build rawType, a `ts.TypeNode` of the class with its generic parameters passed through from // the definition without any type bounds. For example, if the class is // `FooDirective<T extends Bar>`, its rawType would be `FooDirective<T>`. const rawTypeArgs = node.typeParameters !== undefined ? generateGenericArgs(node.typeParameters) : undefined; const rawType = ts.factory.createTypeReferenceNode(node.name, rawTypeArgs); const initParam = constructTypeCtorParameter(env, meta, rawType); // If this constructor is being generated into a .ts file, then it needs a fake body. The body // is set to a return of `null!`. If the type constructor is being generated into a .d.ts file, // it needs no body. let body: ts.Block | undefined = undefined; if (meta.body) { body = ts.factory.createBlock([ ts.factory.createReturnStatement(ts.factory.createNonNullExpression(ts.factory.createNull())), ]); } // Create the type constructor method declaration. return ts.factory.createMethodDeclaration( /* modifiers */ [ts.factory.createModifier(ts.SyntaxKind.StaticKeyword)], /* asteriskToken */ undefined, /* name */ meta.fnName, /* questionToken */ undefined, /* typeParameters */ typeParametersWithDefaultTypes(node.typeParameters), /* parameters */ [initParam], /* type */ rawType, /* body */ body, ); } function constructTypeCtorParameter( env: ReferenceEmitEnvironment, meta: TypeCtorMetadata, rawType: ts.TypeReferenceNode, ): ts.ParameterDeclaration { // initType is the type of 'init', the single argument to the type constructor method. // If the Directive has any inputs, its initType will be: // // Pick<rawType, 'inputA'|'inputB'> // // Pick here is used to select only those fields from which the generic type parameters of the // directive will be inferred. // // In the special case there are no inputs, initType is set to {}. let initType: ts.TypeNode | null = null; const plainKeys: ts.LiteralTypeNode[] = []; const coercedKeys: ts.PropertySignature[] = []; const signalInputKeys: ts.LiteralTypeNode[] = []; for (const {classPropertyName, transform, isSignal} of meta.fields.inputs) { if (isSignal) { signalInputKeys.push( ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(classPropertyName)), ); } else if (!meta.coercedInputFields.has(classPropertyName)) { plainKeys.push( ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(classPropertyName)), ); } else { const coercionType = transform != null ? transform.type.node : tsCreateTypeQueryForCoercedInput(rawType.typeName, classPropertyName); coercedKeys.push( ts.factory.createPropertySignature( /* modifiers */ undefined, /* name */ classPropertyName, /* questionToken */ undefined, /* type */ coercionType, ), ); } } if (plainKeys.length > 0) { // Construct a union of all the field names. const keyTypeUnion = ts.factory.createUnionTypeNode(plainKeys); // Construct the Pick<rawType, keyTypeUnion>. initType = ts.factory.createTypeReferenceNode('Pick', [rawType, keyTypeUnion]); } if (coercedKeys.length > 0) { const coercedLiteral = ts.factory.createTypeLiteralNode(coercedKeys); initType = initType !== null ? ts.factory.createIntersectionTypeNode([initType, coercedLiteral]) : coercedLiteral; } if (signalInputKeys.length > 0) { const keyTypeUnion = ts.factory.createUnionTypeNode(signalInputKeys); // Construct the UnwrapDirectiveSignalInputs<rawType, keyTypeUnion>. const unwrapDirectiveSignalInputsExpr = env.referenceExternalType( R3Identifiers.UnwrapDirectiveSignalInputs.moduleName, R3Identifiers.UnwrapDirectiveSignalInputs.name, [ // TODO: new ExpressionType(new WrappedNodeExpr(rawType)), new ExpressionType(new WrappedNodeExpr(keyTypeUnion)), ], ); initType = initType !== null ? ts.factory.createIntersectionTypeNode([initType, unwrapDirectiveSignalInputsExpr]) : unwrapDirectiveSignalInputsExpr; } if (initType === null) { // Special case - no inputs, outputs, or other fields which could influence the result type. initType = ts.factory.createTypeLiteralNode([]); } // Create the 'init' parameter itself. return ts.factory.createParameterDeclaration( /* modifiers */ undefined, /* dotDotDotToken */ undefined, /* name */ 'init', /* questionToken */ undefined, /* type */ initType, /* initializer */ undefined, ); }
{ "end_byte": 8619, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts_8621_11252
function generateGenericArgs(params: ReadonlyArray<ts.TypeParameterDeclaration>): ts.TypeNode[] { return params.map((param) => ts.factory.createTypeReferenceNode(param.name, undefined)); } export function requiresInlineTypeCtor( node: ClassDeclaration<ts.ClassDeclaration>, host: ReflectionHost, env: ReferenceEmitEnvironment, ): boolean { // The class requires an inline type constructor if it has generic type bounds that can not be // emitted into the provided type-check environment. return !checkIfGenericTypeBoundsCanBeEmitted(node, host, env); } /** * Add a default `= any` to type parameters that don't have a default value already. * * TypeScript uses the default type of a type parameter whenever inference of that parameter * fails. This can happen when inferring a complex type from 'any'. For example, if `NgFor`'s * inference is done with the TCB code: * * ``` * class NgFor<T> { * ngForOf: T[]; * } * * declare function ctor<T>(o: Pick<NgFor<T>, 'ngForOf'|'ngForTrackBy'|'ngForTemplate'>): * NgFor<T>; * ``` * * An invocation looks like: * * ``` * var _t1 = ctor({ngForOf: [1, 2], ngForTrackBy: null as any, ngForTemplate: null as any}); * ``` * * This correctly infers the type `NgFor<number>` for `_t1`, since `T` is inferred from the * assignment of type `number[]` to `ngForOf`'s type `T[]`. However, if `any` is passed instead: * * ``` * var _t2 = ctor({ngForOf: [1, 2] as any, ngForTrackBy: null as any, ngForTemplate: null as * any}); * ``` * * then inference for `T` fails (it cannot be inferred from `T[] = any`). In this case, `T` * takes the type `{}`, and so `_t2` is inferred as `NgFor<{}>`. This is obviously wrong. * * Adding a default type to the generic declaration in the constructor solves this problem, as * the default type will be used in the event that inference fails. * * ``` * declare function ctor<T = any>(o: Pick<NgFor<T>, 'ngForOf'>): NgFor<T>; * * var _t3 = ctor({ngForOf: [1, 2] as any}); * ``` * * This correctly infers `T` as `any`, and therefore `_t3` as `NgFor<any>`. */ function typeParametersWithDefaultTypes( params: ReadonlyArray<ts.TypeParameterDeclaration> | undefined, ): ts.TypeParameterDeclaration[] | undefined { if (params === undefined) { return undefined; } return params.map((param) => { if (param.default === undefined) { return ts.factory.updateTypeParameterDeclaration( param, param.modifiers, param.name, param.constraint, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } else { return param; } }); }
{ "end_byte": 11252, "start_byte": 8621, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/ts_util.ts_0_6606
/** * @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.dev/license */ import ts from 'typescript'; import {addExpressionIdentifier, ExpressionIdentifier} from './comments'; /** * A `Set` of `ts.SyntaxKind`s of `ts.Expression` which are safe to wrap in a `ts.AsExpression` * without needing to be wrapped in parentheses. * * For example, `foo.bar()` is a `ts.CallExpression`, and can be safely cast to `any` with * `foo.bar() as any`. however, `foo !== bar` is a `ts.BinaryExpression`, and attempting to cast * without the parentheses yields the expression `foo !== bar as any`. This is semantically * equivalent to `foo !== (bar as any)`, which is not what was intended. Thus, * `ts.BinaryExpression`s need to be wrapped in parentheses before casting. */ // const SAFE_TO_CAST_WITHOUT_PARENS: Set<ts.SyntaxKind> = new Set([ // Expressions which are already parenthesized can be cast without further wrapping. ts.SyntaxKind.ParenthesizedExpression, // Expressions which form a single lexical unit leave no room for precedence issues with the cast. ts.SyntaxKind.Identifier, ts.SyntaxKind.CallExpression, ts.SyntaxKind.NonNullExpression, ts.SyntaxKind.ElementAccessExpression, ts.SyntaxKind.PropertyAccessExpression, ts.SyntaxKind.ArrayLiteralExpression, ts.SyntaxKind.ObjectLiteralExpression, // The same goes for various literals. ts.SyntaxKind.StringLiteral, ts.SyntaxKind.NumericLiteral, ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword, ts.SyntaxKind.UndefinedKeyword, ]); export function tsCastToAny(expr: ts.Expression): ts.Expression { // Wrap `expr` in parentheses if needed (see `SAFE_TO_CAST_WITHOUT_PARENS` above). if (!SAFE_TO_CAST_WITHOUT_PARENS.has(expr.kind)) { expr = ts.factory.createParenthesizedExpression(expr); } // The outer expression is always wrapped in parentheses. return ts.factory.createParenthesizedExpression( ts.factory.createAsExpression(expr, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)), ); } /** * Create an expression which instantiates an element by its HTML tagName. * * Thanks to narrowing of `document.createElement()`, this expression will have its type inferred * based on the tag name, including for custom elements that have appropriate .d.ts definitions. */ export function tsCreateElement(tagName: string): ts.Expression { const createElement = ts.factory.createPropertyAccessExpression( /* expression */ ts.factory.createIdentifier('document'), 'createElement', ); return ts.factory.createCallExpression( /* expression */ createElement, /* typeArguments */ undefined, /* argumentsArray */ [ts.factory.createStringLiteral(tagName)], ); } /** * Create a `ts.VariableStatement` which declares a variable without explicit initialization. * * The initializer `null!` is used to bypass strict variable initialization checks. * * Unlike with `tsCreateVariable`, the type of the variable is explicitly specified. */ export function tsDeclareVariable(id: ts.Identifier, type: ts.TypeNode): ts.VariableStatement { // When we create a variable like `var _t1: boolean = null!`, TypeScript actually infers `_t1` // to be `never`, instead of a `boolean`. To work around it, we cast the value // in the initializer, e.g. `var _t1 = null! as boolean;`. addExpressionIdentifier(type, ExpressionIdentifier.VARIABLE_AS_EXPRESSION); const initializer: ts.Expression = ts.factory.createAsExpression( ts.factory.createNonNullExpression(ts.factory.createNull()), type, ); const decl = ts.factory.createVariableDeclaration( /* name */ id, /* exclamationToken */ undefined, /* type */ undefined, /* initializer */ initializer, ); return ts.factory.createVariableStatement( /* modifiers */ undefined, /* declarationList */ [decl], ); } /** * Creates a `ts.TypeQueryNode` for a coerced input. * * For example: `typeof MatInput.ngAcceptInputType_value`, where MatInput is `typeName` and `value` * is the `coercedInputName`. * * @param typeName The `EntityName` of the Directive where the static coerced input is defined. * @param coercedInputName The field name of the coerced input. */ export function tsCreateTypeQueryForCoercedInput( typeName: ts.EntityName, coercedInputName: string, ): ts.TypeQueryNode { return ts.factory.createTypeQueryNode( ts.factory.createQualifiedName(typeName, `ngAcceptInputType_${coercedInputName}`), ); } /** * Create a `ts.VariableStatement` that initializes a variable with a given expression. * * Unlike with `tsDeclareVariable`, the type of the variable is inferred from the initializer * expression. */ export function tsCreateVariable( id: ts.Identifier, initializer: ts.Expression, flags: ts.NodeFlags | null = null, ): ts.VariableStatement { const decl = ts.factory.createVariableDeclaration( /* name */ id, /* exclamationToken */ undefined, /* type */ undefined, /* initializer */ initializer, ); return ts.factory.createVariableStatement( /* modifiers */ undefined, /* declarationList */ flags === null ? [decl] : ts.factory.createVariableDeclarationList([decl], flags), ); } /** * Construct a `ts.CallExpression` that calls a method on a receiver. */ export function tsCallMethod( receiver: ts.Expression, methodName: string, args: ts.Expression[] = [], ): ts.CallExpression { const methodAccess = ts.factory.createPropertyAccessExpression(receiver, methodName); return ts.factory.createCallExpression( /* expression */ methodAccess, /* typeArguments */ undefined, /* argumentsArray */ args, ); } export function isAccessExpression( node: ts.Node, ): node is ts.ElementAccessExpression | ts.PropertyAccessExpression { return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node); } /** * Creates a TypeScript node representing a numeric value. */ export function tsNumericExpression(value: number): ts.NumericLiteral | ts.PrefixUnaryExpression { // As of TypeScript 5.3 negative numbers are represented as `prefixUnaryOperator` and passing a // negative number (even as a string) into `createNumericLiteral` will result in an error. if (value < 0) { const operand = ts.factory.createNumericLiteral(Math.abs(value)); return ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, operand); } return ts.factory.createNumericLiteral(value); }
{ "end_byte": 6606, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/ts_util.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.ts_0_4546
/** * @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.dev/license */ import {AbsoluteSourceSpan, ParseSourceSpan} from '@angular/compiler'; import ts from 'typescript'; import {TemplateDiagnostic, TemplateId} from '../api'; import {makeTemplateDiagnostic} from '../diagnostics'; import {getTemplateMapping, TemplateSourceResolver} from './tcb_util'; /** * Wraps the node in parenthesis such that inserted span comments become attached to the proper * node. This is an alias for `ts.factory.createParenthesizedExpression` with the benefit that it * signifies that the inserted parenthesis are for diagnostic purposes, not for correctness of the * rendered TCB code. * * Note that it is important that nodes and its attached comment are not wrapped into parenthesis * by default, as it prevents correct translation of e.g. diagnostics produced for incorrect method * arguments. Such diagnostics would then be produced for the parenthesised node whereas the * positional comment would be located within that node, resulting in a mismatch. */ export function wrapForDiagnostics(expr: ts.Expression): ts.Expression { return ts.factory.createParenthesizedExpression(expr); } /** * Wraps the node in parenthesis such that inserted span comments become attached to the proper * node. This is an alias for `ts.factory.createParenthesizedExpression` with the benefit that it * signifies that the inserted parenthesis are for use by the type checker, not for correctness of * the rendered TCB code. */ export function wrapForTypeChecker(expr: ts.Expression): ts.Expression { return ts.factory.createParenthesizedExpression(expr); } /** * Adds a synthetic comment to the expression that represents the parse span of the provided node. * This comment can later be retrieved as trivia of a node to recover original source locations. */ export function addParseSpanInfo(node: ts.Node, span: AbsoluteSourceSpan | ParseSourceSpan): void { let commentText: string; if (span instanceof AbsoluteSourceSpan) { commentText = `${span.start},${span.end}`; } else { commentText = `${span.start.offset},${span.end.offset}`; } ts.addSyntheticTrailingComment( node, ts.SyntaxKind.MultiLineCommentTrivia, commentText, /* hasTrailingNewLine */ false, ); } /** * Adds a synthetic comment to the function declaration that contains the template id * of the class declaration. */ export function addTemplateId(tcb: ts.FunctionDeclaration, id: TemplateId): void { ts.addSyntheticLeadingComment(tcb, ts.SyntaxKind.MultiLineCommentTrivia, id, true); } /** * Determines if the diagnostic should be reported. Some diagnostics are produced because of the * way TCBs are generated; those diagnostics should not be reported as type check errors of the * template. */ export function shouldReportDiagnostic(diagnostic: ts.Diagnostic): boolean { const {code} = diagnostic; if (code === 6133 /* $var is declared but its value is never read. */) { return false; } else if (code === 6199 /* All variables are unused. */) { return false; } else if (code === 2695 /* Left side of comma operator is unused and has no side effects. */) { return false; } else if (code === 7006 /* Parameter '$event' implicitly has an 'any' type. */) { return false; } return true; } /** * Attempts to translate a TypeScript diagnostic produced during template type-checking to their * location of origin, based on the comments that are emitted in the TCB code. * * If the diagnostic could not be translated, `null` is returned to indicate that the diagnostic * should not be reported at all. This prevents diagnostics from non-TCB code in a user's source * file from being reported as type-check errors. */ export function translateDiagnostic( diagnostic: ts.Diagnostic, resolver: TemplateSourceResolver, ): TemplateDiagnostic | null { if (diagnostic.file === undefined || diagnostic.start === undefined) { return null; } const fullMapping = getTemplateMapping( diagnostic.file, diagnostic.start, resolver, /*isDiagnosticsRequest*/ true, ); if (fullMapping === null) { return null; } const {sourceLocation, templateSourceMapping, span} = fullMapping; return makeTemplateDiagnostic( sourceLocation.id, templateSourceMapping, span, diagnostic.category, diagnostic.code, diagnostic.messageText, ); }
{ "end_byte": 4546, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_0_7611
/** * @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.dev/license */ import { AST, BindingPipe, BindingType, BoundTarget, Call, createCssSelectorFromNode, CssSelector, DYNAMIC_TYPE, ImplicitReceiver, ParsedEventType, ParseSourceSpan, PropertyRead, PropertyWrite, R3Identifiers, SafeCall, SafePropertyRead, SchemaMetadata, SelectorMatcher, TemplateEntity, ThisReceiver, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstContent, TmplAstDeferredBlock, TmplAstDeferredBlockTriggers, TmplAstElement, TmplAstForLoopBlock, TmplAstForLoopBlockEmpty, TmplAstHoverDeferredTrigger, TmplAstIcu, TmplAstIfBlock, TmplAstIfBlockBranch, TmplAstInteractionDeferredTrigger, TmplAstLetDeclaration, TmplAstNode, TmplAstReference, TmplAstSwitchBlock, TmplAstSwitchBlockCase, TmplAstTemplate, TmplAstText, TmplAstTextAttribute, TmplAstVariable, TmplAstViewportDeferredTrigger, TransplantedType, } from '@angular/compiler'; import ts from 'typescript'; import {Reference} from '../../imports'; import {BindingPropertyName, ClassPropertyName, PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {TemplateId, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata} from '../api'; import {addExpressionIdentifier, ExpressionIdentifier, markIgnoreDiagnostics} from './comments'; import { addParseSpanInfo, addTemplateId, wrapForDiagnostics, wrapForTypeChecker, } from './diagnostics'; import {DomSchemaChecker} from './dom'; import {Environment} from './environment'; import {astToTypescript, ANY_EXPRESSION} from './expression'; import {OutOfBandDiagnosticRecorder} from './oob'; import { tsCallMethod, tsCastToAny, tsCreateElement, tsCreateTypeQueryForCoercedInput, tsCreateVariable, tsDeclareVariable, } from './ts_util'; import {requiresInlineTypeCtor} from './type_constructor'; import {TypeParameterEmitter} from './type_parameter_emitter'; /** * Controls how generics for the component context class will be handled during TCB generation. */ export enum TcbGenericContextBehavior { /** * References to generic parameter bounds will be emitted via the `TypeParameterEmitter`. * * The caller must verify that all parameter bounds are emittable in order to use this mode. */ UseEmitter, /** * Generic parameter declarations will be copied directly from the `ts.ClassDeclaration` of the * component class. * * The caller must only use the generated TCB code in a context where such copies will still be * valid, such as an inline type check block. */ CopyClassNodes, /** * Any generic parameters for the component context class will be set to `any`. * * Produces a less useful type, but is always safe to use. */ FallbackToAny, } /** * Given a `ts.ClassDeclaration` for a component, and metadata regarding that component, compose a * "type check block" function. * * When passed through TypeScript's TypeChecker, type errors that arise within the type check block * function indicate issues in the template itself. * * As a side effect of generating a TCB for the component, `ts.Diagnostic`s may also be produced * directly for issues within the template which are identified during generation. These issues are * recorded in either the `domSchemaChecker` (which checks usage of DOM elements and bindings) as * well as the `oobRecorder` (which records errors when the type-checking code generator is unable * to sufficiently understand a template). * * @param env an `Environment` into which type-checking code will be generated. * @param ref a `Reference` to the component class which should be type-checked. * @param name a `ts.Identifier` to use for the generated `ts.FunctionDeclaration`. * @param meta metadata about the component's template and the function being generated. * @param domSchemaChecker used to check and record errors regarding improper usage of DOM elements * and bindings. * @param oobRecorder used to record errors regarding template elements which could not be correctly * translated into types during TCB generation. * @param genericContextBehavior controls how generic parameters (especially parameters with generic * bounds) will be referenced from the generated TCB code. */ export function generateTypeCheckBlock( env: Environment, ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, name: ts.Identifier, meta: TypeCheckBlockMetadata, domSchemaChecker: DomSchemaChecker, oobRecorder: OutOfBandDiagnosticRecorder, genericContextBehavior: TcbGenericContextBehavior, ): ts.FunctionDeclaration { const tcb = new Context( env, domSchemaChecker, oobRecorder, meta.id, meta.boundTarget, meta.pipes, meta.schemas, meta.isStandalone, meta.preserveWhitespaces, ); const scope = Scope.forNodes(tcb, null, null, tcb.boundTarget.target.template!, /* guard */ null); const ctxRawType = env.referenceType(ref); if (!ts.isTypeReferenceNode(ctxRawType)) { throw new Error( `Expected TypeReferenceNode when referencing the ctx param for ${ref.debugName}`, ); } let typeParameters: ts.TypeParameterDeclaration[] | undefined = undefined; let typeArguments: ts.TypeNode[] | undefined = undefined; if (ref.node.typeParameters !== undefined) { if (!env.config.useContextGenericType) { genericContextBehavior = TcbGenericContextBehavior.FallbackToAny; } switch (genericContextBehavior) { case TcbGenericContextBehavior.UseEmitter: // Guaranteed to emit type parameters since we checked that the class has them above. typeParameters = new TypeParameterEmitter(ref.node.typeParameters, env.reflector).emit( (typeRef) => env.referenceType(typeRef), )!; typeArguments = typeParameters.map((param) => ts.factory.createTypeReferenceNode(param.name), ); break; case TcbGenericContextBehavior.CopyClassNodes: typeParameters = [...ref.node.typeParameters]; typeArguments = typeParameters.map((param) => ts.factory.createTypeReferenceNode(param.name), ); break; case TcbGenericContextBehavior.FallbackToAny: typeArguments = ref.node.typeParameters.map(() => ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); break; } } const paramList = [tcbThisParam(ctxRawType.typeName, typeArguments)]; const scopeStatements = scope.render(); const innerBody = ts.factory.createBlock([...env.getPreludeStatements(), ...scopeStatements]); // Wrap the body in an "if (true)" expression. This is unnecessary but has the effect of causing // the `ts.Printer` to format the type-check block nicely. const body = ts.factory.createBlock([ ts.factory.createIfStatement(ts.factory.createTrue(), innerBody, undefined), ]); const fnDecl = ts.factory.createFunctionDeclaration( /* modifiers */ undefined, /* asteriskToken */ undefined, /* name */ name, /* typeParameters */ env.config.useContextGenericType ? typeParameters : undefined, /* parameters */ paramList, /* type */ undefined, /* body */ body, ); addTemplateId(fnDecl, meta.id); return fnDecl; } /** Types that can referenced locally in a template. */ type LocalSymbol = | TmplAstElement | TmplAstTemplate | TmplAstVariable | TmplAstLetDeclaration | TmplAstReference;
{ "end_byte": 7611, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_7613_14365
/** * A code generation operation that's involved in the construction of a Type Check Block. * * The generation of a TCB is non-linear. Bindings within a template may result in the need to * construct certain types earlier than they otherwise would be constructed. That is, if the * generation of a TCB for a template is broken down into specific operations (constructing a * directive, extracting a variable from a let- operation, etc), then it's possible for operations * earlier in the sequence to depend on operations which occur later in the sequence. * * `TcbOp` abstracts the different types of operations which are required to convert a template into * a TCB. This allows for two phases of processing for the template, where 1) a linear sequence of * `TcbOp`s is generated, and then 2) these operations are executed, not necessarily in linear * order. * * Each `TcbOp` may insert statements into the body of the TCB, and also optionally return a * `ts.Expression` which can be used to reference the operation's result. */ abstract class TcbOp { /** * Set to true if this operation can be considered optional. Optional operations are only executed * when depended upon by other operations, otherwise they are disregarded. This allows for less * code to generate, parse and type-check, overall positively contributing to performance. */ abstract readonly optional: boolean; abstract execute(): ts.Expression | null; /** * Replacement value or operation used while this `TcbOp` is executing (i.e. to resolve circular * references during its execution). * * This is usually a `null!` expression (which asks TS to infer an appropriate type), but another * `TcbOp` can be returned in cases where additional code generation is necessary to deal with * circular references. */ circularFallback(): TcbOp | ts.Expression { return INFER_TYPE_FOR_CIRCULAR_OP_EXPR; } } /** * A `TcbOp` which creates an expression for a native DOM element (or web component) from a * `TmplAstElement`. * * Executing this operation returns a reference to the element variable. */ class TcbElementOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private element: TmplAstElement, ) { super(); } override get optional() { // The statement generated by this operation is only used for type-inference of the DOM // element's type and won't report diagnostics by itself, so the operation is marked as optional // to avoid generating statements for DOM elements that are never referenced. return true; } override execute(): ts.Identifier { const id = this.tcb.allocateId(); // Add the declaration of the element using document.createElement. const initializer = tsCreateElement(this.element.name); addParseSpanInfo(initializer, this.element.startSourceSpan || this.element.sourceSpan); this.scope.addStatement(tsCreateVariable(id, initializer)); return id; } } /** * A `TcbOp` which creates an expression for particular let- `TmplAstVariable` on a * `TmplAstTemplate`'s context. * * Executing this operation returns a reference to the variable variable (lol). */ class TcbTemplateVariableOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private template: TmplAstTemplate, private variable: TmplAstVariable, ) { super(); } override get optional() { return false; } override execute(): ts.Identifier { // Look for a context variable for the template. const ctx = this.scope.resolve(this.template); // Allocate an identifier for the TmplAstVariable, and initialize it to a read of the variable // on the template context. const id = this.tcb.allocateId(); const initializer = ts.factory.createPropertyAccessExpression( /* expression */ ctx, /* name */ this.variable.value || '$implicit', ); addParseSpanInfo(id, this.variable.keySpan); // Declare the variable, and return its identifier. let variable: ts.VariableStatement; if (this.variable.valueSpan !== undefined) { addParseSpanInfo(initializer, this.variable.valueSpan); variable = tsCreateVariable(id, wrapForTypeChecker(initializer)); } else { variable = tsCreateVariable(id, initializer); } addParseSpanInfo(variable.declarationList.declarations[0], this.variable.sourceSpan); this.scope.addStatement(variable); return id; } } /** * A `TcbOp` which generates a variable for a `TmplAstTemplate`'s context. * * Executing this operation returns a reference to the template's context variable. */ class TcbTemplateContextOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, ) { super(); } // The declaration of the context variable is only needed when the context is actually referenced. override readonly optional = true; override execute(): ts.Identifier { // Allocate a template ctx variable and declare it with an 'any' type. The type of this variable // may be narrowed as a result of template guard conditions. const ctx = this.tcb.allocateId(); const type = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); this.scope.addStatement(tsDeclareVariable(ctx, type)); return ctx; } } /** * A `TcbOp` which generates a constant for a `TmplAstLetDeclaration`. * * Executing this operation returns a reference to the `@let` declaration. */ class TcbLetDeclarationOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstLetDeclaration, ) { super(); } /** * `@let` declarations are mandatory, because their expressions * should be checked even if they aren't referenced anywhere. */ override readonly optional = false; override execute(): ts.Identifier { const id = this.tcb.allocateId(); addParseSpanInfo(id, this.node.nameSpan); const value = tcbExpression(this.node.value, this.tcb, this.scope); // Value needs to be wrapped, because spans for the expressions inside of it can // be picked up incorrectly as belonging to the full variable declaration. const varStatement = tsCreateVariable(id, wrapForTypeChecker(value), ts.NodeFlags.Const); addParseSpanInfo(varStatement.declarationList.declarations[0], this.node.sourceSpan); this.scope.addStatement(varStatement); return id; } } /** * A `TcbOp` which descends into a `TmplAstTemplate`'s children and generates type-checking code for * them. * * This operation wraps the children's type-checking code in an `if` block, which may include one * or more type guard conditions that narrow types within the template body. */
{ "end_byte": 14365, "start_byte": 7613, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_14366_23275
class TcbTemplateBodyOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private template: TmplAstTemplate, ) { super(); } override get optional() { return false; } override execute(): null { // An `if` will be constructed, within which the template's children will be type checked. The // `if` is used for two reasons: it creates a new syntactic scope, isolating variables declared // in the template's TCB from the outer context, and it allows any directives on the templates // to perform type narrowing of either expressions or the template's context. // // The guard is the `if` block's condition. It's usually set to `true` but directives that exist // on the template can trigger extra guard expressions that serve to narrow types within the // `if`. `guard` is calculated by starting with `true` and adding other conditions as needed. // Collect these into `guards` by processing the directives. const directiveGuards: ts.Expression[] = []; const directives = this.tcb.boundTarget.getDirectivesOfNode(this.template); if (directives !== null) { for (const dir of directives) { const dirInstId = this.scope.resolve(this.template, dir); const dirId = this.tcb.env.reference( dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>, ); // There are two kinds of guards. Template guards (ngTemplateGuards) allow type narrowing of // the expression passed to an @Input of the directive. Scan the directive to see if it has // any template guards, and generate them if needed. dir.ngTemplateGuards.forEach((guard) => { // For each template guard function on the directive, look for a binding to that input. const boundInput = this.template.inputs.find((i) => i.name === guard.inputName) || this.template.templateAttrs.find( (i: TmplAstTextAttribute | TmplAstBoundAttribute): i is TmplAstBoundAttribute => i instanceof TmplAstBoundAttribute && i.name === guard.inputName, ); if (boundInput !== undefined) { // If there is such a binding, generate an expression for it. const expr = tcbExpression(boundInput.value, this.tcb, this.scope); // The expression has already been checked in the type constructor invocation, so // it should be ignored when used within a template guard. markIgnoreDiagnostics(expr); if (guard.type === 'binding') { // Use the binding expression itself as guard. directiveGuards.push(expr); } else { // Call the guard function on the directive with the directive instance and that // expression. const guardInvoke = tsCallMethod(dirId, `ngTemplateGuard_${guard.inputName}`, [ dirInstId, expr, ]); addParseSpanInfo(guardInvoke, boundInput.value.sourceSpan); directiveGuards.push(guardInvoke); } } }); // The second kind of guard is a template context guard. This guard narrows the template // rendering context variable `ctx`. if (dir.hasNgTemplateContextGuard) { if (this.tcb.env.config.applyTemplateContextGuards) { const ctx = this.scope.resolve(this.template); const guardInvoke = tsCallMethod(dirId, 'ngTemplateContextGuard', [dirInstId, ctx]); addParseSpanInfo(guardInvoke, this.template.sourceSpan); directiveGuards.push(guardInvoke); } else if ( this.template.variables.length > 0 && this.tcb.env.config.suggestionsForSuboptimalTypeInference ) { // The compiler could have inferred a better type for the variables in this template, // but was prevented from doing so by the type-checking configuration. Issue a warning // diagnostic. this.tcb.oobRecorder.suboptimalTypeInference(this.tcb.id, this.template.variables); } } } } // By default the guard is simply `true`. let guard: ts.Expression | null = null; // If there are any guards from directives, use them instead. if (directiveGuards.length > 0) { // Pop the first value and use it as the initializer to reduce(). This way, a single guard // will be used on its own, but two or more will be combined into binary AND expressions. guard = directiveGuards.reduce( (expr, dirGuard) => ts.factory.createBinaryExpression(expr, ts.SyntaxKind.AmpersandAmpersandToken, dirGuard), directiveGuards.pop()!, ); } // Create a new Scope for the template. This constructs the list of operations for the template // children, as well as tracks bindings within the template. const tmplScope = Scope.forNodes( this.tcb, this.scope, this.template, this.template.children, guard, ); // Render the template's `Scope` into its statements. const statements = tmplScope.render(); if (statements.length === 0) { // As an optimization, don't generate the scope's block if it has no statements. This is // beneficial for templates that contain for example `<span *ngIf="first"></span>`, in which // case there's no need to render the `NgIf` guard expression. This seems like a minor // improvement, however it reduces the number of flow-node antecedents that TypeScript needs // to keep into account for such cases, resulting in an overall reduction of // type-checking time. return null; } let tmplBlock: ts.Statement = ts.factory.createBlock(statements); if (guard !== null) { // The scope has a guard that needs to be applied, so wrap the template block into an `if` // statement containing the guard expression. tmplBlock = ts.factory.createIfStatement( /* expression */ guard, /* thenStatement */ tmplBlock, ); } this.scope.addStatement(tmplBlock); return null; } } /** * A `TcbOp` which renders an Angular expression (e.g. `{{foo() && bar.baz}}`). * * Executing this operation returns nothing. */ class TcbExpressionOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private expression: AST, ) { super(); } override get optional() { return false; } override execute(): null { const expr = tcbExpression(this.expression, this.tcb, this.scope); this.scope.addStatement(ts.factory.createExpressionStatement(expr)); return null; } } /** * A `TcbOp` which constructs an instance of a directive. For generic directives, generic * parameters are set to `any` type. */ abstract class TcbDirectiveTypeOpBase extends TcbOp { constructor( protected tcb: Context, protected scope: Scope, protected node: TmplAstTemplate | TmplAstElement, protected dir: TypeCheckableDirectiveMeta, ) { super(); } override get optional() { // The statement generated by this operation is only used to declare the directive's type and // won't report diagnostics by itself, so the operation is marked as optional to avoid // generating declarations for directives that don't have any inputs/outputs. return true; } override execute(): ts.Identifier { const dirRef = this.dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>; const rawType = this.tcb.env.referenceType(this.dir.ref); let type: ts.TypeNode; if (this.dir.isGeneric === false || dirRef.node.typeParameters === undefined) { type = rawType; } else { if (!ts.isTypeReferenceNode(rawType)) { throw new Error( `Expected TypeReferenceNode when referencing the type for ${this.dir.ref.debugName}`, ); } const typeArguments = dirRef.node.typeParameters.map(() => ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); type = ts.factory.createTypeReferenceNode(rawType.typeName, typeArguments); } const id = this.tcb.allocateId(); addExpressionIdentifier(id, ExpressionIdentifier.DIRECTIVE); addParseSpanInfo(id, this.node.startSourceSpan || this.node.sourceSpan); this.scope.addStatement(tsDeclareVariable(id, type)); return id; } } /** * A `TcbOp` which constructs an instance of a non-generic directive _without_ setting any of its * inputs. Inputs are later set in the `TcbDirectiveInputsOp`. Type checking was found to be * faster when done in this way as opposed to `TcbDirectiveCtorOp` which is only necessary when the * directive is generic. * * Executing this operation returns a reference to the directive instance variable with its inferred * type. */
{ "end_byte": 23275, "start_byte": 14366, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_23276_31896
class TcbNonGenericDirectiveTypeOp extends TcbDirectiveTypeOpBase { /** * Creates a variable declaration for this op's directive of the argument type. Returns the id of * the newly created variable. */ override execute(): ts.Identifier { const dirRef = this.dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>; if (this.dir.isGeneric) { throw new Error(`Assertion Error: expected ${dirRef.debugName} not to be generic.`); } return super.execute(); } } /** * A `TcbOp` which constructs an instance of a generic directive with its generic parameters set * to `any` type. This op is like `TcbDirectiveTypeOp`, except that generic parameters are set to * `any` type. This is used for situations where we want to avoid inlining. * * Executing this operation returns a reference to the directive instance variable with its generic * type parameters set to `any`. */ class TcbGenericDirectiveTypeWithAnyParamsOp extends TcbDirectiveTypeOpBase { override execute(): ts.Identifier { const dirRef = this.dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>; if (dirRef.node.typeParameters === undefined) { throw new Error( `Assertion Error: expected typeParameters when creating a declaration for ${dirRef.debugName}`, ); } return super.execute(); } } /** * A `TcbOp` which creates a variable for a local ref in a template. * The initializer for the variable is the variable expression for the directive, template, or * element the ref refers to. When the reference is used in the template, those TCB statements will * access this variable as well. For example: * ``` * var _t1 = document.createElement('div'); * var _t2 = _t1; * _t2.value * ``` * This operation supports more fluent lookups for the `TemplateTypeChecker` when getting a symbol * for a reference. In most cases, this isn't essential; that is, the information for the symbol * could be gathered without this operation using the `BoundTarget`. However, for the case of * ng-template references, we will need this reference variable to not only provide a location in * the shim file, but also to narrow the variable to the correct `TemplateRef<T>` type rather than * `TemplateRef<any>` (this work is still TODO). * * Executing this operation returns a reference to the directive instance variable with its inferred * type. */ class TcbReferenceOp extends TcbOp { constructor( private readonly tcb: Context, private readonly scope: Scope, private readonly node: TmplAstReference, private readonly host: TmplAstElement | TmplAstTemplate, private readonly target: TypeCheckableDirectiveMeta | TmplAstTemplate | TmplAstElement, ) { super(); } // The statement generated by this operation is only used to for the Type Checker // so it can map a reference variable in the template directly to a node in the TCB. override readonly optional = true; override execute(): ts.Identifier { const id = this.tcb.allocateId(); let initializer: ts.Expression = this.target instanceof TmplAstTemplate || this.target instanceof TmplAstElement ? this.scope.resolve(this.target) : this.scope.resolve(this.host, this.target); // The reference is either to an element, an <ng-template> node, or to a directive on an // element or template. if ( (this.target instanceof TmplAstElement && !this.tcb.env.config.checkTypeOfDomReferences) || !this.tcb.env.config.checkTypeOfNonDomReferences ) { // References to DOM nodes are pinned to 'any' when `checkTypeOfDomReferences` is `false`. // References to `TemplateRef`s and directives are pinned to 'any' when // `checkTypeOfNonDomReferences` is `false`. initializer = ts.factory.createAsExpression( initializer, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } else if (this.target instanceof TmplAstTemplate) { // Direct references to an <ng-template> node simply require a value of type // `TemplateRef<any>`. To get this, an expression of the form // `(_t1 as any as TemplateRef<any>)` is constructed. initializer = ts.factory.createAsExpression( initializer, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); initializer = ts.factory.createAsExpression( initializer, this.tcb.env.referenceExternalType('@angular/core', 'TemplateRef', [DYNAMIC_TYPE]), ); initializer = ts.factory.createParenthesizedExpression(initializer); } addParseSpanInfo(initializer, this.node.sourceSpan); addParseSpanInfo(id, this.node.keySpan); this.scope.addStatement(tsCreateVariable(id, initializer)); return id; } } /** * A `TcbOp` which is used when the target of a reference is missing. This operation generates a * variable of type any for usages of the invalid reference to resolve to. The invalid reference * itself is recorded out-of-band. */ class TcbInvalidReferenceOp extends TcbOp { constructor( private readonly tcb: Context, private readonly scope: Scope, ) { super(); } // The declaration of a missing reference is only needed when the reference is resolved. override readonly optional = true; override execute(): ts.Identifier { const id = this.tcb.allocateId(); this.scope.addStatement(tsCreateVariable(id, ANY_EXPRESSION)); return id; } } /** * A `TcbOp` which constructs an instance of a directive with types inferred from its inputs. The * inputs themselves are not checked here; checking of inputs is achieved in `TcbDirectiveInputsOp`. * Any errors reported in this statement are ignored, as the type constructor call is only present * for type-inference. * * When a Directive is generic, it is required that the TCB generates the instance using this method * in order to infer the type information correctly. * * Executing this operation returns a reference to the directive instance variable with its inferred * type. */ class TcbDirectiveCtorOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstTemplate | TmplAstElement, private dir: TypeCheckableDirectiveMeta, ) { super(); } override get optional() { // The statement generated by this operation is only used to infer the directive's type and // won't report diagnostics by itself, so the operation is marked as optional. return true; } override execute(): ts.Identifier { const id = this.tcb.allocateId(); addExpressionIdentifier(id, ExpressionIdentifier.DIRECTIVE); addParseSpanInfo(id, this.node.startSourceSpan || this.node.sourceSpan); const genericInputs = new Map<string, TcbDirectiveInput>(); const boundAttrs = getBoundAttributes(this.dir, this.node); for (const attr of boundAttrs) { // Skip text attributes if configured to do so. if ( !this.tcb.env.config.checkTypeOfAttributes && attr.attribute instanceof TmplAstTextAttribute ) { continue; } for (const {fieldName, isTwoWayBinding} of attr.inputs) { // Skip the field if an attribute has already been bound to it; we can't have a duplicate // key in the type constructor call. if (genericInputs.has(fieldName)) { continue; } const expression = translateInput(attr.attribute, this.tcb, this.scope); genericInputs.set(fieldName, { type: 'binding', field: fieldName, expression, sourceSpan: attr.attribute.sourceSpan, isTwoWayBinding, }); } } // Add unset directive inputs for each of the remaining unset fields. for (const {classPropertyName} of this.dir.inputs) { if (!genericInputs.has(classPropertyName)) { genericInputs.set(classPropertyName, {type: 'unset', field: classPropertyName}); } } // Call the type constructor of the directive to infer a type, and assign the directive // instance. const typeCtor = tcbCallTypeCtor(this.dir, this.tcb, Array.from(genericInputs.values())); markIgnoreDiagnostics(typeCtor); this.scope.addStatement(tsCreateVariable(id, typeCtor)); return id; } override circularFallback(): TcbOp { return new TcbDirectiveCtorCircularFallbackOp(this.tcb, this.scope, this.node, this.dir); } } /** * A `TcbOp` which generates code to check input bindings on an element that correspond with the * members of a directive. * * Executing this operation returns nothing. */
{ "end_byte": 31896, "start_byte": 23276, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_31897_40893
class TcbDirectiveInputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstTemplate | TmplAstElement, private dir: TypeCheckableDirectiveMeta, ) { super(); } override get optional() { return false; } override execute(): null { let dirId: ts.Expression | null = null; // TODO(joost): report duplicate properties const boundAttrs = getBoundAttributes(this.dir, this.node); const seenRequiredInputs = new Set<ClassPropertyName>(); for (const attr of boundAttrs) { // For bound inputs, the property is assigned the binding expression. const expr = widenBinding(translateInput(attr.attribute, this.tcb, this.scope), this.tcb); let assignment: ts.Expression = wrapForDiagnostics(expr); for (const {fieldName, required, transformType, isSignal, isTwoWayBinding} of attr.inputs) { let target: ts.LeftHandSideExpression; if (required) { seenRequiredInputs.add(fieldName); } // Note: There is no special logic for transforms/coercion with signal inputs. // For signal inputs, a `transformType` will never be set as we do not capture // the transform in the compiler metadata. Signal inputs incorporate their // transform write type into their member type, and we extract it below when // setting the `WriteT` of such `InputSignalWithTransform<_, WriteT>`. if (this.dir.coercedInputFields.has(fieldName)) { let type: ts.TypeNode; if (transformType !== null) { type = this.tcb.env.referenceTransplantedType(new TransplantedType(transformType)); } else { // The input has a coercion declaration which should be used instead of assigning the // expression into the input field directly. To achieve this, a variable is declared // with a type of `typeof Directive.ngAcceptInputType_fieldName` which is then used as // target of the assignment. const dirTypeRef: ts.TypeNode = this.tcb.env.referenceType(this.dir.ref); if (!ts.isTypeReferenceNode(dirTypeRef)) { throw new Error( `Expected TypeReferenceNode from reference to ${this.dir.ref.debugName}`, ); } type = tsCreateTypeQueryForCoercedInput(dirTypeRef.typeName, fieldName); } const id = this.tcb.allocateId(); this.scope.addStatement(tsDeclareVariable(id, type)); target = id; } else if (this.dir.undeclaredInputFields.has(fieldName)) { // If no coercion declaration is present nor is the field declared (i.e. the input is // declared in a `@Directive` or `@Component` decorator's `inputs` property) there is no // assignment target available, so this field is skipped. continue; } else if ( !this.tcb.env.config.honorAccessModifiersForInputBindings && this.dir.restrictedInputFields.has(fieldName) ) { // If strict checking of access modifiers is disabled and the field is restricted // (i.e. private/protected/readonly), generate an assignment into a temporary variable // that has the type of the field. This achieves type-checking but circumvents the access // modifiers. if (dirId === null) { dirId = this.scope.resolve(this.node, this.dir); } const id = this.tcb.allocateId(); const dirTypeRef = this.tcb.env.referenceType(this.dir.ref); if (!ts.isTypeReferenceNode(dirTypeRef)) { throw new Error( `Expected TypeReferenceNode from reference to ${this.dir.ref.debugName}`, ); } const type = ts.factory.createIndexedAccessTypeNode( ts.factory.createTypeQueryNode(dirId as ts.Identifier), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(fieldName)), ); const temp = tsDeclareVariable(id, type); this.scope.addStatement(temp); target = id; } else { if (dirId === null) { dirId = this.scope.resolve(this.node, this.dir); } // To get errors assign directly to the fields on the instance, using property access // when possible. String literal fields may not be valid JS identifiers so we use // literal element access instead for those cases. target = this.dir.stringLiteralInputFields.has(fieldName) ? ts.factory.createElementAccessExpression( dirId, ts.factory.createStringLiteral(fieldName), ) : ts.factory.createPropertyAccessExpression( dirId, ts.factory.createIdentifier(fieldName), ); } // For signal inputs, we unwrap the target `InputSignal`. Note that // we intentionally do the following things: // 1. keep the direct access to `dir.[field]` so that modifiers are honored. // 2. follow the existing pattern where multiple targets assign a single expression. // This is a significant requirement for language service auto-completion. if (isSignal) { const inputSignalBrandWriteSymbol = this.tcb.env.referenceExternalSymbol( R3Identifiers.InputSignalBrandWriteType.moduleName, R3Identifiers.InputSignalBrandWriteType.name, ); if ( !ts.isIdentifier(inputSignalBrandWriteSymbol) && !ts.isPropertyAccessExpression(inputSignalBrandWriteSymbol) ) { throw new Error( `Expected identifier or property access for reference to ${R3Identifiers.InputSignalBrandWriteType.name}`, ); } target = ts.factory.createElementAccessExpression(target, inputSignalBrandWriteSymbol); } if (attr.attribute.keySpan !== undefined) { addParseSpanInfo(target, attr.attribute.keySpan); } // Two-way bindings accept `T | WritableSignal<T>` so we have to unwrap the value. if (isTwoWayBinding && this.tcb.env.config.allowSignalsInTwoWayBindings) { assignment = unwrapWritableSignal(assignment, this.tcb); } // Finally the assignment is extended by assigning it into the target expression. assignment = ts.factory.createBinaryExpression( target, ts.SyntaxKind.EqualsToken, assignment, ); } addParseSpanInfo(assignment, attr.attribute.sourceSpan); // Ignore diagnostics for text attributes if configured to do so. if ( !this.tcb.env.config.checkTypeOfAttributes && attr.attribute instanceof TmplAstTextAttribute ) { markIgnoreDiagnostics(assignment); } this.scope.addStatement(ts.factory.createExpressionStatement(assignment)); } this.checkRequiredInputs(seenRequiredInputs); return null; } private checkRequiredInputs(seenRequiredInputs: Set<ClassPropertyName>): void { const missing: BindingPropertyName[] = []; for (const input of this.dir.inputs) { if (input.required && !seenRequiredInputs.has(input.classPropertyName)) { missing.push(input.bindingPropertyName); } } if (missing.length > 0) { this.tcb.oobRecorder.missingRequiredInputs( this.tcb.id, this.node, this.dir.name, this.dir.isComponent, missing, ); } } } /** * A `TcbOp` which is used to generate a fallback expression if the inference of a directive type * via `TcbDirectiveCtorOp` requires a reference to its own type. This can happen using a template * reference: * * ```html * <some-cmp #ref [prop]="ref.foo"></some-cmp> * ``` * * In this case, `TcbDirectiveCtorCircularFallbackOp` will add a second inference of the directive * type to the type-check block, this time calling the directive's type constructor without any * input expressions. This infers the widest possible supertype for the directive, which is used to * resolve any recursive references required to infer the real type. */ class TcbDirectiveCtorCircularFallbackOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstTemplate | TmplAstElement, private dir: TypeCheckableDirectiveMeta, ) { super(); } override get optional() { return false; } override execute(): ts.Identifier { const id = this.tcb.allocateId(); const typeCtor = this.tcb.env.typeCtorFor(this.dir); const circularPlaceholder = ts.factory.createCallExpression( typeCtor, /* typeArguments */ undefined, [ts.factory.createNonNullExpression(ts.factory.createNull())], ); this.scope.addStatement(tsCreateVariable(id, circularPlaceholder)); return id; } }
{ "end_byte": 40893, "start_byte": 31897, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_40895_48132
/** * A `TcbOp` which feeds elements and unclaimed properties to the `DomSchemaChecker`. * * The DOM schema is not checked via TCB code generation. Instead, the `DomSchemaChecker` ingests * elements and property bindings and accumulates synthetic `ts.Diagnostic`s out-of-band. These are * later merged with the diagnostics generated from the TCB. * * For convenience, the TCB iteration of the template is used to drive the `DomSchemaChecker` via * the `TcbDomSchemaCheckerOp`. */ class TcbDomSchemaCheckerOp extends TcbOp { constructor( private tcb: Context, private element: TmplAstElement, private checkElement: boolean, private claimedInputs: Set<string>, ) { super(); } override get optional() { return false; } override execute(): ts.Expression | null { if (this.checkElement) { this.tcb.domSchemaChecker.checkElement( this.tcb.id, this.element, this.tcb.schemas, this.tcb.hostIsStandalone, ); } // TODO(alxhub): this could be more efficient. for (const binding of this.element.inputs) { const isPropertyBinding = binding.type === BindingType.Property || binding.type === BindingType.TwoWay; if (isPropertyBinding && this.claimedInputs.has(binding.name)) { // Skip this binding as it was claimed by a directive. continue; } if (isPropertyBinding && binding.name !== 'style' && binding.name !== 'class') { // A direct binding to a property. const propertyName = ATTR_TO_PROP.get(binding.name) ?? binding.name; this.tcb.domSchemaChecker.checkProperty( this.tcb.id, this.element, propertyName, binding.sourceSpan, this.tcb.schemas, this.tcb.hostIsStandalone, ); } } return null; } } /** * A `TcbOp` that finds and flags control flow nodes that interfere with content projection. * * Context: * Control flow blocks try to emulate the content projection behavior of `*ngIf` and `*ngFor` * in order to reduce breakages when moving from one syntax to the other (see #52414), however the * approach only works if there's only one element at the root of the control flow expression. * This means that a stray sibling node (e.g. text) can prevent an element from being projected * into the right slot. The purpose of the `TcbOp` is to find any places where a node at the root * of a control flow expression *would have been projected* into a specific slot, if the control * flow node didn't exist. */ class TcbControlFlowContentProjectionOp extends TcbOp { private readonly category: ts.DiagnosticCategory; constructor( private tcb: Context, private element: TmplAstElement, private ngContentSelectors: string[], private componentName: string, ) { super(); // We only need to account for `error` and `warning` since // this check won't be enabled for `suppress`. this.category = tcb.env.config.controlFlowPreventingContentProjection === 'error' ? ts.DiagnosticCategory.Error : ts.DiagnosticCategory.Warning; } override readonly optional = false; override execute(): null { const controlFlowToCheck = this.findPotentialControlFlowNodes(); if (controlFlowToCheck.length > 0) { const matcher = new SelectorMatcher<string>(); for (const selector of this.ngContentSelectors) { // `*` is a special selector for the catch-all slot. if (selector !== '*') { matcher.addSelectables(CssSelector.parse(selector), selector); } } for (const root of controlFlowToCheck) { for (const child of root.children) { if (child instanceof TmplAstElement || child instanceof TmplAstTemplate) { matcher.match(createCssSelectorFromNode(child), (_, originalSelector) => { this.tcb.oobRecorder.controlFlowPreventingContentProjection( this.tcb.id, this.category, child, this.componentName, originalSelector, root, this.tcb.hostPreserveWhitespaces, ); }); } } } } return null; } private findPotentialControlFlowNodes() { const result: Array< TmplAstIfBlockBranch | TmplAstSwitchBlockCase | TmplAstForLoopBlock | TmplAstForLoopBlockEmpty > = []; for (const child of this.element.children) { if (child instanceof TmplAstForLoopBlock) { if (this.shouldCheck(child)) { result.push(child); } if (child.empty !== null && this.shouldCheck(child.empty)) { result.push(child.empty); } } else if (child instanceof TmplAstIfBlock) { for (const branch of child.branches) { if (this.shouldCheck(branch)) { result.push(branch); } } } else if (child instanceof TmplAstSwitchBlock) { for (const current of child.cases) { if (this.shouldCheck(current)) { result.push(current); } } } } return result; } private shouldCheck(node: TmplAstNode & {children: TmplAstNode[]}): boolean { // Skip nodes with less than two children since it's impossible // for them to run into the issue that we're checking for. if (node.children.length < 2) { return false; } let hasSeenRootNode = false; // Check the number of root nodes while skipping empty text where relevant. for (const child of node.children) { // Normally `preserveWhitspaces` would have been accounted for during parsing, however // in `ngtsc/annotations/component/src/resources.ts#parseExtractedTemplate` we enable // `preserveWhitespaces` to preserve the accuracy of source maps diagnostics. This means // that we have to account for it here since the presence of text nodes affects the // content projection behavior. if ( !(child instanceof TmplAstText) || this.tcb.hostPreserveWhitespaces || child.value.trim().length > 0 ) { // Content projection will be affected if there's more than one root node. if (hasSeenRootNode) { return true; } hasSeenRootNode = true; } } return false; } } /** * Mapping between attributes names that don't correspond to their element property names. * Note: this mapping has to be kept in sync with the equally named mapping in the runtime. */ const ATTR_TO_PROP = new Map( Object.entries({ 'class': 'className', 'for': 'htmlFor', 'formaction': 'formAction', 'innerHtml': 'innerHTML', 'readonly': 'readOnly', 'tabindex': 'tabIndex', }), ); /** * A `TcbOp` which generates code to check "unclaimed inputs" - bindings on an element which were * not attributed to any directive or component, and are instead processed against the HTML element * itself. * * Currently, only the expressions of these bindings are checked. The targets of the bindings are * checked against the DOM schema via a `TcbDomSchemaCheckerOp`. * * Executing this operation returns nothing. */
{ "end_byte": 48132, "start_byte": 40895, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_48133_57376
class TcbUnclaimedInputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private element: TmplAstElement, private claimedInputs: Set<string>, ) { super(); } override get optional() { return false; } override execute(): null { // `this.inputs` contains only those bindings not matched by any directive. These bindings go to // the element itself. let elId: ts.Expression | null = null; // TODO(alxhub): this could be more efficient. for (const binding of this.element.inputs) { const isPropertyBinding = binding.type === BindingType.Property || binding.type === BindingType.TwoWay; if (isPropertyBinding && this.claimedInputs.has(binding.name)) { // Skip this binding as it was claimed by a directive. continue; } const expr = widenBinding(tcbExpression(binding.value, this.tcb, this.scope), this.tcb); if (this.tcb.env.config.checkTypeOfDomBindings && isPropertyBinding) { if (binding.name !== 'style' && binding.name !== 'class') { if (elId === null) { elId = this.scope.resolve(this.element); } // A direct binding to a property. const propertyName = ATTR_TO_PROP.get(binding.name) ?? binding.name; const prop = ts.factory.createElementAccessExpression( elId, ts.factory.createStringLiteral(propertyName), ); const stmt = ts.factory.createBinaryExpression( prop, ts.SyntaxKind.EqualsToken, wrapForDiagnostics(expr), ); addParseSpanInfo(stmt, binding.sourceSpan); this.scope.addStatement(ts.factory.createExpressionStatement(stmt)); } else { this.scope.addStatement(ts.factory.createExpressionStatement(expr)); } } else { // A binding to an animation, attribute, class or style. For now, only validate the right- // hand side of the expression. // TODO: properly check class and style bindings. this.scope.addStatement(ts.factory.createExpressionStatement(expr)); } } return null; } } /** * A `TcbOp` which generates code to check event bindings on an element that correspond with the * outputs of a directive. * * Executing this operation returns nothing. */ export class TcbDirectiveOutputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstTemplate | TmplAstElement, private dir: TypeCheckableDirectiveMeta, ) { super(); } override get optional() { return false; } override execute(): null { let dirId: ts.Expression | null = null; const outputs = this.dir.outputs; for (const output of this.node.outputs) { if ( output.type === ParsedEventType.Animation || !outputs.hasBindingPropertyName(output.name) ) { continue; } if (this.tcb.env.config.checkTypeOfOutputEvents && output.name.endsWith('Change')) { const inputName = output.name.slice(0, -6); isSplitTwoWayBinding(inputName, output, this.node.inputs, this.tcb); } // TODO(alxhub): consider supporting multiple fields with the same property name for outputs. const field = outputs.getByBindingPropertyName(output.name)![0].classPropertyName; if (dirId === null) { dirId = this.scope.resolve(this.node, this.dir); } const outputField = ts.factory.createElementAccessExpression( dirId, ts.factory.createStringLiteral(field), ); addParseSpanInfo(outputField, output.keySpan); if (this.tcb.env.config.checkTypeOfOutputEvents) { // For strict checking of directive events, generate a call to the `subscribe` method // on the directive's output field to let type information flow into the handler function's // `$event` parameter. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Infer); const subscribeFn = ts.factory.createPropertyAccessExpression(outputField, 'subscribe'); const call = ts.factory.createCallExpression(subscribeFn, /* typeArguments */ undefined, [ handler, ]); addParseSpanInfo(call, output.sourceSpan); this.scope.addStatement(ts.factory.createExpressionStatement(call)); } else { // If strict checking of directive events is disabled: // // * We still generate the access to the output field as a statement in the TCB so consumers // of the `TemplateTypeChecker` can still find the node for the class member for the // output. // * Emit a handler function where the `$event` parameter has an explicit `any` type. this.scope.addStatement(ts.factory.createExpressionStatement(outputField)); const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Any); this.scope.addStatement(ts.factory.createExpressionStatement(handler)); } } return null; } } /** * A `TcbOp` which generates code to check "unclaimed outputs" - event bindings on an element which * were not attributed to any directive or component, and are instead processed against the HTML * element itself. * * Executing this operation returns nothing. */ class TcbUnclaimedOutputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private element: TmplAstElement, private claimedOutputs: Set<string>, ) { super(); } override get optional() { return false; } override execute(): null { let elId: ts.Expression | null = null; // TODO(alxhub): this could be more efficient. for (const output of this.element.outputs) { if (this.claimedOutputs.has(output.name)) { // Skip this event handler as it was claimed by a directive. continue; } if (this.tcb.env.config.checkTypeOfOutputEvents && output.name.endsWith('Change')) { const inputName = output.name.slice(0, -6); if (isSplitTwoWayBinding(inputName, output, this.element.inputs, this.tcb)) { // Skip this event handler as the error was already handled. continue; } } if (output.type === ParsedEventType.Animation) { // Animation output bindings always have an `$event` parameter of type `AnimationEvent`. const eventType = this.tcb.env.config.checkTypeOfAnimationEvents ? this.tcb.env.referenceExternalType('@angular/animations', 'AnimationEvent') : EventParamType.Any; const handler = tcbCreateEventHandler(output, this.tcb, this.scope, eventType); this.scope.addStatement(ts.factory.createExpressionStatement(handler)); } else if (this.tcb.env.config.checkTypeOfDomEvents) { // If strict checking of DOM events is enabled, generate a call to `addEventListener` on // the element instance so that TypeScript's type inference for // `HTMLElement.addEventListener` using `HTMLElementEventMap` to infer an accurate type for // `$event` depending on the event name. For unknown event names, TypeScript resorts to the // base `Event` type. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Infer); if (elId === null) { elId = this.scope.resolve(this.element); } const propertyAccess = ts.factory.createPropertyAccessExpression(elId, 'addEventListener'); addParseSpanInfo(propertyAccess, output.keySpan); const call = ts.factory.createCallExpression( /* expression */ propertyAccess, /* typeArguments */ undefined, /* arguments */ [ts.factory.createStringLiteral(output.name), handler], ); addParseSpanInfo(call, output.sourceSpan); this.scope.addStatement(ts.factory.createExpressionStatement(call)); } else { // If strict checking of DOM inputs is disabled, emit a handler function where the `$event` // parameter has an explicit `any` type. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Any); this.scope.addStatement(ts.factory.createExpressionStatement(handler)); } } return null; } } /** * A `TcbOp` which generates a completion point for the component context. * * This completion point looks like `this. ;` in the TCB output, and does not produce diagnostics. * TypeScript autocompletion APIs can be used at this completion point (after the '.') to produce * autocompletion results of properties and methods from the template's component context. */ class TcbComponentContextCompletionOp extends TcbOp { constructor(private scope: Scope) { super(); } override readonly optional = false; override execute(): null { const ctx = ts.factory.createThis(); const ctxDot = ts.factory.createPropertyAccessExpression(ctx, ''); markIgnoreDiagnostics(ctxDot); addExpressionIdentifier(ctxDot, ExpressionIdentifier.COMPONENT_COMPLETION); this.scope.addStatement(ts.factory.createExpressionStatement(ctxDot)); return null; } }
{ "end_byte": 57376, "start_byte": 48133, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_57378_64209
/** * A `TcbOp` which renders a variable defined inside of block syntax (e.g. `@if (expr; as var) {}`). * * Executing this operation returns the identifier which can be used to refer to the variable. */ class TcbBlockVariableOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private initializer: ts.Expression, private variable: TmplAstVariable, ) { super(); } override get optional() { return false; } override execute(): ts.Identifier { const id = this.tcb.allocateId(); addParseSpanInfo(id, this.variable.keySpan); const variable = tsCreateVariable(id, wrapForTypeChecker(this.initializer)); addParseSpanInfo(variable.declarationList.declarations[0], this.variable.sourceSpan); this.scope.addStatement(variable); return id; } } /** * A `TcbOp` which renders a variable that is implicitly available within a block (e.g. `$count` * in a `@for` block). * * Executing this operation returns the identifier which can be used to refer to the variable. */ class TcbBlockImplicitVariableOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private type: ts.TypeNode, private variable: TmplAstVariable, ) { super(); } override readonly optional = true; override execute(): ts.Identifier { const id = this.tcb.allocateId(); addParseSpanInfo(id, this.variable.keySpan); const variable = tsDeclareVariable(id, this.type); addParseSpanInfo(variable.declarationList.declarations[0], this.variable.sourceSpan); this.scope.addStatement(variable); return id; } } /** * A `TcbOp` which renders an `if` template block as a TypeScript `if` statement. * * Executing this operation returns nothing. */ class TcbIfOp extends TcbOp { private expressionScopes = new Map<TmplAstIfBlockBranch, Scope>(); constructor( private tcb: Context, private scope: Scope, private block: TmplAstIfBlock, ) { super(); } override get optional() { return false; } override execute(): null { const root = this.generateBranch(0); root && this.scope.addStatement(root); return null; } private generateBranch(index: number): ts.Statement | undefined { const branch = this.block.branches[index]; if (!branch) { return undefined; } // If the expression is null, it means that it's an `else` statement. if (branch.expression === null) { const branchScope = this.getBranchScope(this.scope, branch, index); return ts.factory.createBlock(branchScope.render()); } // We process the expression first in the parent scope, but create a scope around the block // that the body will inherit from. We do this, because we need to declare a separate variable // for the case where the expression has an alias _and_ because we need the processed // expression when generating the guard for the body. const outerScope = Scope.forNodes(this.tcb, this.scope, branch, [], null); outerScope.render().forEach((stmt) => this.scope.addStatement(stmt)); this.expressionScopes.set(branch, outerScope); let expression = tcbExpression(branch.expression, this.tcb, this.scope); if (branch.expressionAlias !== null) { expression = ts.factory.createBinaryExpression( ts.factory.createParenthesizedExpression(expression), ts.SyntaxKind.AmpersandAmpersandToken, outerScope.resolve(branch.expressionAlias), ); } const bodyScope = this.getBranchScope(outerScope, branch, index); return ts.factory.createIfStatement( expression, ts.factory.createBlock(bodyScope.render()), this.generateBranch(index + 1), ); } private getBranchScope(parentScope: Scope, branch: TmplAstIfBlockBranch, index: number): Scope { const checkBody = this.tcb.env.config.checkControlFlowBodies; return Scope.forNodes( this.tcb, parentScope, null, checkBody ? branch.children : [], checkBody ? this.generateBranchGuard(index) : null, ); } private generateBranchGuard(index: number): ts.Expression | null { let guard: ts.Expression | null = null; // Since event listeners are inside callbacks, type narrowing doesn't apply to them anymore. // To recreate the behavior, we generate an expression that negates all the values of the // branches _before_ the current one, and then we add the current branch's expression on top. // For example `@if (expr === 1) {} @else if (expr === 2) {} @else if (expr === 3)`, the guard // for the last expression will be `!(expr === 1) && !(expr === 2) && expr === 3`. for (let i = 0; i <= index; i++) { const branch = this.block.branches[i]; // Skip over branches without an expression. if (branch.expression === null) { continue; } // This shouldn't happen since all the state is handled // internally, but we have the check just in case. if (!this.expressionScopes.has(branch)) { throw new Error(`Could not determine expression scope of branch at index ${i}`); } const expressionScope = this.expressionScopes.get(branch)!; let expression: ts.Expression; // We need to recreate the expression and mark it to be ignored for diagnostics, // because it was already checked as a part of the block's condition and we don't // want it to produce a duplicate diagnostic. expression = tcbExpression(branch.expression, this.tcb, expressionScope); if (branch.expressionAlias !== null) { expression = ts.factory.createBinaryExpression( ts.factory.createParenthesizedExpression(expression), ts.SyntaxKind.AmpersandAmpersandToken, expressionScope.resolve(branch.expressionAlias), ); } markIgnoreDiagnostics(expression); // The expressions of the preceding branches have to be negated // (e.g. `expr` becomes `!(expr)`) when comparing in the guard, except // for the branch's own expression which is preserved as is. const comparisonExpression = i === index ? expression : ts.factory.createPrefixUnaryExpression( ts.SyntaxKind.ExclamationToken, ts.factory.createParenthesizedExpression(expression), ); // Finally add the expression to the guard with an && operator. guard = guard === null ? comparisonExpression : ts.factory.createBinaryExpression( guard, ts.SyntaxKind.AmpersandAmpersandToken, comparisonExpression, ); } return guard; } } /** * A `TcbOp` which renders a `switch` block as a TypeScript `switch` statement. * * Executing this operation returns nothing. */
{ "end_byte": 64209, "start_byte": 57378, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_64210_71306
class TcbSwitchOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private block: TmplAstSwitchBlock, ) { super(); } override get optional() { return false; } override execute(): null { const switchExpression = tcbExpression(this.block.expression, this.tcb, this.scope); const clauses = this.block.cases.map((current) => { const checkBody = this.tcb.env.config.checkControlFlowBodies; const clauseScope = Scope.forNodes( this.tcb, this.scope, null, checkBody ? current.children : [], checkBody ? this.generateGuard(current, switchExpression) : null, ); const statements = [...clauseScope.render(), ts.factory.createBreakStatement()]; return current.expression === null ? ts.factory.createDefaultClause(statements) : ts.factory.createCaseClause( tcbExpression(current.expression, this.tcb, clauseScope), statements, ); }); this.scope.addStatement( ts.factory.createSwitchStatement(switchExpression, ts.factory.createCaseBlock(clauses)), ); return null; } private generateGuard( node: TmplAstSwitchBlockCase, switchValue: ts.Expression, ): ts.Expression | null { // For non-default cases, the guard needs to compare against the case value, e.g. // `switchExpression === caseExpression`. if (node.expression !== null) { // The expression needs to be ignored for diagnostics since it has been checked already. const expression = tcbExpression(node.expression, this.tcb, this.scope); markIgnoreDiagnostics(expression); return ts.factory.createBinaryExpression( switchValue, ts.SyntaxKind.EqualsEqualsEqualsToken, expression, ); } // To fully narrow the type in the default case, we need to generate an expression that negates // the values of all of the other expressions. For example: // @switch (expr) { // @case (1) {} // @case (2) {} // @default {} // } // Will produce the guard `expr !== 1 && expr !== 2`. let guard: ts.Expression | null = null; for (const current of this.block.cases) { if (current.expression === null) { continue; } // The expression needs to be ignored for diagnostics since it has been checked already. const expression = tcbExpression(current.expression, this.tcb, this.scope); markIgnoreDiagnostics(expression); const comparison = ts.factory.createBinaryExpression( switchValue, ts.SyntaxKind.ExclamationEqualsEqualsToken, expression, ); if (guard === null) { guard = comparison; } else { guard = ts.factory.createBinaryExpression( guard, ts.SyntaxKind.AmpersandAmpersandToken, comparison, ); } } return guard; } } /** * A `TcbOp` which renders a `for` block as a TypeScript `for...of` loop. * * Executing this operation returns nothing. */ class TcbForOfOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private block: TmplAstForLoopBlock, ) { super(); } override get optional() { return false; } override execute(): null { const loopScope = Scope.forNodes( this.tcb, this.scope, this.block, this.tcb.env.config.checkControlFlowBodies ? this.block.children : [], null, ); const initializerId = loopScope.resolve(this.block.item); if (!ts.isIdentifier(initializerId)) { throw new Error( `Could not resolve for loop variable ${this.block.item.name} to an identifier`, ); } const initializer = ts.factory.createVariableDeclarationList( [ts.factory.createVariableDeclaration(initializerId)], ts.NodeFlags.Const, ); addParseSpanInfo(initializer, this.block.item.keySpan); // It's common to have a for loop over a nullable value (e.g. produced by the `async` pipe). // Add a non-null expression to allow such values to be assigned. const expression = ts.factory.createNonNullExpression( tcbExpression(this.block.expression, this.tcb, this.scope), ); const trackTranslator = new TcbForLoopTrackTranslator(this.tcb, loopScope, this.block); const trackExpression = trackTranslator.translate(this.block.trackBy); const statements = [ ...loopScope.render(), ts.factory.createExpressionStatement(trackExpression), ]; this.scope.addStatement( ts.factory.createForOfStatement( undefined, initializer, expression, ts.factory.createBlock(statements), ), ); return null; } } /** * Value used to break a circular reference between `TcbOp`s. * * This value is returned whenever `TcbOp`s have a circular dependency. The expression is a non-null * assertion of the null value (in TypeScript, the expression `null!`). This construction will infer * the least narrow type for whatever it's assigned to. */ const INFER_TYPE_FOR_CIRCULAR_OP_EXPR = ts.factory.createNonNullExpression(ts.factory.createNull()); /** * Overall generation context for the type check block. * * `Context` handles operations during code generation which are global with respect to the whole * block. It's responsible for variable name allocation and management of any imports needed. It * also contains the template metadata itself. */ export class Context { private nextId = 1; constructor( readonly env: Environment, readonly domSchemaChecker: DomSchemaChecker, readonly oobRecorder: OutOfBandDiagnosticRecorder, readonly id: TemplateId, readonly boundTarget: BoundTarget<TypeCheckableDirectiveMeta>, private pipes: Map<string, PipeMeta>, readonly schemas: SchemaMetadata[], readonly hostIsStandalone: boolean, readonly hostPreserveWhitespaces: boolean, ) {} /** * Allocate a new variable name for use within the `Context`. * * Currently this uses a monotonically increasing counter, but in the future the variable name * might change depending on the type of data being stored. */ allocateId(): ts.Identifier { return ts.factory.createIdentifier(`_t${this.nextId++}`); } getPipeByName(name: string): PipeMeta | null { if (!this.pipes.has(name)) { return null; } return this.pipes.get(name)!; } } /** * Local scope within the type check block for a particular template. * * The top-level template and each nested `<ng-template>` have their own `Scope`, which exist in a * hierarchy. The structure of this hierarchy mirrors the syntactic scopes in the generated type * check block, where each nested template is encased in an `if` structure. * * As a template's `TcbOp`s are executed in a given `Scope`, statements are added via * `addStatement()`. When this processing is complete, the `Scope` can be turned into a `ts.Block` * via `renderToBlock()`. * * If a `TcbOp` requires the output of another, it can call `resolve()`. */
{ "end_byte": 71306, "start_byte": 64210, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_71307_79234
class Scope { /** * A queue of operations which need to be performed to generate the TCB code for this scope. * * This array can contain either a `TcbOp` which has yet to be executed, or a `ts.Expression|null` * representing the memoized result of executing the operation. As operations are executed, their * results are written into the `opQueue`, overwriting the original operation. * * If an operation is in the process of being executed, it is temporarily overwritten here with * `INFER_TYPE_FOR_CIRCULAR_OP_EXPR`. This way, if a cycle is encountered where an operation * depends transitively on its own result, the inner operation will infer the least narrow type * that fits instead. This has the same semantics as TypeScript itself when types are referenced * circularly. */ private opQueue: (TcbOp | ts.Expression | null)[] = []; /** * A map of `TmplAstElement`s to the index of their `TcbElementOp` in the `opQueue` */ private elementOpMap = new Map<TmplAstElement, number>(); /** * A map of maps which tracks the index of `TcbDirectiveCtorOp`s in the `opQueue` for each * directive on a `TmplAstElement` or `TmplAstTemplate` node. */ private directiveOpMap = new Map< TmplAstElement | TmplAstTemplate, Map<TypeCheckableDirectiveMeta, number> >(); /** * A map of `TmplAstReference`s to the index of their `TcbReferenceOp` in the `opQueue` */ private referenceOpMap = new Map<TmplAstReference, number>(); /** * Map of immediately nested <ng-template>s (within this `Scope`) represented by `TmplAstTemplate` * nodes to the index of their `TcbTemplateContextOp`s in the `opQueue`. */ private templateCtxOpMap = new Map<TmplAstTemplate, number>(); /** * Map of variables declared on the template that created this `Scope` (represented by * `TmplAstVariable` nodes) to the index of their `TcbVariableOp`s in the `opQueue`, or to * pre-resolved variable identifiers. */ private varMap = new Map<TmplAstVariable, number | ts.Identifier>(); /** * A map of the names of `TmplAstLetDeclaration`s to the index of their op in the `opQueue`. * * Assumes that there won't be duplicated `@let` declarations within the same scope. */ private letDeclOpMap = new Map<string, {opIndex: number; node: TmplAstLetDeclaration}>(); /** * Statements for this template. * * Executing the `TcbOp`s in the `opQueue` populates this array. */ private statements: ts.Statement[] = []; /** * Names of the for loop context variables and their types. */ private static readonly forLoopContextVariableTypes = new Map<string, ts.KeywordTypeSyntaxKind>([ ['$first', ts.SyntaxKind.BooleanKeyword], ['$last', ts.SyntaxKind.BooleanKeyword], ['$even', ts.SyntaxKind.BooleanKeyword], ['$odd', ts.SyntaxKind.BooleanKeyword], ['$index', ts.SyntaxKind.NumberKeyword], ['$count', ts.SyntaxKind.NumberKeyword], ]); private constructor( private tcb: Context, private parent: Scope | null = null, private guard: ts.Expression | null = null, ) {} /** * Constructs a `Scope` given either a `TmplAstTemplate` or a list of `TmplAstNode`s. * * @param tcb the overall context of TCB generation. * @param parentScope the `Scope` of the parent template (if any) or `null` if this is the root * `Scope`. * @param scopedNode Node that provides the scope around the child nodes (e.g. a * `TmplAstTemplate` node exposing variables to its children). * @param children Child nodes that should be appended to the TCB. * @param guard an expression that is applied to this scope for type narrowing purposes. */ static forNodes( tcb: Context, parentScope: Scope | null, scopedNode: TmplAstTemplate | TmplAstIfBlockBranch | TmplAstForLoopBlock | null, children: TmplAstNode[], guard: ts.Expression | null, ): Scope { const scope = new Scope(tcb, parentScope, guard); if (parentScope === null && tcb.env.config.enableTemplateTypeChecker) { // Add an autocompletion point for the component context. scope.opQueue.push(new TcbComponentContextCompletionOp(scope)); } // If given an actual `TmplAstTemplate` instance, then process any additional information it // has. if (scopedNode instanceof TmplAstTemplate) { // The template's variable declarations need to be added as `TcbVariableOp`s. const varMap = new Map<string, TmplAstVariable>(); for (const v of scopedNode.variables) { // Validate that variables on the `TmplAstTemplate` are only declared once. if (!varMap.has(v.name)) { varMap.set(v.name, v); } else { const firstDecl = varMap.get(v.name)!; tcb.oobRecorder.duplicateTemplateVar(tcb.id, v, firstDecl); } this.registerVariable(scope, v, new TcbTemplateVariableOp(tcb, scope, scopedNode, v)); } } else if (scopedNode instanceof TmplAstIfBlockBranch) { const {expression, expressionAlias} = scopedNode; if (expression !== null && expressionAlias !== null) { this.registerVariable( scope, expressionAlias, new TcbBlockVariableOp( tcb, scope, tcbExpression(expression, tcb, scope), expressionAlias, ), ); } } else if (scopedNode instanceof TmplAstForLoopBlock) { // Register the variable for the loop so it can be resolved by // children. It'll be declared once the loop is created. const loopInitializer = tcb.allocateId(); addParseSpanInfo(loopInitializer, scopedNode.item.sourceSpan); scope.varMap.set(scopedNode.item, loopInitializer); for (const variable of scopedNode.contextVariables) { if (!this.forLoopContextVariableTypes.has(variable.value)) { throw new Error(`Unrecognized for loop context variable ${variable.name}`); } const type = ts.factory.createKeywordTypeNode( this.forLoopContextVariableTypes.get(variable.value)!, ); this.registerVariable( scope, variable, new TcbBlockImplicitVariableOp(tcb, scope, type, variable), ); } } for (const node of children) { scope.appendNode(node); } // Once everything is registered, we need to check if there are `@let` // declarations that conflict with other local symbols defined after them. for (const variable of scope.varMap.keys()) { Scope.checkConflictingLet(scope, variable); } for (const ref of scope.referenceOpMap.keys()) { Scope.checkConflictingLet(scope, ref); } return scope; } /** Registers a local variable with a scope. */ private static registerVariable(scope: Scope, variable: TmplAstVariable, op: TcbOp): void { const opIndex = scope.opQueue.push(op) - 1; scope.varMap.set(variable, opIndex); } /** * Look up a `ts.Expression` representing the value of some operation in the current `Scope`, * including any parent scope(s). This method always returns a mutable clone of the * `ts.Expression` with the comments cleared. * * @param node a `TmplAstNode` of the operation in question. The lookup performed will depend on * the type of this node: * * Assuming `directive` is not present, then `resolve` will return: * * * `TmplAstElement` - retrieve the expression for the element DOM node * * `TmplAstTemplate` - retrieve the template context variable * * `TmplAstVariable` - retrieve a template let- variable * * `TmplAstLetDeclaration` - retrieve a template `@let` declaration * * `TmplAstReference` - retrieve variable created for the local ref * * @param directive if present, a directive type on a `TmplAstElement` or `TmplAstTemplate` to * look up instead of the default for an element or template node. */
{ "end_byte": 79234, "start_byte": 71307, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_79237_85880
resolve( node: LocalSymbol, directive?: TypeCheckableDirectiveMeta, ): ts.Identifier | ts.NonNullExpression { // Attempt to resolve the operation locally. const res = this.resolveLocal(node, directive); if (res !== null) { // We want to get a clone of the resolved expression and clear the trailing comments // so they don't continue to appear in every place the expression is used. // As an example, this would otherwise produce: // var _t1 /**T:DIR*/ /*1,2*/ = _ctor1(); // _t1 /**T:DIR*/ /*1,2*/.input = 'value'; // // In addition, returning a clone prevents the consumer of `Scope#resolve` from // attaching comments at the declaration site. let clone: ts.Identifier | ts.NonNullExpression; if (ts.isIdentifier(res)) { clone = ts.factory.createIdentifier(res.text); } else if (ts.isNonNullExpression(res)) { clone = ts.factory.createNonNullExpression(res.expression); } else { throw new Error(`Could not resolve ${node} to an Identifier or a NonNullExpression`); } ts.setOriginalNode(clone, res); (clone as any).parent = clone.parent; return ts.setSyntheticTrailingComments(clone, []); } else if (this.parent !== null) { // Check with the parent. return this.parent.resolve(node, directive); } else { throw new Error(`Could not resolve ${node} / ${directive}`); } } /** * Add a statement to this scope. */ addStatement(stmt: ts.Statement): void { this.statements.push(stmt); } /** * Get the statements. */ render(): ts.Statement[] { for (let i = 0; i < this.opQueue.length; i++) { // Optional statements cannot be skipped when we are generating the TCB for use // by the TemplateTypeChecker. const skipOptional = !this.tcb.env.config.enableTemplateTypeChecker; this.executeOp(i, skipOptional); } return this.statements; } /** * Returns an expression of all template guards that apply to this scope, including those of * parent scopes. If no guards have been applied, null is returned. */ guards(): ts.Expression | null { let parentGuards: ts.Expression | null = null; if (this.parent !== null) { // Start with the guards from the parent scope, if present. parentGuards = this.parent.guards(); } if (this.guard === null) { // This scope does not have a guard, so return the parent's guards as is. return parentGuards; } else if (parentGuards === null) { // There's no guards from the parent scope, so this scope's guard represents all available // guards. return this.guard; } else { // Both the parent scope and this scope provide a guard, so create a combination of the two. // It is important that the parent guard is used as left operand, given that it may provide // narrowing that is required for this scope's guard to be valid. return ts.factory.createBinaryExpression( parentGuards, ts.SyntaxKind.AmpersandAmpersandToken, this.guard, ); } } /** Returns whether a template symbol is defined locally within the current scope. */ isLocal(node: TmplAstVariable | TmplAstLetDeclaration | TmplAstReference): boolean { if (node instanceof TmplAstVariable) { return this.varMap.has(node); } if (node instanceof TmplAstLetDeclaration) { return this.letDeclOpMap.has(node.name); } return this.referenceOpMap.has(node); } private resolveLocal( ref: LocalSymbol, directive?: TypeCheckableDirectiveMeta, ): ts.Expression | null { if (ref instanceof TmplAstReference && this.referenceOpMap.has(ref)) { return this.resolveOp(this.referenceOpMap.get(ref)!); } else if (ref instanceof TmplAstLetDeclaration && this.letDeclOpMap.has(ref.name)) { return this.resolveOp(this.letDeclOpMap.get(ref.name)!.opIndex); } else if (ref instanceof TmplAstVariable && this.varMap.has(ref)) { // Resolving a context variable for this template. // Execute the `TcbVariableOp` associated with the `TmplAstVariable`. const opIndexOrNode = this.varMap.get(ref)!; return typeof opIndexOrNode === 'number' ? this.resolveOp(opIndexOrNode) : opIndexOrNode; } else if ( ref instanceof TmplAstTemplate && directive === undefined && this.templateCtxOpMap.has(ref) ) { // Resolving the context of the given sub-template. // Execute the `TcbTemplateContextOp` for the template. return this.resolveOp(this.templateCtxOpMap.get(ref)!); } else if ( (ref instanceof TmplAstElement || ref instanceof TmplAstTemplate) && directive !== undefined && this.directiveOpMap.has(ref) ) { // Resolving a directive on an element or sub-template. const dirMap = this.directiveOpMap.get(ref)!; if (dirMap.has(directive)) { return this.resolveOp(dirMap.get(directive)!); } else { return null; } } else if (ref instanceof TmplAstElement && this.elementOpMap.has(ref)) { // Resolving the DOM node of an element in this template. return this.resolveOp(this.elementOpMap.get(ref)!); } else { return null; } } /** * Like `executeOp`, but assert that the operation actually returned `ts.Expression`. */ private resolveOp(opIndex: number): ts.Expression { const res = this.executeOp(opIndex, /* skipOptional */ false); if (res === null) { throw new Error(`Error resolving operation, got null`); } return res; } /** * Execute a particular `TcbOp` in the `opQueue`. * * This method replaces the operation in the `opQueue` with the result of execution (once done) * and also protects against a circular dependency from the operation to itself by temporarily * setting the operation's result to a special expression. */ private executeOp(opIndex: number, skipOptional: boolean): ts.Expression | null { const op = this.opQueue[opIndex]; if (!(op instanceof TcbOp)) { return op; } if (skipOptional && op.optional) { return null; } // Set the result of the operation in the queue to its circular fallback. If executing this // operation results in a circular dependency, this will prevent an infinite loop and allow for // the resolution of such cycles. this.opQueue[opIndex] = op.circularFallback(); const res = op.execute(); // Once the operation has finished executing, it's safe to cache the real result. this.opQueue[opIndex] = res; return res; }
{ "end_byte": 85880, "start_byte": 79237, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_85884_93140
private appendNode(node: TmplAstNode): void { if (node instanceof TmplAstElement) { const opIndex = this.opQueue.push(new TcbElementOp(this.tcb, this, node)) - 1; this.elementOpMap.set(node, opIndex); if (this.tcb.env.config.controlFlowPreventingContentProjection !== 'suppress') { this.appendContentProjectionCheckOp(node); } this.appendDirectivesAndInputsOfNode(node); this.appendOutputsOfNode(node); this.appendChildren(node); this.checkAndAppendReferencesOfNode(node); } else if (node instanceof TmplAstTemplate) { // Template children are rendered in a child scope. this.appendDirectivesAndInputsOfNode(node); this.appendOutputsOfNode(node); const ctxIndex = this.opQueue.push(new TcbTemplateContextOp(this.tcb, this)) - 1; this.templateCtxOpMap.set(node, ctxIndex); if (this.tcb.env.config.checkTemplateBodies) { this.opQueue.push(new TcbTemplateBodyOp(this.tcb, this, node)); } else if (this.tcb.env.config.alwaysCheckSchemaInTemplateBodies) { this.appendDeepSchemaChecks(node.children); } this.checkAndAppendReferencesOfNode(node); } else if (node instanceof TmplAstDeferredBlock) { this.appendDeferredBlock(node); } else if (node instanceof TmplAstIfBlock) { this.opQueue.push(new TcbIfOp(this.tcb, this, node)); } else if (node instanceof TmplAstSwitchBlock) { this.opQueue.push(new TcbSwitchOp(this.tcb, this, node)); } else if (node instanceof TmplAstForLoopBlock) { this.opQueue.push(new TcbForOfOp(this.tcb, this, node)); node.empty && this.tcb.env.config.checkControlFlowBodies && this.appendChildren(node.empty); } else if (node instanceof TmplAstBoundText) { this.opQueue.push(new TcbExpressionOp(this.tcb, this, node.value)); } else if (node instanceof TmplAstIcu) { this.appendIcuExpressions(node); } else if (node instanceof TmplAstContent) { this.appendChildren(node); } else if (node instanceof TmplAstLetDeclaration) { const opIndex = this.opQueue.push(new TcbLetDeclarationOp(this.tcb, this, node)) - 1; if (this.isLocal(node)) { this.tcb.oobRecorder.conflictingDeclaration(this.tcb.id, node); } else { this.letDeclOpMap.set(node.name, {opIndex, node}); } } } private appendChildren(node: TmplAstNode & {children: TmplAstNode[]}) { for (const child of node.children) { this.appendNode(child); } } private checkAndAppendReferencesOfNode(node: TmplAstElement | TmplAstTemplate): void { for (const ref of node.references) { const target = this.tcb.boundTarget.getReferenceTarget(ref); let ctxIndex: number; if (target === null) { // The reference is invalid if it doesn't have a target, so report it as an error. this.tcb.oobRecorder.missingReferenceTarget(this.tcb.id, ref); // Any usages of the invalid reference will be resolved to a variable of type any. ctxIndex = this.opQueue.push(new TcbInvalidReferenceOp(this.tcb, this)) - 1; } else if (target instanceof TmplAstTemplate || target instanceof TmplAstElement) { ctxIndex = this.opQueue.push(new TcbReferenceOp(this.tcb, this, ref, node, target)) - 1; } else { ctxIndex = this.opQueue.push(new TcbReferenceOp(this.tcb, this, ref, node, target.directive)) - 1; } this.referenceOpMap.set(ref, ctxIndex); } } private appendDirectivesAndInputsOfNode(node: TmplAstElement | TmplAstTemplate): void { // Collect all the inputs on the element. const claimedInputs = new Set<string>(); const directives = this.tcb.boundTarget.getDirectivesOfNode(node); if (directives === null || directives.length === 0) { // If there are no directives, then all inputs are unclaimed inputs, so queue an operation // to add them if needed. if (node instanceof TmplAstElement) { this.opQueue.push(new TcbUnclaimedInputsOp(this.tcb, this, node, claimedInputs)); this.opQueue.push( new TcbDomSchemaCheckerOp(this.tcb, node, /* checkElement */ true, claimedInputs), ); } return; } else { if (node instanceof TmplAstElement) { const isDeferred = this.tcb.boundTarget.isDeferred(node); if (!isDeferred && directives.some((dirMeta) => dirMeta.isExplicitlyDeferred)) { // This node has directives/components that were defer-loaded (included into // `@Component.deferredImports`), but the node itself was used outside of a // `@defer` block, which is the error. this.tcb.oobRecorder.deferredComponentUsedEagerly(this.tcb.id, node); } } } const dirMap = new Map<TypeCheckableDirectiveMeta, number>(); for (const dir of directives) { let directiveOp: TcbOp; const host = this.tcb.env.reflector; const dirRef = dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>; if (!dir.isGeneric) { // The most common case is that when a directive is not generic, we use the normal // `TcbNonDirectiveTypeOp`. directiveOp = new TcbNonGenericDirectiveTypeOp(this.tcb, this, node, dir); } else if ( !requiresInlineTypeCtor(dirRef.node, host, this.tcb.env) || this.tcb.env.config.useInlineTypeConstructors ) { // For generic directives, we use a type constructor to infer types. If a directive requires // an inline type constructor, then inlining must be available to use the // `TcbDirectiveCtorOp`. If not we, we fallback to using `any` – see below. directiveOp = new TcbDirectiveCtorOp(this.tcb, this, node, dir); } else { // If inlining is not available, then we give up on inferring the generic params, and use // `any` type for the directive's generic parameters. directiveOp = new TcbGenericDirectiveTypeWithAnyParamsOp(this.tcb, this, node, dir); } const dirIndex = this.opQueue.push(directiveOp) - 1; dirMap.set(dir, dirIndex); this.opQueue.push(new TcbDirectiveInputsOp(this.tcb, this, node, dir)); } this.directiveOpMap.set(node, dirMap); // After expanding the directives, we might need to queue an operation to check any unclaimed // inputs. if (node instanceof TmplAstElement) { // Go through the directives and remove any inputs that it claims from `elementInputs`. for (const dir of directives) { for (const propertyName of dir.inputs.propertyNames) { claimedInputs.add(propertyName); } } this.opQueue.push(new TcbUnclaimedInputsOp(this.tcb, this, node, claimedInputs)); // If there are no directives which match this element, then it's a "plain" DOM element (or a // web component), and should be checked against the DOM schema. If any directives match, // we must assume that the element could be custom (either a component, or a directive like // <router-outlet>) and shouldn't validate the element name itself. const checkElement = directives.length === 0; this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, checkElement, claimedInputs)); } }
{ "end_byte": 93140, "start_byte": 85884, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_93144_99741
ivate appendOutputsOfNode(node: TmplAstElement | TmplAstTemplate): void { // Collect all the outputs on the element. const claimedOutputs = new Set<string>(); const directives = this.tcb.boundTarget.getDirectivesOfNode(node); if (directives === null || directives.length === 0) { // If there are no directives, then all outputs are unclaimed outputs, so queue an operation // to add them if needed. if (node instanceof TmplAstElement) { this.opQueue.push(new TcbUnclaimedOutputsOp(this.tcb, this, node, claimedOutputs)); } return; } // Queue operations for all directives to check the relevant outputs for a directive. for (const dir of directives) { this.opQueue.push(new TcbDirectiveOutputsOp(this.tcb, this, node, dir)); } // After expanding the directives, we might need to queue an operation to check any unclaimed // outputs. if (node instanceof TmplAstElement) { // Go through the directives and register any outputs that it claims in `claimedOutputs`. for (const dir of directives) { for (const outputProperty of dir.outputs.propertyNames) { claimedOutputs.add(outputProperty); } } this.opQueue.push(new TcbUnclaimedOutputsOp(this.tcb, this, node, claimedOutputs)); } } private appendDeepSchemaChecks(nodes: TmplAstNode[]): void { for (const node of nodes) { if (!(node instanceof TmplAstElement || node instanceof TmplAstTemplate)) { continue; } if (node instanceof TmplAstElement) { const claimedInputs = new Set<string>(); const directives = this.tcb.boundTarget.getDirectivesOfNode(node); let hasDirectives: boolean; if (directives === null || directives.length === 0) { hasDirectives = false; } else { hasDirectives = true; for (const dir of directives) { for (const propertyName of dir.inputs.propertyNames) { claimedInputs.add(propertyName); } } } this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, !hasDirectives, claimedInputs)); } this.appendDeepSchemaChecks(node.children); } } private appendIcuExpressions(node: TmplAstIcu): void { for (const variable of Object.values(node.vars)) { this.opQueue.push(new TcbExpressionOp(this.tcb, this, variable.value)); } for (const placeholder of Object.values(node.placeholders)) { if (placeholder instanceof TmplAstBoundText) { this.opQueue.push(new TcbExpressionOp(this.tcb, this, placeholder.value)); } } } private appendContentProjectionCheckOp(root: TmplAstElement): void { const meta = this.tcb.boundTarget.getDirectivesOfNode(root)?.find((meta) => meta.isComponent) || null; if (meta !== null && meta.ngContentSelectors !== null && meta.ngContentSelectors.length > 0) { const selectors = meta.ngContentSelectors; // We don't need to generate anything for components that don't have projection // slots, or they only have one catch-all slot (represented by `*`). if (selectors.length > 1 || (selectors.length === 1 && selectors[0] !== '*')) { this.opQueue.push( new TcbControlFlowContentProjectionOp(this.tcb, root, selectors, meta.name), ); } } } private appendDeferredBlock(block: TmplAstDeferredBlock): void { this.appendDeferredTriggers(block, block.triggers); this.appendDeferredTriggers(block, block.prefetchTriggers); // Only the `when` hydration trigger needs to be checked. if (block.hydrateTriggers.when) { this.opQueue.push(new TcbExpressionOp(this.tcb, this, block.hydrateTriggers.when.value)); } this.appendChildren(block); if (block.placeholder !== null) { this.appendChildren(block.placeholder); } if (block.loading !== null) { this.appendChildren(block.loading); } if (block.error !== null) { this.appendChildren(block.error); } } private appendDeferredTriggers( block: TmplAstDeferredBlock, triggers: TmplAstDeferredBlockTriggers, ): void { if (triggers.when !== undefined) { this.opQueue.push(new TcbExpressionOp(this.tcb, this, triggers.when.value)); } if (triggers.hover !== undefined) { this.appendReferenceBasedDeferredTrigger(block, triggers.hover); } if (triggers.interaction !== undefined) { this.appendReferenceBasedDeferredTrigger(block, triggers.interaction); } if (triggers.viewport !== undefined) { this.appendReferenceBasedDeferredTrigger(block, triggers.viewport); } } private appendReferenceBasedDeferredTrigger( block: TmplAstDeferredBlock, trigger: | TmplAstHoverDeferredTrigger | TmplAstInteractionDeferredTrigger | TmplAstViewportDeferredTrigger, ): void { if (this.tcb.boundTarget.getDeferredTriggerTarget(block, trigger) === null) { this.tcb.oobRecorder.inaccessibleDeferredTriggerElement(this.tcb.id, trigger); } } /** Reports a diagnostic if there are any `@let` declarations that conflict with a node. */ private static checkConflictingLet(scope: Scope, node: TmplAstVariable | TmplAstReference): void { if (scope.letDeclOpMap.has(node.name)) { scope.tcb.oobRecorder.conflictingDeclaration( scope.tcb.id, scope.letDeclOpMap.get(node.name)!.node, ); } } } interface TcbBoundAttribute { attribute: TmplAstBoundAttribute | TmplAstTextAttribute; inputs: { fieldName: ClassPropertyName; required: boolean; isSignal: boolean; transformType: Reference<ts.TypeNode> | null; isTwoWayBinding: boolean; }[]; } /** * Create the `this` parameter to the top-level TCB function, with the given generic type * arguments. */ function tcbThisParam( name: ts.EntityName, typeArguments: ts.TypeNode[] | undefined, ): ts.ParameterDeclaration { return ts.factory.createParameterDeclaration( /* modifiers */ undefined, /* dotDotDotToken */ undefined, /* name */ 'this', /* questionToken */ undefined, /* type */ ts.factory.createTypeReferenceNode(name, typeArguments), /* initializer */ undefined, ); } /** * Process an `AST` expression and convert it into a `ts.Expression`, generating references to the * correct identifiers in the current scope. */ function tcbExpression(ast: AST, tcb: Context, scope: Scope): ts.Expression { const translator = new TcbExpressionTranslator(tcb, scope); return translator.translate(ast); }
{ "end_byte": 99741, "start_byte": 93144, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_99743_108527
ass TcbExpressionTranslator { constructor( protected tcb: Context, protected scope: Scope, ) {} translate(ast: AST): ts.Expression { // `astToTypescript` actually does the conversion. A special resolver `tcbResolve` is passed // which interprets specific expression nodes that interact with the `ImplicitReceiver`. These // nodes actually refer to identifiers within the current scope. return astToTypescript(ast, (ast) => this.resolve(ast), this.tcb.env.config); } /** * Resolve an `AST` expression within the given scope. * * Some `AST` expressions refer to top-level concepts (references, variables, the component * context). This method assists in resolving those. */ protected resolve(ast: AST): ts.Expression | null { if ( ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver && !(ast.receiver instanceof ThisReceiver) ) { // Try to resolve a bound target for this expression. If no such target is available, then // the expression is referencing the top-level component context. In that case, `null` is // returned here to let it fall through resolution so it will be caught when the // `ImplicitReceiver` is resolved in the branch below. const target = this.tcb.boundTarget.getExpressionTarget(ast); const targetExpression = target === null ? null : this.getTargetNodeExpression(target, ast); if ( target instanceof TmplAstLetDeclaration && !this.isValidLetDeclarationAccess(target, ast) ) { this.tcb.oobRecorder.letUsedBeforeDefinition(this.tcb.id, ast, target); // Cast the expression to `any` so we don't produce additional diagnostics. // We don't use `markIgnoreForDiagnostics` here, because it won't prevent duplicate // diagnostics for nested accesses in cases like `@let value = value.foo.bar.baz`. if (targetExpression !== null) { return ts.factory.createAsExpression( targetExpression, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } } return targetExpression; } else if (ast instanceof PropertyWrite && ast.receiver instanceof ImplicitReceiver) { const target = this.tcb.boundTarget.getExpressionTarget(ast); if (target === null) { return null; } const targetExpression = this.getTargetNodeExpression(target, ast); const expr = this.translate(ast.value); const result = ts.factory.createParenthesizedExpression( ts.factory.createBinaryExpression(targetExpression, ts.SyntaxKind.EqualsToken, expr), ); addParseSpanInfo(result, ast.sourceSpan); // Ignore diagnostics from TS produced for writes to `@let` and re-report them using // our own infrastructure. We can't rely on the TS reporting, because it includes // the name of the auto-generated TCB variable name. if (target instanceof TmplAstLetDeclaration) { markIgnoreDiagnostics(result); this.tcb.oobRecorder.illegalWriteToLetDeclaration(this.tcb.id, ast, target); } return result; } else if (ast instanceof ImplicitReceiver) { // AST instances representing variables and references look very similar to property reads // or method calls from the component context: both have the shape // PropertyRead(ImplicitReceiver, 'propName') or Call(ImplicitReceiver, 'methodName'). // // `translate` will first try to `resolve` the outer PropertyRead/Call. If this works, // it's because the `BoundTarget` found an expression target for the whole expression, and // therefore `translate` will never attempt to `resolve` the ImplicitReceiver of that // PropertyRead/Call. // // Therefore if `resolve` is called on an `ImplicitReceiver`, it's because no outer // PropertyRead/Call resolved to a variable or reference, and therefore this is a // property read or method call on the component context itself. return ts.factory.createThis(); } else if (ast instanceof BindingPipe) { const expr = this.translate(ast.exp); const pipeMeta = this.tcb.getPipeByName(ast.name); let pipe: ts.Expression | null; if (pipeMeta === null) { // No pipe by that name exists in scope. Record this as an error. this.tcb.oobRecorder.missingPipe(this.tcb.id, ast); // Use an 'any' value to at least allow the rest of the expression to be checked. pipe = ANY_EXPRESSION; } else if ( pipeMeta.isExplicitlyDeferred && this.tcb.boundTarget.getEagerlyUsedPipes().includes(ast.name) ) { // This pipe was defer-loaded (included into `@Component.deferredImports`), // but was used outside of a `@defer` block, which is the error. this.tcb.oobRecorder.deferredPipeUsedEagerly(this.tcb.id, ast); // Use an 'any' value to at least allow the rest of the expression to be checked. pipe = ANY_EXPRESSION; } else { // Use a variable declared as the pipe's type. pipe = this.tcb.env.pipeInst( pipeMeta.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>, ); } const args = ast.args.map((arg) => this.translate(arg)); let methodAccess: ts.Expression = ts.factory.createPropertyAccessExpression( pipe, 'transform', ); addParseSpanInfo(methodAccess, ast.nameSpan); if (!this.tcb.env.config.checkTypeOfPipes) { methodAccess = ts.factory.createAsExpression( methodAccess, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } const result = ts.factory.createCallExpression( /* expression */ methodAccess, /* typeArguments */ undefined, /* argumentsArray */ [expr, ...args], ); addParseSpanInfo(result, ast.sourceSpan); return result; } else if ( (ast instanceof Call || ast instanceof SafeCall) && (ast.receiver instanceof PropertyRead || ast.receiver instanceof SafePropertyRead) ) { // Resolve the special `$any(expr)` syntax to insert a cast of the argument to type `any`. // `$any(expr)` -> `expr as any` if ( ast.receiver.receiver instanceof ImplicitReceiver && !(ast.receiver.receiver instanceof ThisReceiver) && ast.receiver.name === '$any' && ast.args.length === 1 ) { const expr = this.translate(ast.args[0]); const exprAsAny = ts.factory.createAsExpression( expr, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); const result = ts.factory.createParenthesizedExpression(exprAsAny); addParseSpanInfo(result, ast.sourceSpan); return result; } // Attempt to resolve a bound target for the method, and generate the method call if a target // could be resolved. If no target is available, then the method is referencing the top-level // component context, in which case `null` is returned to let the `ImplicitReceiver` being // resolved to the component context. const target = this.tcb.boundTarget.getExpressionTarget(ast); if (target === null) { return null; } const receiver = this.getTargetNodeExpression(target, ast); const method = wrapForDiagnostics(receiver); addParseSpanInfo(method, ast.receiver.nameSpan); const args = ast.args.map((arg) => this.translate(arg)); const node = ts.factory.createCallExpression(method, undefined, args); addParseSpanInfo(node, ast.sourceSpan); return node; } else { // This AST isn't special after all. return null; } } private getTargetNodeExpression(targetNode: TemplateEntity, expressionNode: AST): ts.Expression { const expr = this.scope.resolve(targetNode); addParseSpanInfo(expr, expressionNode.sourceSpan); return expr; } protected isValidLetDeclarationAccess(target: TmplAstLetDeclaration, ast: PropertyRead): boolean { const targetStart = target.sourceSpan.start.offset; const targetEnd = target.sourceSpan.end.offset; const astStart = ast.sourceSpan.start; // We only flag local references that occur before the declaration, because embedded views // are updated before the child views. In practice this means that something like // `<ng-template [ngIf]="true">{{value}}</ng-template> @let value = 1;` is valid. return (targetStart < astStart && astStart > targetEnd) || !this.scope.isLocal(target); } } /** * Call the type constructor of a directive instance on a given template node, inferring a type for * the directive instance from any bound inputs. */ f
{ "end_byte": 108527, "start_byte": 99743, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_108528_117294
nction tcbCallTypeCtor( dir: TypeCheckableDirectiveMeta, tcb: Context, inputs: TcbDirectiveInput[], ): ts.Expression { const typeCtor = tcb.env.typeCtorFor(dir); // Construct an array of `ts.PropertyAssignment`s for each of the directive's inputs. const members = inputs.map((input) => { const propertyName = ts.factory.createStringLiteral(input.field); if (input.type === 'binding') { // For bound inputs, the property is assigned the binding expression. let expr = widenBinding(input.expression, tcb); if (input.isTwoWayBinding && tcb.env.config.allowSignalsInTwoWayBindings) { expr = unwrapWritableSignal(expr, tcb); } const assignment = ts.factory.createPropertyAssignment( propertyName, wrapForDiagnostics(expr), ); addParseSpanInfo(assignment, input.sourceSpan); return assignment; } else { // A type constructor is required to be called with all input properties, so any unset // inputs are simply assigned a value of type `any` to ignore them. return ts.factory.createPropertyAssignment(propertyName, ANY_EXPRESSION); } }); // Call the `ngTypeCtor` method on the directive class, with an object literal argument created // from the matched inputs. return ts.factory.createCallExpression( /* expression */ typeCtor, /* typeArguments */ undefined, /* argumentsArray */ [ts.factory.createObjectLiteralExpression(members)], ); } function getBoundAttributes( directive: TypeCheckableDirectiveMeta, node: TmplAstTemplate | TmplAstElement, ): TcbBoundAttribute[] { const boundInputs: TcbBoundAttribute[] = []; const processAttribute = (attr: TmplAstBoundAttribute | TmplAstTextAttribute) => { // Skip non-property bindings. if ( attr instanceof TmplAstBoundAttribute && attr.type !== BindingType.Property && attr.type !== BindingType.TwoWay ) { return; } // Skip the attribute if the directive does not have an input for it. const inputs = directive.inputs.getByBindingPropertyName(attr.name); if (inputs !== null) { boundInputs.push({ attribute: attr, inputs: inputs.map((input) => { return { fieldName: input.classPropertyName, required: input.required, transformType: input.transform?.type || null, isSignal: input.isSignal, isTwoWayBinding: attr instanceof TmplAstBoundAttribute && attr.type === BindingType.TwoWay, }; }), }); } }; node.inputs.forEach(processAttribute); node.attributes.forEach(processAttribute); if (node instanceof TmplAstTemplate) { node.templateAttrs.forEach(processAttribute); } return boundInputs; } /** * Translates the given attribute binding to a `ts.Expression`. */ function translateInput( attr: TmplAstBoundAttribute | TmplAstTextAttribute, tcb: Context, scope: Scope, ): ts.Expression { if (attr instanceof TmplAstBoundAttribute) { // Produce an expression representing the value of the binding. return tcbExpression(attr.value, tcb, scope); } else { // For regular attributes with a static string value, use the represented string literal. return ts.factory.createStringLiteral(attr.value); } } /** * Potentially widens the type of `expr` according to the type-checking configuration. */ function widenBinding(expr: ts.Expression, tcb: Context): ts.Expression { if (!tcb.env.config.checkTypeOfInputBindings) { // If checking the type of bindings is disabled, cast the resulting expression to 'any' // before the assignment. return tsCastToAny(expr); } else if (!tcb.env.config.strictNullInputBindings) { if (ts.isObjectLiteralExpression(expr) || ts.isArrayLiteralExpression(expr)) { // Object literals and array literals should not be wrapped in non-null assertions as that // would cause literals to be prematurely widened, resulting in type errors when assigning // into a literal type. return expr; } else { // If strict null checks are disabled, erase `null` and `undefined` from the type by // wrapping the expression in a non-null assertion. return ts.factory.createNonNullExpression(expr); } } else { // No widening is requested, use the expression as is. return expr; } } /** * Wraps an expression in an `unwrapSignal` call which extracts the signal's value. */ function unwrapWritableSignal(expression: ts.Expression, tcb: Context): ts.CallExpression { const unwrapRef = tcb.env.referenceExternalSymbol( R3Identifiers.unwrapWritableSignal.moduleName, R3Identifiers.unwrapWritableSignal.name, ); return ts.factory.createCallExpression(unwrapRef, undefined, [expression]); } /** * An input binding that corresponds with a field of a directive. */ interface TcbDirectiveBoundInput { type: 'binding'; /** * The name of a field on the directive that is set. */ field: string; /** * The `ts.Expression` corresponding with the input binding expression. */ expression: ts.Expression; /** * The source span of the full attribute binding. */ sourceSpan: ParseSourceSpan; /** * Whether the binding is part of a two-way binding. */ isTwoWayBinding: boolean; } /** * Indicates that a certain field of a directive does not have a corresponding input binding. */ interface TcbDirectiveUnsetInput { type: 'unset'; /** * The name of a field on the directive for which no input binding is present. */ field: string; } type TcbDirectiveInput = TcbDirectiveBoundInput | TcbDirectiveUnsetInput; const EVENT_PARAMETER = '$event'; const enum EventParamType { /* Generates code to infer the type of `$event` based on how the listener is registered. */ Infer, /* Declares the type of the `$event` parameter as `any`. */ Any, } /** * Creates an arrow function to be used as handler function for event bindings. The handler * function has a single parameter `$event` and the bound event's handler `AST` represented as a * TypeScript expression as its body. * * When `eventType` is set to `Infer`, the `$event` parameter will not have an explicit type. This * allows for the created handler function to have its `$event` parameter's type inferred based on * how it's used, to enable strict type checking of event bindings. When set to `Any`, the `$event` * parameter will have an explicit `any` type, effectively disabling strict type checking of event * bindings. Alternatively, an explicit type can be passed for the `$event` parameter. */ function tcbCreateEventHandler( event: TmplAstBoundEvent, tcb: Context, scope: Scope, eventType: EventParamType | ts.TypeNode, ): ts.Expression { const handler = tcbEventHandlerExpression(event.handler, tcb, scope); let eventParamType: ts.TypeNode | undefined; if (eventType === EventParamType.Infer) { eventParamType = undefined; } else if (eventType === EventParamType.Any) { eventParamType = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); } else { eventParamType = eventType; } // Obtain all guards that have been applied to the scope and its parents, as they have to be // repeated within the handler function for their narrowing to be in effect within the handler. const guards = scope.guards(); let body: ts.Statement = ts.factory.createExpressionStatement(handler); if (guards !== null) { // Wrap the body in an `if` statement containing all guards that have to be applied. body = ts.factory.createIfStatement(guards, body); } const eventParam = ts.factory.createParameterDeclaration( /* modifiers */ undefined, /* dotDotDotToken */ undefined, /* name */ EVENT_PARAMETER, /* questionToken */ undefined, /* type */ eventParamType, ); addExpressionIdentifier(eventParam, ExpressionIdentifier.EVENT_PARAMETER); // Return an arrow function instead of a function expression to preserve the `this` context. return ts.factory.createArrowFunction( /* modifiers */ undefined, /* typeParameters */ undefined, /* parameters */ [eventParam], /* type */ ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), /* equalsGreaterThanToken */ undefined, /* body */ ts.factory.createBlock([body]), ); } /** * Similar to `tcbExpression`, this function converts the provided `AST` expression into a * `ts.Expression`, with special handling of the `$event` variable that can be used within event * bindings. */ function tcbEventHandlerExpression(ast: AST, tcb: Context, scope: Scope): ts.Expression { const translator = new TcbEventHandlerTranslator(tcb, scope); return translator.translate(ast); }
{ "end_byte": 117294, "start_byte": 108528, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts_117296_120525
nction isSplitTwoWayBinding( inputName: string, output: TmplAstBoundEvent, inputs: TmplAstBoundAttribute[], tcb: Context, ) { const input = inputs.find((input) => input.name === inputName); if (input === undefined || input.sourceSpan !== output.sourceSpan) { return false; } // Input consumer should be a directive because it's claimed const inputConsumer = tcb.boundTarget.getConsumerOfBinding(input) as TypeCheckableDirectiveMeta; const outputConsumer = tcb.boundTarget.getConsumerOfBinding(output); if ( outputConsumer === null || inputConsumer.ref === undefined || outputConsumer instanceof TmplAstTemplate ) { return false; } if (outputConsumer instanceof TmplAstElement) { tcb.oobRecorder.splitTwoWayBinding( tcb.id, input, output, inputConsumer.ref.node, outputConsumer, ); return true; } else if (outputConsumer.ref !== inputConsumer.ref) { tcb.oobRecorder.splitTwoWayBinding( tcb.id, input, output, inputConsumer.ref.node, outputConsumer.ref.node, ); return true; } return false; } class TcbEventHandlerTranslator extends TcbExpressionTranslator { protected override resolve(ast: AST): ts.Expression | null { // Recognize a property read on the implicit receiver corresponding with the event parameter // that is available in event bindings. Since this variable is a parameter of the handler // function that the converted expression becomes a child of, just create a reference to the // parameter by its name. if ( ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver && !(ast.receiver instanceof ThisReceiver) && ast.name === EVENT_PARAMETER ) { const event = ts.factory.createIdentifier(EVENT_PARAMETER); addParseSpanInfo(event, ast.nameSpan); return event; } return super.resolve(ast); } protected override isValidLetDeclarationAccess(): boolean { // Event listeners are allowed to read `@let` declarations before // they're declared since the callback won't be executed immediately. return true; } } class TcbForLoopTrackTranslator extends TcbExpressionTranslator { private allowedVariables: Set<TmplAstVariable>; constructor( tcb: Context, scope: Scope, private block: TmplAstForLoopBlock, ) { super(tcb, scope); // Tracking expressions are only allowed to read the `$index`, // the item and properties off the component instance. this.allowedVariables = new Set([block.item]); for (const variable of block.contextVariables) { if (variable.value === '$index') { this.allowedVariables.add(variable); } } } protected override resolve(ast: AST): ts.Expression | null { if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver) { const target = this.tcb.boundTarget.getExpressionTarget(ast); if ( target !== null && (!(target instanceof TmplAstVariable) || !this.allowedVariables.has(target)) ) { this.tcb.oobRecorder.illegalForLoopTrackAccess(this.tcb.id, this.block, ast); } } return super.resolve(ast); } }
{ "end_byte": 120525, "start_byte": 117296, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/completion.ts_0_8490
/** * @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.dev/license */ import { AST, EmptyExpr, ImplicitReceiver, LetDeclaration, LiteralPrimitive, PropertyRead, PropertyWrite, SafePropertyRead, TmplAstLetDeclaration, TmplAstNode, TmplAstReference, TmplAstTemplate, TmplAstTextAttribute, } from '@angular/compiler'; import ts from 'typescript'; import {AbsoluteFsPath} from '../../file_system'; import { CompletionKind, GlobalCompletion, ReferenceCompletion, TcbLocation, VariableCompletion, LetDeclarationCompletion, } from '../api'; import {ExpressionIdentifier, findFirstMatchingNode} from './comments'; import {TemplateData} from './context'; /** * Powers autocompletion for a specific component. * * Internally caches autocompletion results, and must be discarded if the component template or * surrounding TS program have changed. */ export class CompletionEngine { private componentContext: TcbLocation | null; /** * Cache of completions for various levels of the template, including the root template (`null`). * Memoizes `getTemplateContextCompletions`. */ private templateContextCache = new Map< TmplAstTemplate | null, Map<string, ReferenceCompletion | VariableCompletion | LetDeclarationCompletion> >(); private expressionCompletionCache = new Map< PropertyRead | SafePropertyRead | LiteralPrimitive | TmplAstTextAttribute, TcbLocation >(); constructor( private tcb: ts.Node, private data: TemplateData, private tcbPath: AbsoluteFsPath, private tcbIsShim: boolean, ) { // Find the component completion expression within the TCB. This looks like: `ctx. /* ... */;` const globalRead = findFirstMatchingNode(this.tcb, { filter: ts.isPropertyAccessExpression, withExpressionIdentifier: ExpressionIdentifier.COMPONENT_COMPLETION, }); if (globalRead !== null) { this.componentContext = { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, // `globalRead.name` is an empty `ts.Identifier`, so its start position immediately follows // the `.` in `ctx.`. TS autocompletion APIs can then be used to access completion results // for the component context. positionInFile: globalRead.name.getStart(), }; } else { this.componentContext = null; } } /** * Get global completions within the given template context and AST node. * * @param context the given template context - either a `TmplAstTemplate` embedded view, or `null` * for the root * template context. * @param node the given AST node */ getGlobalCompletions( context: TmplAstTemplate | null, node: AST | TmplAstNode, ): GlobalCompletion | null { if (this.componentContext === null) { return null; } const templateContext = this.getTemplateContextCompletions(context); if (templateContext === null) { return null; } let nodeContext: TcbLocation | null = null; if (node instanceof EmptyExpr) { const nodeLocation = findFirstMatchingNode(this.tcb, { filter: ts.isIdentifier, withSpan: node.sourceSpan, }); if (nodeLocation !== null) { nodeContext = { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: nodeLocation.getStart(), }; } } if (node instanceof PropertyRead && node.receiver instanceof ImplicitReceiver) { const nodeLocation = findFirstMatchingNode(this.tcb, { filter: ts.isPropertyAccessExpression, withSpan: node.sourceSpan, }); if (nodeLocation) { nodeContext = { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: nodeLocation.getStart(), }; } } return { componentContext: this.componentContext, templateContext, nodeContext, }; } getExpressionCompletionLocation( expr: PropertyRead | PropertyWrite | SafePropertyRead, ): TcbLocation | null { if (this.expressionCompletionCache.has(expr)) { return this.expressionCompletionCache.get(expr)!; } // Completion works inside property reads and method calls. let tsExpr: ts.PropertyAccessExpression | null = null; if (expr instanceof PropertyRead || expr instanceof PropertyWrite) { // Non-safe navigation operations are trivial: `foo.bar` or `foo.bar()` tsExpr = findFirstMatchingNode(this.tcb, { filter: ts.isPropertyAccessExpression, withSpan: expr.nameSpan, }); } else if (expr instanceof SafePropertyRead) { // Safe navigation operations are a little more complex, and involve a ternary. Completion // happens in the "true" case of the ternary. const ternaryExpr = findFirstMatchingNode(this.tcb, { filter: ts.isParenthesizedExpression, withSpan: expr.sourceSpan, }); if (ternaryExpr === null || !ts.isConditionalExpression(ternaryExpr.expression)) { return null; } const whenTrue = ternaryExpr.expression.whenTrue; if (ts.isPropertyAccessExpression(whenTrue)) { tsExpr = whenTrue; } else if ( ts.isCallExpression(whenTrue) && ts.isPropertyAccessExpression(whenTrue.expression) ) { tsExpr = whenTrue.expression; } } if (tsExpr === null) { return null; } const res: TcbLocation = { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: tsExpr.name.getEnd(), }; this.expressionCompletionCache.set(expr, res); return res; } getLiteralCompletionLocation(expr: LiteralPrimitive | TmplAstTextAttribute): TcbLocation | null { if (this.expressionCompletionCache.has(expr)) { return this.expressionCompletionCache.get(expr)!; } let tsExpr: ts.StringLiteral | ts.NumericLiteral | null = null; if (expr instanceof TmplAstTextAttribute) { const strNode = findFirstMatchingNode(this.tcb, { filter: ts.isParenthesizedExpression, withSpan: expr.sourceSpan, }); if (strNode !== null && ts.isStringLiteral(strNode.expression)) { tsExpr = strNode.expression; } } else { tsExpr = findFirstMatchingNode(this.tcb, { filter: (n: ts.Node): n is ts.NumericLiteral | ts.StringLiteral => ts.isStringLiteral(n) || ts.isNumericLiteral(n), withSpan: expr.sourceSpan, }); } if (tsExpr === null) { return null; } let positionInShimFile = tsExpr.getEnd(); if (ts.isStringLiteral(tsExpr)) { // In the shimFile, if `tsExpr` is a string, the position should be in the quotes. positionInShimFile -= 1; } const res: TcbLocation = { tcbPath: this.tcbPath, isShimFile: this.tcbIsShim, positionInFile: positionInShimFile, }; this.expressionCompletionCache.set(expr, res); return res; } /** * Get global completions within the given template context - either a `TmplAstTemplate` embedded * view, or `null` for the root context. */ private getTemplateContextCompletions( context: TmplAstTemplate | null, ): Map<string, ReferenceCompletion | VariableCompletion | LetDeclarationCompletion> | null { if (this.templateContextCache.has(context)) { return this.templateContextCache.get(context)!; } const templateContext = new Map< string, ReferenceCompletion | VariableCompletion | LetDeclarationCompletion >(); // The bound template already has details about the references and variables in scope in the // `context` template - they just need to be converted to `Completion`s. for (const node of this.data.boundTarget.getEntitiesInScope(context)) { if (node instanceof TmplAstReference) { templateContext.set(node.name, { kind: CompletionKind.Reference, node, }); } else if (node instanceof TmplAstLetDeclaration) { templateContext.set(node.name, { kind: CompletionKind.LetDeclaration, node, }); } else { templateContext.set(node.name, { kind: CompletionKind.Variable, node, }); } } this.templateContextCache.set(context, templateContext); return templateContext; } }
{ "end_byte": 8490, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/completion.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/symbol_util.ts_0_1577
/*! * @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.dev/license */ import ts from 'typescript'; import {Symbol, SymbolKind} from '../api'; /** Names of known signal functions. */ const SIGNAL_FNS = new Set([ 'WritableSignal', 'Signal', 'InputSignal', 'InputSignalWithTransform', 'ModelSignal', ]); /** Returns whether a symbol is a reference to a signal. */ export function isSignalReference(symbol: Symbol): boolean { return ( (symbol.kind === SymbolKind.Expression || symbol.kind === SymbolKind.Variable || symbol.kind === SymbolKind.LetDeclaration) && // Note that `tsType.symbol` isn't optional in the typings, // but it appears that it can be undefined at runtime. ((symbol.tsType.symbol !== undefined && isSignalSymbol(symbol.tsType.symbol)) || (symbol.tsType.aliasSymbol !== undefined && isSignalSymbol(symbol.tsType.aliasSymbol))) ); } /** Checks whether a symbol points to a signal. */ function isSignalSymbol(symbol: ts.Symbol): boolean { const declarations = symbol.getDeclarations(); return ( declarations !== undefined && declarations.some((decl) => { const fileName = decl.getSourceFile().fileName; return ( (ts.isInterfaceDeclaration(decl) || ts.isTypeAliasDeclaration(decl)) && SIGNAL_FNS.has(decl.name.text) && (fileName.includes('@angular/core') || fileName.includes('angular2/rc/packages/core')) ); }) ); }
{ "end_byte": 1577, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/symbol_util.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.ts_0_4822
/** * @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.dev/license */ import ts from 'typescript'; import {AbsoluteFsPath, join} from '../../file_system'; import {Reference, ReferenceEmitter} from '../../imports'; import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {ImportManager} from '../../translator'; import {TypeCheckBlockMetadata, TypeCheckingConfig} from '../api'; import {DomSchemaChecker} from './dom'; import {Environment} from './environment'; import {OutOfBandDiagnosticRecorder} from './oob'; import {ensureTypeCheckFilePreparationImports} from './tcb_util'; import {generateTypeCheckBlock, TcbGenericContextBehavior} from './type_check_block'; /** * An `Environment` representing the single type-checking file into which most (if not all) Type * Check Blocks (TCBs) will be generated. * * The `TypeCheckFile` hosts multiple TCBs and allows the sharing of declarations (e.g. type * constructors) between them. Rather than return such declarations via `getPreludeStatements()`, it * hoists them to the top of the generated `ts.SourceFile`. */ export class TypeCheckFile extends Environment { private nextTcbId = 1; private tcbStatements: ts.Statement[] = []; constructor( readonly fileName: AbsoluteFsPath, config: TypeCheckingConfig, refEmitter: ReferenceEmitter, reflector: ReflectionHost, compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, ) { super( config, new ImportManager({ // This minimizes noticeable changes with older versions of `ImportManager`. forceGenerateNamespacesForNewImports: true, // Type check block code affects code completion and fix suggestions. // We want to encourage single quotes for now, like we always did. shouldUseSingleQuotes: () => true, }), refEmitter, reflector, ts.createSourceFile( compilerHost.getCanonicalFileName(fileName), '', ts.ScriptTarget.Latest, true, ), ); } addTypeCheckBlock( ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, meta: TypeCheckBlockMetadata, domSchemaChecker: DomSchemaChecker, oobRecorder: OutOfBandDiagnosticRecorder, genericContextBehavior: TcbGenericContextBehavior, ): void { const fnId = ts.factory.createIdentifier(`_tcb${this.nextTcbId++}`); const fn = generateTypeCheckBlock( this, ref, fnId, meta, domSchemaChecker, oobRecorder, genericContextBehavior, ); this.tcbStatements.push(fn); } render(removeComments: boolean): string { // NOTE: We are conditionally adding imports whenever we discover signal inputs. This has a // risk of changing the import graph of the TypeScript program, degrading incremental program // re-use due to program structure changes. For type check block files, we are ensuring an // import to e.g. `@angular/core` always exists to guarantee a stable graph. ensureTypeCheckFilePreparationImports(this); const importChanges = this.importManager.finalize(); if (importChanges.updatedImports.size > 0) { throw new Error( 'AssertionError: Expected no imports to be updated for a new type check file.', ); } const printer = ts.createPrinter({removeComments}); let source = ''; const newImports = importChanges.newImports.get(this.contextFile.fileName); if (newImports !== undefined) { source += newImports .map((i) => printer.printNode(ts.EmitHint.Unspecified, i, this.contextFile)) .join('\n'); } source += '\n'; for (const stmt of this.pipeInstStatements) { source += printer.printNode(ts.EmitHint.Unspecified, stmt, this.contextFile) + '\n'; } for (const stmt of this.typeCtorStatements) { source += printer.printNode(ts.EmitHint.Unspecified, stmt, this.contextFile) + '\n'; } source += '\n'; for (const stmt of this.tcbStatements) { source += printer.printNode(ts.EmitHint.Unspecified, stmt, this.contextFile) + '\n'; } // Ensure the template type-checking file is an ES module. Otherwise, it's interpreted as some // kind of global namespace in TS, which forces a full re-typecheck of the user's program that // is somehow more expensive than the initial parse. source += '\nexport const IS_A_MODULE = true;\n'; return source; } override getPreludeStatements(): ts.Statement[] { return []; } } export function typeCheckFilePath(rootDirs: AbsoluteFsPath[]): AbsoluteFsPath { const shortest = rootDirs.concat([]).sort((a, b) => a.length - b.length)[0]; return join(shortest, '__ng_typecheck__.ts'); }
{ "end_byte": 4822, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.ts" }
angular/packages/compiler-cli/src/ngtsc/resource/BUILD.bazel_0_553
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "resource", srcs = ["index.ts"] + glob([ "src/*.ts", ]), module_name = "@angular/compiler-cli/src/ngtsc/resource", deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/annotations", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], )
{ "end_byte": 553, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/resource/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/resource/index.ts_0_256
/** * @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.dev/license */ export {AdapterResourceLoader} from './src/loader';
{ "end_byte": 256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/resource/index.ts" }
angular/packages/compiler-cli/src/ngtsc/resource/src/loader.ts_0_766
/** * @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.dev/license */ import ts from 'typescript'; import {ResourceLoader, ResourceLoaderContext} from '../../annotations'; import {NgCompilerAdapter, ResourceHostContext} from '../../core/api'; import {AbsoluteFsPath, join, PathSegment} from '../../file_system'; import {RequiredDelegations} from '../../util/src/typescript'; const CSS_PREPROCESSOR_EXT = /(\.scss|\.sass|\.less|\.styl)$/; const RESOURCE_MARKER = '.$ngresource$'; const RESOURCE_MARKER_TS = RESOURCE_MARKER + '.ts'; /** * `ResourceLoader` which delegates to an `NgCompilerAdapter`'s resource loading methods. */
{ "end_byte": 766, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/resource/src/loader.ts" }
angular/packages/compiler-cli/src/ngtsc/resource/src/loader.ts_767_9693
export class AdapterResourceLoader implements ResourceLoader { private cache = new Map<string, string>(); private fetching = new Map<string, Promise<void>>(); private lookupResolutionHost: RequiredDelegations<ts.ModuleResolutionHost>; canPreload: boolean; canPreprocess: boolean; constructor( private adapter: NgCompilerAdapter, private options: ts.CompilerOptions, ) { this.lookupResolutionHost = createLookupResolutionHost(this.adapter); this.canPreload = !!this.adapter.readResource; this.canPreprocess = !!this.adapter.transformResource; } /** * Resolve the url of a resource relative to the file that contains the reference to it. * The return value of this method can be used in the `load()` and `preload()` methods. * * Uses the provided CompilerHost if it supports mapping resources to filenames. * Otherwise, uses a fallback mechanism that searches the module resolution candidates. * * @param url The, possibly relative, url of the resource. * @param fromFile The path to the file that contains the URL of the resource. * @returns A resolved url of resource. * @throws An error if the resource cannot be resolved. */ resolve(url: string, fromFile: string): string { let resolvedUrl: string | null = null; if (this.adapter.resourceNameToFileName) { resolvedUrl = this.adapter.resourceNameToFileName( url, fromFile, (url: string, fromFile: string) => this.fallbackResolve(url, fromFile), ); } else { resolvedUrl = this.fallbackResolve(url, fromFile); } if (resolvedUrl === null) { throw new Error(`HostResourceResolver: could not resolve ${url} in context of ${fromFile})`); } return resolvedUrl; } /** * Preload the specified resource, asynchronously. * * Once the resource is loaded, its value is cached so it can be accessed synchronously via the * `load()` method. * * @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to preload. * @param context Information about the resource such as the type and containing file. * @returns A Promise that is resolved once the resource has been loaded or `undefined` if the * file has already been loaded. * @throws An Error if pre-loading is not available. */ preload(resolvedUrl: string, context: ResourceLoaderContext): Promise<void> | undefined { if (!this.adapter.readResource) { throw new Error( 'HostResourceLoader: the CompilerHost provided does not support pre-loading resources.', ); } if (this.cache.has(resolvedUrl)) { return undefined; } else if (this.fetching.has(resolvedUrl)) { return this.fetching.get(resolvedUrl); } let result = this.adapter.readResource(resolvedUrl); if (this.adapter.transformResource && context.type === 'style') { const resourceContext: ResourceHostContext = { type: 'style', containingFile: context.containingFile, resourceFile: resolvedUrl, className: context.className, }; result = Promise.resolve(result).then(async (str) => { const transformResult = await this.adapter.transformResource!(str, resourceContext); return transformResult === null ? str : transformResult.content; }); } if (typeof result === 'string') { this.cache.set(resolvedUrl, result); return undefined; } else { const fetchCompletion = result.then((str) => { this.fetching.delete(resolvedUrl); this.cache.set(resolvedUrl, str); }); this.fetching.set(resolvedUrl, fetchCompletion); return fetchCompletion; } } /** * Preprocess the content data of an inline resource, asynchronously. * * @param data The existing content data from the inline resource. * @param context Information regarding the resource such as the type and containing file. * @returns A Promise that resolves to the processed data. If no processing occurs, the * same data string that was passed to the function will be resolved. */ async preprocessInline(data: string, context: ResourceLoaderContext): Promise<string> { if (!this.adapter.transformResource || context.type !== 'style') { return data; } const transformResult = await this.adapter.transformResource(data, { type: 'style', containingFile: context.containingFile, resourceFile: null, order: context.order, className: context.className, }); if (transformResult === null) { return data; } return transformResult.content; } /** * Load the resource at the given url, synchronously. * * The contents of the resource may have been cached by a previous call to `preload()`. * * @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to load. * @returns The contents of the resource. */ load(resolvedUrl: string): string { if (this.cache.has(resolvedUrl)) { return this.cache.get(resolvedUrl)!; } const result = this.adapter.readResource ? this.adapter.readResource(resolvedUrl) : this.adapter.readFile(resolvedUrl); if (typeof result !== 'string') { throw new Error(`HostResourceLoader: loader(${resolvedUrl}) returned a Promise`); } this.cache.set(resolvedUrl, result); return result; } /** * Invalidate the entire resource cache. */ invalidate(): void { this.cache.clear(); } /** * Attempt to resolve `url` in the context of `fromFile`, while respecting the rootDirs * option from the tsconfig. First, normalize the file name. */ private fallbackResolve(url: string, fromFile: string): string | null { let candidateLocations: string[]; if (url.startsWith('/')) { // This path is not really an absolute path, but instead the leading '/' means that it's // rooted in the project rootDirs. So look for it according to the rootDirs. candidateLocations = this.getRootedCandidateLocations(url); } else { // This path is a "relative" path and can be resolved as such. To make this easier on the // downstream resolver, the './' prefix is added if missing to distinguish these paths from // absolute node_modules paths. if (!url.startsWith('.')) { url = `./${url}`; } candidateLocations = this.getResolvedCandidateLocations(url, fromFile); } for (const candidate of candidateLocations) { if (this.adapter.fileExists(candidate)) { return candidate; } else if (CSS_PREPROCESSOR_EXT.test(candidate)) { /** * If the user specified styleUrl points to *.scss, but the Sass compiler was run before * Angular, then the resource may have been generated as *.css. Simply try the resolution * again. */ const cssFallbackUrl = candidate.replace(CSS_PREPROCESSOR_EXT, '.css'); if (this.adapter.fileExists(cssFallbackUrl)) { return cssFallbackUrl; } } } return null; } private getRootedCandidateLocations(url: string): AbsoluteFsPath[] { // The path already starts with '/', so add a '.' to make it relative. const segment: PathSegment = ('.' + url) as PathSegment; return this.adapter.rootDirs.map((rootDir) => join(rootDir, segment)); } /** * TypeScript provides utilities to resolve module names, but not resource files (which aren't * a part of the ts.Program). However, TypeScript's module resolution can be used creatively * to locate where resource files should be expected to exist. Since module resolution returns * a list of file names that were considered, the loader can enumerate the possible locations * for the file by setting up a module resolution for it that will fail. */ private getResolvedCandidateLocations(url: string, fromFile: string): string[] { // `failedLookupLocations` is in the name of the type ts.ResolvedModuleWithFailedLookupLocations // but is marked @internal in TypeScript. See // https://github.com/Microsoft/TypeScript/issues/28770. type ResolvedModuleWithFailedLookupLocations = ts.ResolvedModuleWithFailedLookupLocations & { failedLookupLocations: ReadonlyArray<string>; }; const failedLookup = ts.resolveModuleName( url + RESOURCE_MARKER, fromFile, this.options, this.lookupResolutionHost, ) as ResolvedModuleWithFailedLookupLocations; if (failedLookup.failedLookupLocations === undefined) { throw new Error( `Internal error: expected to find failedLookupLocations during resolution of resource '${url}' in context of ${fromFile}`, ); } return failedLookup.failedLookupLocations .filter((candidate) => candidate.endsWith(RESOURCE_MARKER_TS)) .map((candidate) => candidate.slice(0, -RESOURCE_MARKER_TS.length)); } }
{ "end_byte": 9693, "start_byte": 767, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/resource/src/loader.ts" }
angular/packages/compiler-cli/src/ngtsc/resource/src/loader.ts_9695_11107
/** * Derives a `ts.ModuleResolutionHost` from a compiler adapter that recognizes the special resource * marker and does not go to the filesystem for these requests, as they are known not to exist. */ function createLookupResolutionHost( adapter: NgCompilerAdapter, ): RequiredDelegations<ts.ModuleResolutionHost> { return { directoryExists(directoryName: string): boolean { if (directoryName.includes(RESOURCE_MARKER)) { return false; } else if (adapter.directoryExists !== undefined) { return adapter.directoryExists(directoryName); } else { // TypeScript's module resolution logic assumes that the directory exists when no host // implementation is available. return true; } }, fileExists(fileName: string): boolean { if (fileName.includes(RESOURCE_MARKER)) { return false; } else { return adapter.fileExists(fileName); } }, readFile: adapter.readFile.bind(adapter), getCurrentDirectory: adapter.getCurrentDirectory.bind(adapter), getDirectories: adapter.getDirectories?.bind(adapter), realpath: adapter.realpath?.bind(adapter), trace: adapter.trace?.bind(adapter), useCaseSensitiveFileNames: typeof adapter.useCaseSensitiveFileNames === 'function' ? adapter.useCaseSensitiveFileNames.bind(adapter) : adapter.useCaseSensitiveFileNames, }; }
{ "end_byte": 11107, "start_byte": 9695, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/resource/src/loader.ts" }
angular/packages/compiler-cli/src/ngtsc/perf/README.md_0_1698
# What is the `perf` package? This package contains utilities for collecting performance information from around the compiler and for producing ngtsc performance traces. This feature is currently undocumented and not exposed to users as the trace file format is still unstable. # What is a performance trace? A performance trace is a JSON file which logs events within ngtsc with microsecond precision. It tracks the phase of compilation, the file and possibly symbol being compiled, and other metadata explaining what the compiler was doing during the event. Traces track two specific kinds of events: marks and spans. A mark is a single event with a timestamp, while a span is two events (start and end) that cover a section of work in the compiler. Analyzing a file is a span event, while a decision (such as deciding not to emit a particular file) is a mark event. # Enabling performance traces Performance traces are enabled via the undocumented `tracePerformance` option in `angularCompilerOptions` inside the tsconfig.json file. This option takes a string path relative to the current directory, which will be used to write the trace JSON file. ## In-Memory TS Host Tracing By default, the trace file will be written with the `fs` package directly. However, ngtsc supports in-memory compilation using a `ts.CompilerHost` for all operations. In the event that tracing is required when using an in-memory filesystem, a `ts:` prefix can be added to the value of `tracePerformance`, which will cause the trace JSON file to be written with the TS host's `writeFile` method instead. This is not done by default as `@angular/cli` does not allow writing arbitrary JSON files via its host.
{ "end_byte": 1698, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/README.md" }
angular/packages/compiler-cli/src/ngtsc/perf/BUILD.bazel_0_298
package(default_visibility = ["//visibility:public"]) load("//tools:defaults.bzl", "ts_library") ts_library( name = "perf", srcs = ["index.ts"] + glob([ "src/*.ts", ]), deps = [ "//packages:types", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 298, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/perf/index.ts_0_353
/** * @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.dev/license */ export * from './src/api'; export {NOOP_PERF_RECORDER} from './src/noop'; export {ActivePerfRecorder, DelegatingPerfRecorder} from './src/recorder';
{ "end_byte": 353, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/index.ts" }
angular/packages/compiler-cli/src/ngtsc/perf/src/noop.ts_0_573
/** * @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.dev/license */ import {PerfPhase, PerfRecorder} from './api'; class NoopPerfRecorder implements PerfRecorder { eventCount(): void {} memory(): void {} phase(): PerfPhase { return PerfPhase.Unaccounted; } inPhase<T>(phase: PerfPhase, fn: () => T): T { return fn(); } reset(): void {} } export const NOOP_PERF_RECORDER: PerfRecorder = new NoopPerfRecorder();
{ "end_byte": 573, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/src/noop.ts" }
angular/packages/compiler-cli/src/ngtsc/perf/src/api.ts_0_8282
/** * @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.dev/license */ /** * A phase of compilation for which time is tracked in a distinct bucket. */ export enum PerfPhase { /** * The "default" phase which tracks time not spent in any other phase. */ Unaccounted, /** * Time spent setting up the compiler, before a TypeScript program is created. * * This includes operations like configuring the `ts.CompilerHost` and any wrappers. */ Setup, /** * Time spent in `ts.createProgram`, including reading and parsing `ts.SourceFile`s in the * `ts.CompilerHost`. * * This might be an incremental program creation operation. */ TypeScriptProgramCreate, /** * Time spent reconciling the contents of an old `ts.Program` with the new incremental one. * * Only present in incremental compilations. */ Reconciliation, /** * Time spent updating an `NgCompiler` instance with a resource-only change. * * Only present in incremental compilations where the change was resource-only. */ ResourceUpdate, /** * Time spent calculating the plain TypeScript diagnostics (structural and semantic). */ TypeScriptDiagnostics, /** * Time spent in Angular analysis of individual classes in the program. */ Analysis, /** * Time spent in Angular global analysis (synthesis of analysis information into a complete * understanding of the program). */ Resolve, /** * Time spent building the import graph of the program in order to perform cycle detection. */ CycleDetection, /** * Time spent generating the text of Type Check Blocks in order to perform template type checking. */ TcbGeneration, /** * Time spent updating the `ts.Program` with new Type Check Block code. */ TcbUpdateProgram, /** * Time spent by TypeScript performing its emit operations, including downleveling and writing * output files. */ TypeScriptEmit, /** * Time spent by Angular performing code transformations of ASTs as they're about to be emitted. * * This includes the actual code generation step for templates, and occurs during the emit phase * (but is tracked separately from `TypeScriptEmit` time). */ Compile, /** * Time spent performing a `TemplateTypeChecker` autocompletion operation. */ TtcAutocompletion, /** * Time spent computing template type-checking diagnostics. */ TtcDiagnostics, /** * Time spent getting a `Symbol` from the `TemplateTypeChecker`. */ TtcSymbol, /** * Time spent by the Angular Language Service calculating a "get references" or a renaming * operation. */ LsReferencesAndRenames, /** * Time spent by the Angular Language Service calculating a "quick info" operation. */ LsQuickInfo, /** * Time spent by the Angular Language Service calculating a "get type definition" or "get * definition" operation. */ LsDefinition, /** * Time spent by the Angular Language Service calculating a "get completions" (AKA autocomplete) * operation. */ LsCompletions, /** * Time spent by the Angular Language Service calculating a "view template typecheck block" * operation. */ LsTcb, /** * Time spent by the Angular Language Service calculating diagnostics. */ LsDiagnostics, /** * Time spent by the Angular Language Service calculating a "get component locations for template" * operation. */ LsComponentLocations, /** * Time spent by the Angular Language Service calculating signature help. */ LsSignatureHelp, /** * Time spent by the Angular Language Service calculating outlining spans. */ OutliningSpans, /** * Tracks the number of `PerfPhase`s, and must appear at the end of the list. */ LAST, /** * Time spent by the Angular Language Service calculating code fixes. */ LsCodeFixes, /** * Time spent by the Angular Language Service to fix all detected same type errors. */ LsCodeFixesAll, /** * Time spent computing possible Angular refactorings. */ LSComputeApplicableRefactorings, /** * Time spent computing changes for applying a given refactoring. */ LSApplyRefactoring, } /** * Represents some occurrence during compilation, and is tracked with a counter. */ export enum PerfEvent { /** * Counts the number of `.d.ts` files in the program. */ InputDtsFile, /** * Counts the number of non-`.d.ts` files in the program. */ InputTsFile, /** * An `@Component` class was analyzed. */ AnalyzeComponent, /** * An `@Directive` class was analyzed. */ AnalyzeDirective, /** * An `@Injectable` class was analyzed. */ AnalyzeInjectable, /** * An `@NgModule` class was analyzed. */ AnalyzeNgModule, /** * An `@Pipe` class was analyzed. */ AnalyzePipe, /** * A trait was analyzed. * * In theory, this should be the sum of the `Analyze` counters for each decorator type. */ TraitAnalyze, /** * A trait had a prior analysis available from an incremental program, and did not need to be * re-analyzed. */ TraitReuseAnalysis, /** * A `ts.SourceFile` directly changed between the prior program and a new incremental compilation. */ SourceFilePhysicalChange, /** * A `ts.SourceFile` did not physically changed, but according to the file dependency graph, has * logically changed between the prior program and a new incremental compilation. */ SourceFileLogicalChange, /** * A `ts.SourceFile` has not logically changed and all of its analysis results were thus available * for reuse. */ SourceFileReuseAnalysis, /** * A Type Check Block (TCB) was generated. */ GenerateTcb, /** * A Type Check Block (TCB) could not be generated because inlining was disabled, and the block * would've required inlining. */ SkipGenerateTcbNoInline, /** * A `.ngtypecheck.ts` file could be reused from the previous program and did not need to be * regenerated. */ ReuseTypeCheckFile, /** * The template type-checking program required changes and had to be updated in an incremental * step. */ UpdateTypeCheckProgram, /** * The compiler was able to prove that a `ts.SourceFile` did not need to be re-emitted. */ EmitSkipSourceFile, /** * A `ts.SourceFile` was emitted. */ EmitSourceFile, /** * Tracks the number of `PrefEvent`s, and must appear at the end of the list. */ LAST, } /** * Represents a checkpoint during compilation at which the memory usage of the compiler should be * recorded. */ export enum PerfCheckpoint { /** * The point at which the `PerfRecorder` was created, and ideally tracks memory used before any * compilation structures are created. */ Initial, /** * The point just after the `ts.Program` has been created. */ TypeScriptProgramCreate, /** * The point just before Angular analysis starts. * * In the main usage pattern for the compiler, TypeScript diagnostics have been calculated at this * point, so the `ts.TypeChecker` has fully ingested the current program, all `ts.Type` structures * and `ts.Symbol`s have been created. */ PreAnalysis, /** * The point just after Angular analysis completes. */ Analysis, /** * The point just after Angular resolution is complete. */ Resolve, /** * The point just after Type Check Blocks (TCBs) have been generated. */ TtcGeneration, /** * The point just after the template type-checking program has been updated with any new TCBs. */ TtcUpdateProgram, /** * The point just before emit begins. * * In the main usage pattern for the compiler, all template type-checking diagnostics have been * requested at this point. */ PreEmit, /** * The point just after the program has been fully emitted. */ Emit, /** * Tracks the number of `PerfCheckpoint`s, and must appear at the end of the list. */ LAST, } /** * Records timing, memory, or counts at specific points in the compiler's operation. */
{ "end_byte": 8282, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/src/api.ts" }
angular/packages/compiler-cli/src/ngtsc/perf/src/api.ts_8283_9682
export interface PerfRecorder { /** * Set the current phase of compilation. * * Time spent in the previous phase will be accounted to that phase. The caller is responsible for * exiting the phase when work that should be tracked within it is completed, and either returning * to the previous phase or transitioning to the next one directly. * * In general, prefer using `inPhase()` to instrument a section of code, as it automatically * handles entering and exiting the phase. `phase()` should only be used when the former API * cannot be cleanly applied to a particular operation. * * @returns the previous phase */ phase(phase: PerfPhase): PerfPhase; /** * Run `fn` in the given `PerfPhase` and return the result. * * Enters `phase` before executing the given `fn`, then exits the phase and returns the result. * Prefer this API to `phase()` where possible. */ inPhase<T>(phase: PerfPhase, fn: () => T): T; /** * Record the memory usage of the compiler at the given checkpoint. */ memory(after: PerfCheckpoint): void; /** * Record that a specific event has occurred, possibly more than once. */ eventCount(event: PerfEvent, incrementBy?: number): void; /** * Return the `PerfRecorder` to an empty state (clear all tracked statistics) and reset the zero * point to the current time. */ reset(): void; }
{ "end_byte": 9682, "start_byte": 8283, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/src/api.ts" }
angular/packages/compiler-cli/src/ngtsc/perf/src/recorder.ts_0_4415
/** * @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.dev/license */ /// <reference types="node" /> import {PerfCheckpoint, PerfEvent, PerfPhase, PerfRecorder} from './api'; import {HrTime, mark, timeSinceInMicros} from './clock'; /** * Serializable performance data for the compilation, using string names. */ export interface PerfResults { events: Record<string, number>; phases: Record<string, number>; memory: Record<string, number>; } /** * A `PerfRecorder` that actively tracks performance statistics. */ export class ActivePerfRecorder implements PerfRecorder { private counters: number[]; private phaseTime: number[]; private bytes: number[]; private currentPhase = PerfPhase.Unaccounted; private currentPhaseEntered: HrTime; /** * Creates an `ActivePerfRecorder` with its zero point set to the current time. */ static zeroedToNow(): ActivePerfRecorder { return new ActivePerfRecorder(mark()); } private constructor(private zeroTime: HrTime) { this.currentPhaseEntered = this.zeroTime; this.counters = Array(PerfEvent.LAST).fill(0); this.phaseTime = Array(PerfPhase.LAST).fill(0); this.bytes = Array(PerfCheckpoint.LAST).fill(0); // Take an initial memory snapshot before any other compilation work begins. this.memory(PerfCheckpoint.Initial); } reset(): void { this.counters = Array(PerfEvent.LAST).fill(0); this.phaseTime = Array(PerfPhase.LAST).fill(0); this.bytes = Array(PerfCheckpoint.LAST).fill(0); this.zeroTime = mark(); this.currentPhase = PerfPhase.Unaccounted; this.currentPhaseEntered = this.zeroTime; } memory(after: PerfCheckpoint): void { this.bytes[after] = process.memoryUsage().heapUsed; } phase(phase: PerfPhase): PerfPhase { const previous = this.currentPhase; this.phaseTime[this.currentPhase] += timeSinceInMicros(this.currentPhaseEntered); this.currentPhase = phase; this.currentPhaseEntered = mark(); return previous; } inPhase<T>(phase: PerfPhase, fn: () => T): T { const previousPhase = this.phase(phase); try { return fn(); } finally { this.phase(previousPhase); } } eventCount(counter: PerfEvent, incrementBy: number = 1): void { this.counters[counter] += incrementBy; } /** * Return the current performance metrics as a serializable object. */ finalize(): PerfResults { // Track the last segment of time spent in `this.currentPhase` in the time array. this.phase(PerfPhase.Unaccounted); const results: PerfResults = { events: {}, phases: {}, memory: {}, }; for (let i = 0; i < this.phaseTime.length; i++) { if (this.phaseTime[i] > 0) { results.phases[PerfPhase[i]] = this.phaseTime[i]; } } for (let i = 0; i < this.phaseTime.length; i++) { if (this.counters[i] > 0) { results.events[PerfEvent[i]] = this.counters[i]; } } for (let i = 0; i < this.bytes.length; i++) { if (this.bytes[i] > 0) { results.memory[PerfCheckpoint[i]] = this.bytes[i]; } } return results; } } /** * A `PerfRecorder` that delegates to a target `PerfRecorder` which can be updated later. * * `DelegatingPerfRecorder` is useful when a compiler class that needs a `PerfRecorder` can outlive * the current compilation. This is true for most compiler classes as resource-only changes reuse * the same `NgCompiler` for a new compilation. */ export class DelegatingPerfRecorder implements PerfRecorder { constructor(public target: PerfRecorder) {} eventCount(counter: PerfEvent, incrementBy?: number): void { this.target.eventCount(counter, incrementBy); } phase(phase: PerfPhase): PerfPhase { return this.target.phase(phase); } inPhase<T>(phase: PerfPhase, fn: () => T): T { // Note: this doesn't delegate to `this.target.inPhase` but instead is implemented manually here // to avoid adding an additional frame of noise to the stack when debugging. const previousPhase = this.target.phase(phase); try { return fn(); } finally { this.target.phase(previousPhase); } } memory(after: PerfCheckpoint): void { this.target.memory(after); } reset(): void { this.target.reset(); } }
{ "end_byte": 4415, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/src/recorder.ts" }
angular/packages/compiler-cli/src/ngtsc/perf/src/clock.ts_0_524
/** * @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.dev/license */ // This file uses 'process' /// <reference types="node" /> export type HrTime = [number, number]; export function mark(): HrTime { return process.hrtime(); } export function timeSinceInMicros(mark: HrTime): number { const delta = process.hrtime(mark); return delta[0] * 1000000 + Math.floor(delta[1] / 1000); }
{ "end_byte": 524, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/perf/src/clock.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/BUILD.bazel_0_1149
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "transform", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/incremental/semantic_graph", "//packages/compiler-cli/src/ngtsc/indexer", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "//packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api", "//packages/compiler-cli/src/ngtsc/util", "//packages/compiler-cli/src/ngtsc/xi18n", "@npm//typescript", ], )
{ "end_byte": 1149, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/transform/index.ts_0_639
/** * @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.dev/license */ export * from './src/api'; export {aliasTransformFactory} from './src/alias'; export {ClassRecord, TraitCompiler} from './src/compilation'; export { declarationTransformFactory, DtsTransformRegistry, IvyDeclarationDtsTransform, } from './src/declaration'; export { AnalyzedTrait, PendingTrait, ResolvedTrait, SkippedTrait, Trait, TraitState, } from './src/trait'; export {ivyTransformFactory} from './src/transform';
{ "end_byte": 639, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/index.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/test/BUILD.bazel_0_926
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 926, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts_0_1020
/** * @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.dev/license */ import {ConstantPool} from '@angular/compiler'; import * as o from '@angular/compiler/src/output/output_ast'; import {absoluteFrom} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {NOOP_INCREMENTAL_BUILD} from '../../incremental'; import {NOOP_PERF_RECORDER} from '../../perf'; import { ClassDeclaration, Decorator, isNamedClassDeclaration, TypeScriptReflectionHost, } from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {CompilationMode, DetectResult, DtsTransformRegistry, TraitCompiler} from '../../transform'; import { AnalysisOutput, CompileResult, DecoratorHandler, HandlerPrecedence, ResolveResult, } from '../src/api'; const fakeSfTypeIdentifier = { isShim: () => false, isResource: () => false, };
{ "end_byte": 1020, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts_1022_10439
runInEachFileSystem(() => { describe('TraitCompiler', () => { let _: typeof absoluteFrom; beforeEach(() => (_ = absoluteFrom)); function setup( programContents: string, handlers: DecoratorHandler<{} | null, unknown, null, unknown>[], compilationMode: CompilationMode, makeDtsSourceFile = false, ) { const filename = makeDtsSourceFile ? 'test.d.ts' : 'test.ts'; const {program} = makeProgram([ { name: _('/' + filename), contents: programContents, }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const compiler = new TraitCompiler( handlers, reflectionHost, NOOP_PERF_RECORDER, NOOP_INCREMENTAL_BUILD, true, compilationMode, new DtsTransformRegistry(), null, fakeSfTypeIdentifier, ); const sourceFile = program.getSourceFile(filename)!; return {compiler, sourceFile, program, filename: _('/' + filename)}; } it('should not run decoration handlers against declaration files', () => { class FakeDecoratorHandler implements DecoratorHandler<{} | null, unknown, null, unknown> { name = 'FakeDecoratorHandler'; precedence = HandlerPrecedence.PRIMARY; detect(): undefined { throw new Error('detect should not have been called'); } analyze(): AnalysisOutput<unknown> { throw new Error('analyze should not have been called'); } symbol(): null { throw new Error('symbol should not have been called'); } compileFull(): CompileResult { throw new Error('compileFull should not have been called'); } compileLocal(): CompileResult { throw new Error('compileLocal should not have been called'); } } const contents = `export declare class SomeDirective {}`; const {compiler, sourceFile} = setup( contents, [new FakeDecoratorHandler()], CompilationMode.FULL, true, ); const analysis = compiler.analyzeSync(sourceFile); expect(sourceFile.isDeclarationFile).toBe(true); expect(analysis).toBeFalsy(); }); describe('compilation mode', () => { class LocalDecoratorHandler implements DecoratorHandler<{}, {}, null, unknown> { name = 'LocalDecoratorHandler'; precedence = HandlerPrecedence.PRIMARY; detect( node: ClassDeclaration, decorators: Decorator[] | null, ): DetectResult<{}> | undefined { if (node.name.text !== 'Local') { return undefined; } return {trigger: node, decorator: null, metadata: {}}; } analyze(): AnalysisOutput<unknown> { return {analysis: {}}; } symbol(): null { return null; } compileFull(): CompileResult { return { name: 'compileFull', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } compileLocal(): CompileResult { return { name: 'compileLocal', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } } class PartialDecoratorHandler implements DecoratorHandler<{}, {}, null, unknown> { name = 'PartialDecoratorHandler'; precedence = HandlerPrecedence.PRIMARY; detect( node: ClassDeclaration, decorators: Decorator[] | null, ): DetectResult<{}> | undefined { if (node.name.text !== 'Partial') { return undefined; } return {trigger: node, decorator: null, metadata: {}}; } analyze(): AnalysisOutput<unknown> { return {analysis: {}}; } symbol(): null { return null; } compileFull(): CompileResult { return { name: 'compileFull', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } compilePartial(): CompileResult { return { name: 'compilePartial', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } compileLocal(): CompileResult { return { name: 'compileLocal', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } } class FullDecoratorHandler implements DecoratorHandler<{}, {}, null, unknown> { name = 'FullDecoratorHandler'; precedence = HandlerPrecedence.PRIMARY; detect( node: ClassDeclaration, decorators: Decorator[] | null, ): DetectResult<{}> | undefined { if (node.name.text !== 'Full') { return undefined; } return {trigger: node, decorator: null, metadata: {}}; } analyze(): AnalysisOutput<unknown> { return {analysis: {}}; } symbol(): null { return null; } compileFull(): CompileResult { return { name: 'compileFull', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } compileLocal(): CompileResult { return { name: 'compileLocal', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } } it('should run partial compilation when implemented if compilation mode is partial', () => { const contents = ` export class Full {} export class Partial {} `; const {compiler, sourceFile, program, filename} = setup( contents, [new PartialDecoratorHandler(), new FullDecoratorHandler()], CompilationMode.PARTIAL, ); compiler.analyzeSync(sourceFile); compiler.resolve(); const partialDecl = getDeclaration(program, filename, 'Partial', isNamedClassDeclaration); const partialResult = compiler.compile(partialDecl, new ConstantPool())!; expect(partialResult.length).toBe(1); expect(partialResult[0].name).toBe('compilePartial'); const fullDecl = getDeclaration(program, filename, 'Full', isNamedClassDeclaration); const fullResult = compiler.compile(fullDecl, new ConstantPool())!; expect(fullResult.length).toBe(1); expect(fullResult[0].name).toBe('compileFull'); }); it('should run local compilation when compilation mode is local', () => { const contents = ` export class Full {} export class Local {} `; const {compiler, sourceFile, program, filename} = setup( contents, [new LocalDecoratorHandler(), new FullDecoratorHandler()], CompilationMode.LOCAL, ); compiler.analyzeSync(sourceFile); compiler.resolve(); const localDecl = getDeclaration(program, filename, 'Local', isNamedClassDeclaration); const localResult = compiler.compile(localDecl, new ConstantPool())!; expect(localResult.length).toBe(1); expect(localResult[0].name).toBe('compileLocal'); const fullDecl = getDeclaration(program, filename, 'Full', isNamedClassDeclaration); const fullResult = compiler.compile(fullDecl, new ConstantPool())!; expect(fullResult.length).toBe(1); expect(fullResult[0].name).toBe('compileLocal'); }); it('should run full compilation if compilation mode is full', () => { const contents = ` export class Full {} export class Partial {} export class Local {} `; const {compiler, sourceFile, program, filename} = setup( contents, [new LocalDecoratorHandler(), new PartialDecoratorHandler(), new FullDecoratorHandler()], CompilationMode.FULL, ); compiler.analyzeSync(sourceFile); compiler.resolve(); const localDecl = getDeclaration(program, filename, 'Local', isNamedClassDeclaration); const localResult = compiler.compile(localDecl, new ConstantPool())!; expect(localResult.length).toBe(1); expect(localResult[0].name).toBe('compileFull'); const partialDecl = getDeclaration(program, filename, 'Partial', isNamedClassDeclaration); const partialResult = compiler.compile(partialDecl, new ConstantPool())!; expect(partialResult.length).toBe(1); expect(partialResult[0].name).toBe('compileFull'); const fullDecl = getDeclaration(program, filename, 'Full', isNamedClassDeclaration); const fullResult = compiler.compile(fullDecl, new ConstantPool())!; expect(fullResult.length).toBe(1); expect(fullResult[0].name).toBe('compileFull'); }); });
{ "end_byte": 10439, "start_byte": 1022, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts_10445_13292
describe('local compilation', () => { class TestDecoratorHandler implements DecoratorHandler<{}, {}, null, unknown> { name = 'TestDecoratorHandler'; precedence = HandlerPrecedence.PRIMARY; detect( node: ClassDeclaration, decorators: Decorator[] | null, ): DetectResult<{}> | undefined { if (node.name.text !== 'Test') { return undefined; } return {trigger: node, decorator: null, metadata: {}}; } analyze(): AnalysisOutput<unknown> { return {analysis: {}}; } resolve(): ResolveResult<unknown> { return {}; } register(): void {} updateResources() {} symbol(): null { return null; } compileFull(): CompileResult { return { name: 'compileFull', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } compileLocal(): CompileResult { return { name: 'compileLocal', initializer: o.literal(true), statements: [], type: o.BOOL_TYPE, deferrableImports: null, }; } } it('should invoke `resolve` phase', () => { const contents = ` export class Test {} `; const handler = new TestDecoratorHandler(); spyOn(handler, 'resolve').and.callThrough(); const {compiler, sourceFile} = setup(contents, [handler], CompilationMode.LOCAL); compiler.analyzeSync(sourceFile); compiler.resolve(); expect(handler.resolve).toHaveBeenCalled(); }); it('should invoke `register` phase', () => { const contents = ` export class Test {} `; const handler = new TestDecoratorHandler(); spyOn(handler, 'register'); const {compiler, sourceFile} = setup(contents, [handler], CompilationMode.LOCAL); compiler.analyzeSync(sourceFile); compiler.resolve(); expect(handler.register).toHaveBeenCalled(); }); it('should not call updateResources', () => { const contents = ` export class Test {} `; const handler = new TestDecoratorHandler(); spyOn(handler, 'updateResources'); const {compiler, sourceFile, program, filename} = setup( contents, [handler], CompilationMode.LOCAL, ); const decl = getDeclaration(program, filename, 'Test', isNamedClassDeclaration); compiler.analyzeSync(sourceFile); compiler.resolve(); compiler.updateResources(decl); expect(handler.updateResources).not.toHaveBeenCalled(); }); }); }); });
{ "end_byte": 13292, "start_byte": 10445, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/test/compilation_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/BUILD.bazel_0_580
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "jit", srcs = glob(["**/*.ts"]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/annotations", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/translator", "@npm//typescript", ], )
{ "end_byte": 580, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/index.ts_0_337
/** * @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.dev/license */ export { angularJitApplicationTransform, getDownlevelDecoratorsTransform, getInitializerApiJitTransform, } from './src/index';
{ "end_byte": 337, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/index.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts_0_8686
/** * @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.dev/license */ import ts from 'typescript'; import {TypeScriptReflectionHost} from '../../../reflection'; import {getDownlevelDecoratorsTransform} from '../index'; import {MockAotContext, MockCompilerHost} from '../../../../../test/mocks'; const TEST_FILE_INPUT = '/test.ts'; const TEST_FILE_OUTPUT = `/test.js`; const TEST_FILE_DTS_OUTPUT = `/test.d.ts`; describe('downlevel decorator transform', () => { let host: MockCompilerHost; let context: MockAotContext; let diagnostics: ts.Diagnostic[]; let isClosureEnabled: boolean; beforeEach(() => { diagnostics = []; context = new MockAotContext('/', { 'dom_globals.d.ts': ` declare class HTMLElement {}; declare class Document {}; `, }); host = new MockCompilerHost(context); isClosureEnabled = false; }); function transform( contents: string, compilerOptions: ts.CompilerOptions = {}, preTransformers: ts.TransformerFactory<ts.SourceFile>[] = [], ) { context.writeFile(TEST_FILE_INPUT, contents); const program = ts.createProgram( [TEST_FILE_INPUT, '/dom_globals.d.ts'], { module: ts.ModuleKind.CommonJS, importHelpers: true, lib: ['dom', 'es2015'], target: ts.ScriptTarget.ES2017, declaration: true, experimentalDecorators: true, emitDecoratorMetadata: false, ...compilerOptions, }, host, ); const testFile = program.getSourceFile(TEST_FILE_INPUT); const typeChecker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(typeChecker); const transformers: ts.CustomTransformers = { before: [ ...preTransformers, getDownlevelDecoratorsTransform( program.getTypeChecker(), reflectionHost, diagnostics, /* isCore */ false, isClosureEnabled, ), ], }; let output: string | null = null; let dtsOutput: string | null = null; const emitResult = program.emit( testFile, (fileName, outputText) => { if (fileName === TEST_FILE_OUTPUT) { output = outputText; } else if (fileName === TEST_FILE_DTS_OUTPUT) { dtsOutput = outputText; } }, undefined, undefined, transformers, ); diagnostics.push(...emitResult.diagnostics); expect(output).not.toBeNull(); return { output: omitLeadingWhitespace(output!), dtsOutput: dtsOutput ? omitLeadingWhitespace(dtsOutput) : null, }; } it('should downlevel decorators for @Injectable decorated class', () => { const {output} = transform(` import {Injectable} from '@angular/core'; export class ClassInject {}; @Injectable() export class MyService { constructor(v: ClassInject) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyService.ctorParameters = () => [ { type: ClassInject } ]; exports.MyService = MyService = tslib_1.__decorate([ (0, core_1.Injectable)() ], MyService); `); }); it('should downlevel decorators for @Directive decorated class', () => { const {output} = transform(` import {Directive} from '@angular/core'; export class ClassInject {}; @Directive() export class MyDir { constructor(v: ClassInject) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: ClassInject } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should downlevel decorators for @Component decorated class', () => { const {output} = transform(` import {Component} from '@angular/core'; export class ClassInject {}; @Component({template: 'hello'}) export class MyComp { constructor(v: ClassInject) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyComp.ctorParameters = () => [ { type: ClassInject } ]; exports.MyComp = MyComp = tslib_1.__decorate([ (0, core_1.Component)({ template: 'hello' }) ], MyComp);`); }); it('should downlevel decorators for @Pipe decorated class', () => { const {output} = transform(` import {Pipe} from '@angular/core'; export class ClassInject {}; @Pipe({selector: 'hello'}) export class MyPipe { constructor(v: ClassInject) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyPipe.ctorParameters = () => [ { type: ClassInject } ]; exports.MyPipe = MyPipe = tslib_1.__decorate([ (0, core_1.Pipe)({ selector: 'hello' }) ], MyPipe); `); }); it('should not downlevel non-Angular class decorators', () => { const {output} = transform(` @SomeUnknownDecorator() export class MyClass {} `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` exports.MyClass = MyClass = tslib_1.__decorate([ SomeUnknownDecorator() ], MyClass); `); expect(output).not.toContain('MyClass.decorators'); }); it('should not downlevel non-Angular class decorators generated by a builder', () => { const {output} = transform(` @DecoratorBuilder().customClassDecorator export class MyClass {} `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` exports.MyClass = MyClass = tslib_1.__decorate([ DecoratorBuilder().customClassDecorator ], MyClass); `); expect(output).not.toContain('MyClass.decorators'); }); it('should downlevel Angular-decorated class member', () => { const {output} = transform(` import {Input} from '@angular/core'; export class MyDir { @Input() disabled: boolean = false; } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyDir.propDecorators = { disabled: [{ type: core_1.Input }] }; `); expect(output).not.toContain('tslib'); }); it('should not downlevel class member with unknown decorator', () => { const {output} = transform(` export class MyDir { @SomeDecorator() disabled: boolean = false; } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` tslib_1.__decorate([ SomeDecorator() ], MyDir.prototype, "disabled", void 0); `); expect(output).not.toContain('MyClass.propDecorators'); }); // Regression test for a scenario where previously the class within a constructor body // would be processed twice, where the downleveled class is revisited accidentally and // caused invalid generation of the `ctorParameters` static class member. it('should not duplicate constructor parameters for classes part of constructor body', () => { // Note: the bug with duplicated/invalid generation only surfaces when the actual class // decorators are preserved and emitted by TypeScript itself. This setting is also // disabled within the CLI. const {output} = transform(` import {Injectable} from '@angular/core'; export class ZoneToken {} @Injectable() export class Wrapper { constructor(y: ZoneToken) { @Injectable() class ShouldBeProcessed { constructor(x: ZoneToken) {} } } } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` let Wrapper = class Wrapper { constructor(y) { let ShouldBeProcessed = class ShouldBeProcessed { constructor(x) { } }; ShouldBeProcessed.ctorParameters = () => [ { type: ZoneToken } ]; ShouldBeProcessed = tslib_1.__decorate([ (0, core_1.Injectable)() ], ShouldBeProcessed); } }; exports.Wrapper = Wrapper; `); }); // Angular is not concerned with type information for decorated class members. Instead, // the type is omitted. This also helps with server side rendering as DOM globals which // are used as types, do not load at runtime. https://github.com/angular/angular/issues/30586.
{ "end_byte": 8686, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts_8689_16510
it('should downlevel Angular-decorated class member but not preserve type', () => { context.writeFile('/other-file.ts', `export class MyOtherClass {}`); const {output} = transform(` import {Input} from '@angular/core'; import {MyOtherClass} from './other-file'; export class MyDir { @Input() trigger: HTMLElement; @Input() fromOtherFile: MyOtherClass; } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyDir.propDecorators = { trigger: [{ type: core_1.Input }], fromOtherFile: [{ type: core_1.Input }] }; `); expect(output).not.toContain('HTMLElement'); expect(output).not.toContain('MyOtherClass'); }); it('should capture constructor type metadata with `emitDecoratorMetadata` enabled', () => { context.writeFile('/other-file.ts', `export class MyOtherClass {}`); const {output} = transform( ` import {Directive} from '@angular/core'; import {MyOtherClass} from './other-file'; @Directive() export class MyDir { constructor(other: MyOtherClass) {} } `, {emitDecoratorMetadata: true}, ); expect(diagnostics.length).toBe(0); expect(output).toContain('const other_file_1 = require("./other-file");'); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: other_file_1.MyOtherClass } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)(), tslib_1.__metadata("design:paramtypes", [other_file_1.MyOtherClass]) ], MyDir); `); }); it('should capture constructor type metadata with `emitDecoratorMetadata` disabled', () => { context.writeFile('/other-file.ts', `export class MyOtherClass {}`); const {output, dtsOutput} = transform( ` import {Directive} from '@angular/core'; import {MyOtherClass} from './other-file'; @Directive() export class MyDir { constructor(other: MyOtherClass) {} } `, {emitDecoratorMetadata: false}, ); expect(diagnostics.length).toBe(0); expect(output).toContain('const other_file_1 = require("./other-file");'); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: other_file_1.MyOtherClass } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); expect(dtsOutput).toContain('import'); }); it('should properly serialize constructor parameter with external qualified name type', () => { context.writeFile('/other-file.ts', `export class MyOtherClass {}`); const {output} = transform(` import {Directive} from '@angular/core'; import * as externalFile from './other-file'; @Directive() export class MyDir { constructor(other: externalFile.MyOtherClass) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain('const externalFile = require("./other-file");'); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: externalFile.MyOtherClass } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should properly serialize constructor parameter with local qualified name type', () => { const {output} = transform(` import {Directive} from '@angular/core'; namespace other { export class OtherClass {} }; @Directive() export class MyDir { constructor(other: other.OtherClass) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain('var other;'); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: other.OtherClass } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should properly downlevel constructor parameter decorators', () => { const {output} = transform(` import {Inject, Directive, DOCUMENT} from '@angular/core'; @Directive() export class MyDir { constructor(@Inject(DOCUMENT) document: Document) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: Document, decorators: [{ type: core_1.Inject, args: [core_1.DOCUMENT,] }] } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should properly downlevel constructor parameters with union type', () => { const {output} = transform(` import {Optional, Directive, NgZone} from '@angular/core'; @Directive() export class MyDir { constructor(@Optional() ngZone: NgZone|null) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: core_1.NgZone, decorators: [{ type: core_1.Optional }] } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should add @nocollapse if closure compiler is enabled', () => { isClosureEnabled = true; const {output} = transform(` import {Directive} from '@angular/core'; export class ClassInject {}; @Directive() export class MyDir { constructor(v: ClassInject) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); expect(output).toContain(dedent` /** * @type {function(): !Array<(null|{ * type: ?, * decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>), * })>} * @nocollapse */ MyDir.ctorParameters = () => [ { type: ClassInject } ]; `); }); it( 'should not retain unused type imports due to decorator downleveling with ' + '`emitDecoratorMetadata` enabled.', () => { context.writeFile( '/external.ts', ` export class ErrorHandler {} export class ClassInject {} `, ); const {output} = transform( ` import {Directive, Inject} from '@angular/core'; import {ErrorHandler, ClassInject} from './external'; export class MyDir { private _errorHandler: ErrorHandler; constructor(@Inject(ClassInject) i: ClassInject) {} } `, {module: ts.ModuleKind.ES2015, emitDecoratorMetadata: true}, ); expect(diagnostics.length).toBe(0); expect(output).not.toContain('Directive'); expect(output).not.toContain('ErrorHandler'); }, ); it( 'should not retain unused type imports due to decorator downleveling with ' + '`emitDecoratorMetadata` disabled', () => { context.writeFile( '/external.ts', ` export class ErrorHandler {} export class ClassInject {} `, ); const {output} = transform( ` import {Directive, Inject} from '@angular/core'; import {ErrorHandler, ClassInject} from './external'; export class MyDir { private _errorHandler: ErrorHandler; constructor(@Inject(ClassInject) i: ClassInject) {} } `, {module: ts.ModuleKind.ES2015, emitDecoratorMetadata: false}, ); expect(diagnostics.length).toBe(0); expect(output).not.toContain('Directive'); expect(output).not.toContain('ErrorHandler'); }, );
{ "end_byte": 16510, "start_byte": 8689, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts_16514_23004
it('should not generate invalid reference due to conflicting parameter name', () => { context.writeFile( '/external.ts', ` export class Dep { greet() {} } `, ); const {output} = transform( ` import {Directive} from '@angular/core'; import {Dep} from './external'; @Directive() export class MyDir { constructor(Dep: Dep) { Dep.greet(); } } `, {emitDecoratorMetadata: false}, ); expect(diagnostics.length).toBe(0); expect(output).toContain(`external_1 = require("./external");`); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: external_1.Dep } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should be able to serialize circular constructor parameter type', () => { const {output} = transform(` import {Directive, Optional, Inject, SkipSelf} from '@angular/core'; @Directive() export class MyDir { constructor(@Optional() @SkipSelf() @Inject(MyDir) parentDir: MyDir|null) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` let MyDir = class MyDir { constructor(parentDir) { } }; exports.MyDir = MyDir; MyDir.ctorParameters = () => [ { type: MyDir, decorators: [{ type: core_1.Optional }, { type: core_1.SkipSelf }, { type: core_1.Inject, args: [MyDir,] }] } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should create diagnostic if property name is non-serializable', () => { transform(` import {Directive, ViewChild, TemplateRef} from '@angular/core'; @Directive() export class MyDir { @ViewChild(TemplateRef) ['some' + 'name']: TemplateRef<any>|undefined; } `); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText as string).toBe( `Cannot process decorators for class element with non-analyzable name.`, ); }); it('should not capture constructor parameter types when not resolving to a value', () => { context.writeFile( '/external.ts', ` export interface IState {} export type IOverlay = {hello: true}&IState; export default interface { hello: false; } export const enum KeyCodes {A, B} `, ); const {output} = transform(` import {Directive, Inject} from '@angular/core'; import * as angular from './external'; import {IOverlay, KeyCodes} from './external'; import TypeFromDefaultImport from './external'; @Directive() export class MyDir { constructor(@Inject('$state') param: angular.IState, @Inject('$overlay') other: IOverlay, @Inject('$default') fromDefaultImport: TypeFromDefaultImport, @Inject('$keyCodes') keyCodes: KeyCodes) {} } `); expect(diagnostics.length).toBe(0); expect(output).not.toContain('external'); expect(output).toContain(dedent` MyDir.ctorParameters = () => [ { type: undefined, decorators: [{ type: core_1.Inject, args: ['$state',] }] }, { type: undefined, decorators: [{ type: core_1.Inject, args: ['$overlay',] }] }, { type: undefined, decorators: [{ type: core_1.Inject, args: ['$default',] }] }, { type: undefined, decorators: [{ type: core_1.Inject, args: ['$keyCodes',] }] } ]; exports.MyDir = MyDir = tslib_1.__decorate([ (0, core_1.Directive)() ], MyDir); `); }); it('should allow preceding custom transformers to strip decorators', () => { const stripAllDecoratorsTransform: ts.TransformerFactory<ts.SourceFile> = (context) => { return (sourceFile: ts.SourceFile) => { const visitNode = (node: ts.Node): ts.Node => { if (ts.isClassDeclaration(node)) { return ts.factory.createClassDeclaration( ts.getModifiers(node), node.name, node.typeParameters, node.heritageClauses, node.members, ); } return ts.visitEachChild(node, visitNode, context); }; return visitNode(sourceFile) as ts.SourceFile; }; }; const {output} = transform( ` import {Directive} from '@angular/core'; export class MyInjectedClass {} @Directive() export class MyDir { constructor(someToken: MyInjectedClass) {} } `, {}, [stripAllDecoratorsTransform], ); expect(diagnostics.length).toBe(0); expect(output).not.toContain('MyDir.decorators'); expect(output).not.toContain('MyDir.ctorParameters'); expect(output).not.toContain('tslib'); }); it('should capture a non-const enum used as a constructor type', () => { const {output} = transform(` import {Component} from '@angular/core'; export enum Values {A, B}; @Component({template: 'hello'}) export class MyComp { constructor(v: Values) {} } `); expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` MyComp.ctorParameters = () => [ { type: Values } ]; exports.MyComp = MyComp = tslib_1.__decorate([ (0, core_1.Component)({ template: 'hello' }) ], MyComp); `); }); it('should allow for type-only references to be removed with `emitDecoratorMetadata` from custom decorators', () => { context.writeFile( '/external-interface.ts', ` export interface ExternalInterface { id?: string; } `, ); const {output} = transform( ` import { ExternalInterface } from './external-interface'; export function CustomDecorator() { return <T>(target, propertyKey, descriptor: TypedPropertyDescriptor<T>) => {} } export class Foo { @CustomDecorator() static test(): ExternalInterface { return {}; } } `, {emitDecoratorMetadata: true}, ); expect(diagnostics.length).toBe(0); expect(output).not.toContain('ExternalInterface'); expect(output).toContain('metadata("design:returntype", Object)'); });
{ "end_byte": 23004, "start_byte": 16514, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts_23008_27724
describe('transforming multiple files', () => { it('should work correctly for multiple files that import distinct declarations', () => { context.writeFile( 'foo_service.d.ts', ` export declare class Foo {}; `, ); context.writeFile( 'foo.ts', ` import {Injectable} from '@angular/core'; import {Foo} from './foo_service'; @Injectable() export class MyService { constructor(foo: Foo) {} } `, ); context.writeFile( 'bar_service.d.ts', ` export declare class Bar {}; `, ); context.writeFile( 'bar.ts', ` import {Injectable} from '@angular/core'; import {Bar} from './bar_service'; @Injectable() export class MyService { constructor(bar: Bar) {} } `, ); const {program, transformers} = createProgramWithTransform(['/foo.ts', '/bar.ts']); program.emit(undefined, undefined, undefined, undefined, transformers); expect(context.readFile('/foo.js')).toContain(`import { Foo } from './foo_service';`); expect(context.readFile('/bar.js')).toContain(`import { Bar } from './bar_service';`); }); it('should not result in a stack overflow for a large number of files', () => { // The decorators transform used to patch `ts.EmitResolver.isReferencedAliasDeclaration` // repeatedly for each source file in the program, causing a stack overflow once a large // number of source files was reached. This test verifies that emit succeeds even when there's // lots of source files. See https://github.com/angular/angular/issues/40276. context.writeFile( 'foo.d.ts', ` export declare class Foo {}; `, ); // A somewhat minimal number of source files that used to trigger a stack overflow. const numberOfTestFiles = 6500; const files: string[] = []; for (let i = 0; i < numberOfTestFiles; i++) { const file = `/${i}.ts`; files.push(file); context.writeFile( file, ` import {Injectable} from '@angular/core'; import {Foo} from './foo'; @Injectable() export class MyService { constructor(foo: Foo) {} } `, ); } const {program, transformers} = createProgramWithTransform(files); let written = 0; program.emit( undefined, (fileName, outputText) => { written++; // The below assertion throws an explicit error instead of using a Jasmine expectation, // as we want to abort on the first failure, if any. This avoids as many as `numberOfFiles` // expectation failures, which would bloat the test output. if (!outputText.includes(`import { Foo } from './foo';`)) { throw new Error( `Transform failed to preserve the import in ${fileName}:\n${outputText}`, ); } }, undefined, undefined, transformers, ); expect(written).toBe(numberOfTestFiles); }); function createProgramWithTransform(files: string[]) { const program = ts.createProgram( files, { moduleResolution: ts.ModuleResolutionKind.Node10, importHelpers: true, lib: [], module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest, declaration: false, experimentalDecorators: true, emitDecoratorMetadata: false, }, host, ); const typeChecker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(typeChecker); const transformers: ts.CustomTransformers = { before: [ getDownlevelDecoratorsTransform( program.getTypeChecker(), reflectionHost, diagnostics, /* isCore */ false, isClosureEnabled, ), ], }; return {program, transformers}; } }); }); /** Template string function that can be used to dedent a given string literal. */ export function dedent(strings: TemplateStringsArray, ...values: any[]) { let joinedString = ''; for (let i = 0; i < values.length; i++) { joinedString += `${strings[i]}${values[i]}`; } joinedString += strings[strings.length - 1]; return omitLeadingWhitespace(joinedString); } /** Omits the leading whitespace for each line of the given text. */ function omitLeadingWhitespace(text: string): string { return text.replace(/^\s+/gm, ''); }
{ "end_byte": 27724, "start_byte": 23008, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/downlevel_decorators_transform_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/signal_queries_metadata_transform_spec.ts_0_8024
/** * @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.dev/license */ import ts from 'typescript'; import {ImportedSymbolsTracker} from '../../../imports'; import {TypeScriptReflectionHost} from '../../../reflection'; import {getDownlevelDecoratorsTransform, getInitializerApiJitTransform} from '../index'; import {MockAotContext, MockCompilerHost} from '../../../../../test/mocks'; const TEST_FILE_INPUT = '/test.ts'; const TEST_FILE_OUTPUT = `/test.js`; describe('signal queries metadata transform', () => { let host: MockCompilerHost; let context: MockAotContext; beforeEach(() => { context = new MockAotContext('/', { 'core.d.ts': ` export declare const Component: any; export declare const ViewChild: any; export declare const ViewChildren: any; export declare const ContentChild: any; export declare const ContentChildren: any; export declare const viewChild: any; export declare const viewChildren: any; export declare const contentChild: any; export declare const contentChildren: any; `, }); host = new MockCompilerHost(context); }); function transform(contents: string, postDownlevelDecoratorsTransform = false) { context.writeFile(TEST_FILE_INPUT, contents); const program = ts.createProgram( [TEST_FILE_INPUT], { module: ts.ModuleKind.ESNext, lib: ['dom', 'es2022'], target: ts.ScriptTarget.ES2022, traceResolution: true, experimentalDecorators: true, paths: { '@angular/core': ['./core.d.ts'], }, }, host, ); const testFile = program.getSourceFile(TEST_FILE_INPUT); const typeChecker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(typeChecker); const importTracker = new ImportedSymbolsTracker(); const transformers: ts.CustomTransformers = { before: [getInitializerApiJitTransform(reflectionHost, importTracker, /* isCore */ false)], }; if (postDownlevelDecoratorsTransform) { transformers.before!.push( getDownlevelDecoratorsTransform( typeChecker, reflectionHost, [], /* isCore */ false, /* isClosureCompilerEnabled */ false, ), ); } let output: string | null = null; const emitResult = program.emit( testFile, (fileName, outputText) => { if (fileName === TEST_FILE_OUTPUT) { output = outputText; } }, undefined, undefined, transformers, ); expect(emitResult.diagnostics.length).toBe(0); expect(output).not.toBeNull(); return omitLeadingWhitespace(output!); } it('should add `@ViewChild` decorator for a signal `viewChild`', () => { const result = transform(` import {viewChild, Component} from '@angular/core'; @Component({}) class MyDir { el = viewChild('el'); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.ViewChild('el', { isSignal: true }) ], MyDir.prototype, "el", void 0); `), ); }); it('should add `@ViewChild` decorator for a required `viewChild`', () => { const result = transform(` import {viewChild, Component} from '@angular/core'; @Component({}) class MyDir { el = viewChild.required('el'); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.ViewChild('el', { isSignal: true }) ], MyDir.prototype, "el", void 0); `), ); }); it('should add `@ViewChild` decorator for `viewChild` with read option', () => { const result = transform(` import {viewChild, Component} from '@angular/core'; import * as bla from '@angular/core'; const SomeToken = null!; @Component({}) class MyDir { el = viewChild('el', {read: SomeToken}); el2 = viewChild('el', {read: bla.Component}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ bla.ViewChild('el', { ...{ read: SomeToken }, isSignal: true }) ], MyDir.prototype, "el", void 0); `), ); expect(result).toContain( omitLeadingWhitespace(` __decorate([ bla.ViewChild('el', { ...{ read: bla.Component }, isSignal: true }) ], MyDir.prototype, "el2", void 0); `), ); }); it('should add `@ContentChild` decorator for signal queries with `descendants` option', () => { const result = transform(` import {contentChild, Directive} from '@angular/core'; class X {} @Directive({}) class MyDir { el = contentChild(X, {descendants: true}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.ContentChild(X, { ...{ descendants: true }, isSignal: true }) ], MyDir.prototype, "el", void 0); `), ); }); it('should not transform decorators for non-signal queries', () => { const result = transform(` import {ViewChildren, viewChild, Component} from '@angular/core'; @Component({}) class MyDir { el = viewChild('el'); @ViewChild('el', {someOptionIndicatingThatNothingChanged: true}) nonSignalQuery: any = null; } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.ViewChild('el', { isSignal: true }) ], MyDir.prototype, "el", void 0); __decorate([ ViewChild('el', { someOptionIndicatingThatNothingChanged: true }) ], MyDir.prototype, "nonSignalQuery", void 0); `), ); }); it('should not transform signal queries with an existing decorator', () => { // This is expected to not happen because technically the TS code for signal inputs // should never discover both decorators and a signal query declaration. We handle this // gracefully though in case someone compiles without the Angular compiler (which would report a // diagnostic). const result = transform(` import {contentChildren, ContentChildren, Directive} from '@angular/core'; @Directive({}) class MyDir { @ContentChildren('els', {isSignal: true}) els = contentChildren('els'); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ ContentChildren('els', { isSignal: true }) ], MyDir.prototype, "els", void 0); `), ); }); it('should preserve existing decorators applied on signal inputs fields', () => { const result = transform(` import {contentChild, Directive} from '@angular/core'; declare const MyCustomDecorator: any; @Directive({}) class MyDir { @MyCustomDecorator() bla = contentChild('el', {descendants: false}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.ContentChild('el', { ...{ descendants: false }, isSignal: true }), MyCustomDecorator() ], MyDir.prototype, "bla", void 0); `), ); }); it('should work with decorator downleveling post-transform', () => { const result = transform( ` import {viewChild, Component} from '@angular/core'; class X {} @Component({}) class MyDir { el = viewChild('el', {read: X}); } `, /* postDownlevelDecoratorsTransform */ true, ); expect(result).toContain( omitLeadingWhitespace(` static propDecorators = { el: [{ type: i0.ViewChild, args: ['el', { ...{ read: X }, isSignal: true },] }] }; `), ); }); }); /** Omits the leading whitespace for each line of the given text. */ function omitLeadingWhitespace(text: string): string { return text.replace(/^\s+/gm, ''); }
{ "end_byte": 8024, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/signal_queries_metadata_transform_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/initializer_api_transforms_spec.ts_0_2760
/** * @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.dev/license */ import ts from 'typescript'; import {ImportedSymbolsTracker} from '../../../imports'; import {TypeScriptReflectionHost} from '../../../reflection'; import {getDownlevelDecoratorsTransform, getInitializerApiJitTransform} from '../index'; import {MockAotContext, MockCompilerHost} from '../../../../../test/mocks'; const TEST_FILE_INPUT = '/test.ts'; const TEST_FILE_OUTPUT = `/test.js`; describe('initializer API metadata transform', () => { let host: MockCompilerHost; let context: MockAotContext; beforeEach(() => { context = new MockAotContext('/', { 'core.d.ts': ` export declare const Directive: any; export declare const Input: any; export declare const input: any; export declare const model: any; `, }); host = new MockCompilerHost(context); }); function transform( contents: string, postDownlevelDecoratorsTransform = false, customPreTransform?: ts.TransformerFactory<ts.SourceFile>, ) { context.writeFile(TEST_FILE_INPUT, contents); const program = ts.createProgram( [TEST_FILE_INPUT], { module: ts.ModuleKind.ESNext, lib: ['dom', 'es2022'], target: ts.ScriptTarget.ES2022, traceResolution: true, experimentalDecorators: true, paths: { '@angular/core': ['./core.d.ts'], }, }, host, ); const testFile = program.getSourceFile(TEST_FILE_INPUT); const typeChecker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(typeChecker); const importTracker = new ImportedSymbolsTracker(); const transformers: ts.CustomTransformers = { before: [ ...(customPreTransform ? [customPreTransform] : []), getInitializerApiJitTransform(reflectionHost, importTracker, /* isCore */ false), ], }; if (postDownlevelDecoratorsTransform) { transformers.before!.push( getDownlevelDecoratorsTransform( typeChecker, reflectionHost, [], /* isCore */ false, /* isClosureCompilerEnabled */ false, ), ); } let output: string | null = null; const emitResult = program.emit( testFile, (fileName, outputText) => { if (fileName === TEST_FILE_OUTPUT) { output = outputText; } }, undefined, undefined, transformers, ); expect(emitResult.diagnostics.length).toBe(0); expect(output).not.toBeNull(); return omitLeadingWhitespace(output!); }
{ "end_byte": 2760, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/initializer_api_transforms_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/initializer_api_transforms_spec.ts_2764_11264
describe('input()', () => { it('should add `@Input` decorator for a signal input', () => { const result = transform(` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input(0); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: false, transform: undefined }) ], MyDir.prototype, "someInput", void 0); `), ); }); it('should add `@Input` decorator for a required signal input', () => { const result = transform(` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input.required<string>(); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: true, transform: undefined }) ], MyDir.prototype, "someInput", void 0); `), ); }); it('should add `@Input` decorator for signal inputs with alias options', () => { const result = transform(` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input(null, {alias: "public1"}); someInput2 = input.required<string>({alias: "public2"}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "public1", required: false, transform: undefined }) ], MyDir.prototype, "someInput", void 0); __decorate([ i0.Input({ isSignal: true, alias: "public2", required: true, transform: undefined }) ], MyDir.prototype, "someInput2", void 0); `), ); }); it('should add `@Input` decorator for signal inputs with transforms', () => { const result = transform(` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input(0, {transform: v => v + 1}); someInput2 = input.required<number>({transform: v => v + 1}); } `); // Transform functions are never captured because the input signal already captures // them and will run these independently of whether a `transform` is specified here. expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: false, transform: undefined }) ], MyDir.prototype, "someInput", void 0); __decorate([ i0.Input({ isSignal: true, alias: "someInput2", required: true, transform: undefined }) ], MyDir.prototype, "someInput2", void 0); `), ); }); it('should not transform `@Input` decorator for non-signal inputs', () => { const result = transform(` import {Input, input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input.required<string>({}); @Input({someOptionIndicatingThatNothingChanged: true}) nonSignalInput: number = 0; } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: true, transform: undefined }) ], MyDir.prototype, "someInput", void 0); __decorate([ Input({ someOptionIndicatingThatNothingChanged: true }) ], MyDir.prototype, "nonSignalInput", void 0); `), ); }); it('should not transform signal inputs with an existing `@Input` decorator', () => { // This is expected to not happen because technically the TS code for signal inputs // should never discover both `@Input` and signal inputs. We handle this gracefully // though in case someone compiles without the Angular compiler (which would report a // diagnostic). const result = transform(` import {Input, input, Directive} from '@angular/core'; @Directive({}) class MyDir { @Input() someInput = input.required<string>({}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ Input() ], MyDir.prototype, "someInput", void 0); `), ); }); it('should preserve existing decorators applied on signal inputs fields', () => { const result = transform(` import {Input, input, Directive} from '@angular/core'; declare const MyCustomDecorator: any; @Directive({}) class MyDir { @MyCustomDecorator() someInput = input.required<string>({}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: true, transform: undefined }), MyCustomDecorator() ], MyDir.prototype, "someInput", void 0); `), ); }); it('should work with decorator downleveling post-transform', () => { const result = transform( ` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input(0); } `, /* postDownlevelDecoratorsTransform */ true, ); expect(result).toContain( omitLeadingWhitespace(` static propDecorators = { someInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "someInput", required: false, transform: undefined },] }] }; `), ); }); it('should migrate if the class decorator is downleveled in advance', () => { const fakeDownlevelPreTransform = (ctx: ts.TransformationContext) => { return (sf: ts.SourceFile) => { const visitor = (node: ts.Node) => { if (ts.isClassDeclaration(node)) { return ctx.factory.updateClassDeclaration( node, [], node.name, node.typeParameters, node.heritageClauses, node.members, ); } return node; }; return ts.visitEachChild(sf, visitor, ctx); }; }; const result = transform( ` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input(0); } `, false, fakeDownlevelPreTransform, ); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: false, transform: undefined }) ], MyDir.prototype, "someInput", void 0); `), ); }); // Tsickle may transform the class via the downlevel decorator transform in advance in G3. // In addition, the property declaration may be transformed too, to add `@type` JSDocs in G3. it('should migrate if the class member and class is transformed in advance', () => { const fakeDownlevelPreTransform = (ctx: ts.TransformationContext) => { return (sf: ts.SourceFile) => { const visitor = (node: ts.Node) => { // Updating the `{transform: () => {}} arrow function triggers both transforms. if (ts.isArrowFunction(node)) { return ctx.factory.updateArrowFunction( node, node.modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, ctx.factory.createBlock([]), ); } return ts.visitEachChild(node, visitor, ctx); }; return ts.visitEachChild(sf, visitor, ctx); }; }; const result = transform( ` import {input, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = input({transform: () => {}}); } `, false, fakeDownlevelPreTransform, ); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "someInput", required: false, transform: undefined }) ], MyDir.prototype, "someInput", void 0); `), ); }); });
{ "end_byte": 11264, "start_byte": 2764, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/initializer_api_transforms_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/initializer_api_transforms_spec.ts_11268_17075
describe('model()', () => { it('should add `@Input` and `@Output` decorators for a model input', () => { const result = transform(` import {model, Directive} from '@angular/core'; @Directive({}) class MyDir { value = model(0); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "value", required: false }), i0.Output("valueChange") ], MyDir.prototype, "value", void 0); `), ); }); it('should add `@Input` and `@Output` decorators for a required model input', () => { const result = transform(` import {model, Directive} from '@angular/core'; @Directive({}) class MyDir { value = model.required<string>(); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "value", required: true }), i0.Output("valueChange") ], MyDir.prototype, "value", void 0); `), ); }); it('should add `@Input` and `@Output` decorators for an aliased model input', () => { const result = transform(` import {model, Directive} from '@angular/core'; @Directive({}) class MyDir { value = model(null, {alias: "alias"}); value2 = model.required<string>({alias: "alias2"}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "alias", required: false }), i0.Output("aliasChange") ], MyDir.prototype, "value", void 0); __decorate([ i0.Input({ isSignal: true, alias: "alias2", required: true }), i0.Output("alias2Change") ], MyDir.prototype, "value2", void 0); `), ); }); it('should not transform model inputs with an existing `@Input` decorator', () => { const result = transform(` import {Input, model, Directive} from '@angular/core'; @Directive({}) class MyDir { @Input() value = model.required<string>(); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ Input() ], MyDir.prototype, "value", void 0); `), ); }); it('should not transform model inputs with an existing `@Output` decorator', () => { const result = transform(` import {Output, model, Directive} from '@angular/core'; @Directive({}) class MyDir { @Output() value = model<string>(); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ Output() ], MyDir.prototype, "value", void 0); `), ); }); it('should preserve existing decorators applied on model input fields', () => { const result = transform(` import {model, Directive} from '@angular/core'; declare const MyCustomDecorator: any; @Directive({}) class MyDir { @MyCustomDecorator() value = model.required<string>({}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Input({ isSignal: true, alias: "value", required: true }), i0.Output("valueChange"), MyCustomDecorator() ], MyDir.prototype, "value", void 0); `), ); }); it('should work with decorator downleveling post-transform', () => { const result = transform( ` import {model, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = model(0); } `, /* postDownlevelDecoratorsTransform */ true, ); expect(result).toContain( omitLeadingWhitespace(` static propDecorators = { someInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "someInput", required: false },] }, { type: i0.Output, args: ["someInputChange",] }] }; `), ); }); }); describe('output()', () => { it('should insert an `@Output` decorator', () => { const result = transform(` import {output, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = output(); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Output("someInput") ], MyDir.prototype, "someInput", void 0); `), ); }); it('should insert an `@Output` decorator with aliases', () => { const result = transform(` import {output, Directive} from '@angular/core'; @Directive({}) class MyDir { someInput = output({alias: 'someAlias'}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ i0.Output("someAlias") ], MyDir.prototype, "someInput", void 0); `), ); }); it('should not change an existing `@Output` decorator', () => { const result = transform(` import {output, Output, Directive} from '@angular/core'; const bla = 'some string'; @Directive({}) class MyDir { @Output(bla) someInput = output({}); } `); expect(result).toContain( omitLeadingWhitespace(` __decorate([ Output(bla) ], MyDir.prototype, "someInput", void 0); `), ); }); }); }); /** Omits the leading whitespace for each line of the given text. */ function omitLeadingWhitespace(text: string): string { return text.replace(/^\s+/gm, ''); }
{ "end_byte": 17075, "start_byte": 11268, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/initializer_api_transforms_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/test/BUILD.bazel_0_746
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = [ "downlevel_decorators_transform_spec.ts", "initializer_api_transforms_spec.ts", "signal_queries_metadata_transform_spec.ts", ], deps = [ "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/transform/jit", "//packages/compiler-cli/test:test_utils", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], )
{ "end_byte": 746, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts_0_8927
/** * @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.dev/license */ import ts from 'typescript'; import {isAliasImportDeclaration, loadIsReferencedAliasDeclarationPatch} from '../../../imports'; import {Decorator, ReflectionHost} from '../../../reflection'; /** * Whether a given decorator should be treated as an Angular decorator. * Either it's used in @angular/core, or it's imported from there. */ function isAngularDecorator(decorator: Decorator, isCore: boolean): boolean { return isCore || (decorator.import !== null && decorator.import.from === '@angular/core'); } /* ##################################################################### Code below has been extracted from the tsickle decorator downlevel transformer and a few local modifications have been applied: 1. Tsickle by default processed all decorators that had the `@Annotation` JSDoc. We modified the transform to only be concerned with known Angular decorators. 2. Tsickle by default added `@nocollapse` to all generated `ctorParameters` properties. We only do this when `annotateForClosureCompiler` is enabled. 3. Tsickle does not handle union types for dependency injection. i.e. if a injected type is denoted with `@Optional`, the actual type could be set to `T | null`. See: https://github.com/angular/angular-cli/commit/826803d0736b807867caff9f8903e508970ad5e4. 4. Tsickle relied on `emitDecoratorMetadata` to be set to `true`. This is due to a limitation in TypeScript transformers that never has been fixed. We were able to work around this limitation so that `emitDecoratorMetadata` doesn't need to be specified. See: `patchAliasReferenceResolution` for more details. Here is a link to the tsickle revision on which this transformer is based: https://github.com/angular/tsickle/blob/fae06becb1570f491806060d83f29f2d50c43cdd/src/decorator_downlevel_transformer.ts ##################################################################### */ const DECORATOR_INVOCATION_JSDOC_TYPE = '!Array<{type: !Function, args: (undefined|!Array<?>)}>'; /** * Extracts the type of the decorator (the function or expression invoked), as well as all the * arguments passed to the decorator. Returns an AST with the form: * * // For @decorator(arg1, arg2) * { type: decorator, args: [arg1, arg2] } */ function extractMetadataFromSingleDecorator( decorator: ts.Decorator, diagnostics: ts.Diagnostic[], ): ts.ObjectLiteralExpression { const metadataProperties: ts.ObjectLiteralElementLike[] = []; const expr = decorator.expression; switch (expr.kind) { case ts.SyntaxKind.Identifier: // The decorator was a plain @Foo. metadataProperties.push(ts.factory.createPropertyAssignment('type', expr)); break; case ts.SyntaxKind.CallExpression: // The decorator was a call, like @Foo(bar). const call = expr as ts.CallExpression; metadataProperties.push(ts.factory.createPropertyAssignment('type', call.expression)); if (call.arguments.length) { const args: ts.Expression[] = []; for (const arg of call.arguments) { args.push(arg); } const argsArrayLiteral = ts.factory.createArrayLiteralExpression( ts.factory.createNodeArray(args, true), ); metadataProperties.push(ts.factory.createPropertyAssignment('args', argsArrayLiteral)); } break; default: diagnostics.push({ file: decorator.getSourceFile(), start: decorator.getStart(), length: decorator.getEnd() - decorator.getStart(), messageText: `${ ts.SyntaxKind[decorator.kind] } not implemented in gathering decorator metadata.`, category: ts.DiagnosticCategory.Error, code: 0, }); break; } return ts.factory.createObjectLiteralExpression(metadataProperties); } /** * createCtorParametersClassProperty creates a static 'ctorParameters' property containing * downleveled decorator information. * * The property contains an arrow function that returns an array of object literals of the shape: * static ctorParameters = () => [{ * type: SomeClass|undefined, // the type of the param that's decorated, if it's a value. * decorators: [{ * type: DecoratorFn, // the type of the decorator that's invoked. * args: [ARGS], // the arguments passed to the decorator. * }] * }]; */ function createCtorParametersClassProperty( diagnostics: ts.Diagnostic[], entityNameToExpression: (n: ts.EntityName) => ts.Expression | undefined, ctorParameters: ParameterDecorationInfo[], isClosureCompilerEnabled: boolean, ): ts.PropertyDeclaration { const params: ts.Expression[] = []; for (const ctorParam of ctorParameters) { if (!ctorParam.type && ctorParam.decorators.length === 0) { params.push(ts.factory.createNull()); continue; } const paramType = ctorParam.type ? typeReferenceToExpression(entityNameToExpression, ctorParam.type) : undefined; const members = [ ts.factory.createPropertyAssignment( 'type', paramType || ts.factory.createIdentifier('undefined'), ), ]; const decorators: ts.ObjectLiteralExpression[] = []; for (const deco of ctorParam.decorators) { decorators.push(extractMetadataFromSingleDecorator(deco, diagnostics)); } if (decorators.length) { members.push( ts.factory.createPropertyAssignment( 'decorators', ts.factory.createArrayLiteralExpression(decorators), ), ); } params.push(ts.factory.createObjectLiteralExpression(members)); } const initializer = ts.factory.createArrowFunction( undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createArrayLiteralExpression(params, true), ); const ctorProp = ts.factory.createPropertyDeclaration( [ts.factory.createToken(ts.SyntaxKind.StaticKeyword)], 'ctorParameters', undefined, undefined, initializer, ); if (isClosureCompilerEnabled) { ts.setSyntheticLeadingComments(ctorProp, [ { kind: ts.SyntaxKind.MultiLineCommentTrivia, text: [ `*`, ` * @type {function(): !Array<(null|{`, ` * type: ?,`, ` * decorators: (undefined|${DECORATOR_INVOCATION_JSDOC_TYPE}),`, ` * })>}`, ` * @nocollapse`, ` `, ].join('\n'), pos: -1, end: -1, hasTrailingNewLine: true, }, ]); } return ctorProp; } /** * Returns an expression representing the (potentially) value part for the given node. * * This is a partial re-implementation of TypeScript's serializeTypeReferenceNode. This is a * workaround for https://github.com/Microsoft/TypeScript/issues/17516 (serializeTypeReferenceNode * not being exposed). In practice this implementation is sufficient for Angular's use of type * metadata. */ function typeReferenceToExpression( entityNameToExpression: (n: ts.EntityName) => ts.Expression | undefined, node: ts.TypeNode, ): ts.Expression | undefined { let kind = node.kind; if (ts.isLiteralTypeNode(node)) { // Treat literal types like their base type (boolean, string, number). kind = node.literal.kind; } switch (kind) { case ts.SyntaxKind.FunctionType: case ts.SyntaxKind.ConstructorType: return ts.factory.createIdentifier('Function'); case ts.SyntaxKind.ArrayType: case ts.SyntaxKind.TupleType: return ts.factory.createIdentifier('Array'); case ts.SyntaxKind.TypePredicate: case ts.SyntaxKind.TrueKeyword: case ts.SyntaxKind.FalseKeyword: case ts.SyntaxKind.BooleanKeyword: return ts.factory.createIdentifier('Boolean'); case ts.SyntaxKind.StringLiteral: case ts.SyntaxKind.StringKeyword: return ts.factory.createIdentifier('String'); case ts.SyntaxKind.ObjectKeyword: return ts.factory.createIdentifier('Object'); case ts.SyntaxKind.NumberKeyword: case ts.SyntaxKind.NumericLiteral: return ts.factory.createIdentifier('Number'); case ts.SyntaxKind.TypeReference: const typeRef = node as ts.TypeReferenceNode; // Ignore any generic types, just return the base type. return entityNameToExpression(typeRef.typeName); case ts.SyntaxKind.UnionType: const childTypeNodes = (node as ts.UnionTypeNode).types.filter( (t) => !(ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword), ); return childTypeNodes.length === 1 ? typeReferenceToExpression(entityNameToExpression, childTypeNodes[0]) : undefined; default: return undefined; } }
{ "end_byte": 8927, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts_8929_12802
/** * Checks whether a given symbol refers to a value that exists at runtime (as distinct from a type). * * Expands aliases, which is important for the case where * import * as x from 'some-module'; * and x is now a value (the module object). */ function symbolIsRuntimeValue(typeChecker: ts.TypeChecker, symbol: ts.Symbol): boolean { if (symbol.flags & ts.SymbolFlags.Alias) { symbol = typeChecker.getAliasedSymbol(symbol); } // Note that const enums are a special case, because // while they have a value, they don't exist at runtime. return (symbol.flags & ts.SymbolFlags.Value & ts.SymbolFlags.ConstEnumExcludes) !== 0; } /** ParameterDecorationInfo describes the information for a single constructor parameter. */ interface ParameterDecorationInfo { /** * The type declaration for the parameter. Only set if the type is a value (e.g. a class, not an * interface). */ type: ts.TypeNode | null; /** The list of decorators found on the parameter, null if none. */ decorators: ts.Decorator[]; } /** * Gets a transformer for downleveling Angular constructor parameter and property decorators. * * Note that Angular class decorators are never processed as those rely on side effects that * would otherwise no longer be executed. i.e. the creation of a component definition. * * @param typeChecker Reference to the program's type checker. * @param host Reflection host that is used for determining decorators. * @param diagnostics List which will be populated with diagnostics if any. * @param isCore Whether the current TypeScript program is for the `@angular/core` package. * @param isClosureCompilerEnabled Whether closure annotations need to be added where needed. * @param shouldTransformClass Optional function to check if a given class should be transformed. */ export function getDownlevelDecoratorsTransform( typeChecker: ts.TypeChecker, host: ReflectionHost, diagnostics: ts.Diagnostic[], isCore: boolean, isClosureCompilerEnabled: boolean, shouldTransformClass?: (node: ts.ClassDeclaration) => boolean, ): ts.TransformerFactory<ts.SourceFile> { function addJSDocTypeAnnotation(node: ts.Node, jsdocType: string): void { if (!isClosureCompilerEnabled) { return; } ts.setSyntheticLeadingComments(node, [ { kind: ts.SyntaxKind.MultiLineCommentTrivia, text: `* @type {${jsdocType}} `, pos: -1, end: -1, hasTrailingNewLine: true, }, ]); } /** * createPropDecoratorsClassProperty creates a static 'propDecorators' * property containing type information for every property that has a * decorator applied. * * static propDecorators: {[key: string]: {type: Function, args?: * any[]}[]} = { propA: [{type: MyDecorator, args: [1, 2]}, ...], * ... * }; */ function createPropDecoratorsClassProperty( diagnostics: ts.Diagnostic[], properties: Map<string, ts.Decorator[]>, ): ts.PropertyDeclaration { // `static propDecorators: {[key: string]: ` + {type: Function, args?: // any[]}[] + `} = {\n`); const entries: ts.ObjectLiteralElementLike[] = []; for (const [name, decorators] of properties.entries()) { entries.push( ts.factory.createPropertyAssignment( name, ts.factory.createArrayLiteralExpression( decorators.map((deco) => extractMetadataFromSingleDecorator(deco, diagnostics)), ), ), ); } const initializer = ts.factory.createObjectLiteralExpression(entries, true); const prop = ts.factory.createPropertyDeclaration( [ts.factory.createToken(ts.SyntaxKind.StaticKeyword)], 'propDecorators', undefined, undefined, initializer, ); addJSDocTypeAnnotation(prop, `!Object<string, ${DECORATOR_INVOCATION_JSDOC_TYPE}>`); return prop; }
{ "end_byte": 12802, "start_byte": 8929, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts_12806_21242
return (context: ts.TransformationContext) => { // Ensure that referenced type symbols are not elided by TypeScript. Imports for // such parameter type symbols previously could be type-only, but now might be also // used in the `ctorParameters` static property as a value. We want to make sure // that TypeScript does not elide imports for such type references. Read more // about this in the description for `loadIsReferencedAliasDeclarationPatch`. const referencedParameterTypes = loadIsReferencedAliasDeclarationPatch(context); /** * Converts an EntityName (from a type annotation) to an expression (accessing a value). * * For a given qualified name, this walks depth first to find the leftmost identifier, * and then converts the path into a property access that can be used as expression. */ function entityNameToExpression(name: ts.EntityName): ts.Expression | undefined { const symbol = typeChecker.getSymbolAtLocation(name); // Check if the entity name references a symbol that is an actual value. If it is not, it // cannot be referenced by an expression, so return undefined. if ( !symbol || !symbolIsRuntimeValue(typeChecker, symbol) || !symbol.declarations || symbol.declarations.length === 0 ) { return undefined; } // If we deal with a qualified name, build up a property access expression // that could be used in the JavaScript output. if (ts.isQualifiedName(name)) { const containerExpr = entityNameToExpression(name.left); if (containerExpr === undefined) { return undefined; } return ts.factory.createPropertyAccessExpression(containerExpr, name.right); } const decl = symbol.declarations[0]; // If the given entity name has been resolved to an alias import declaration, // ensure that the alias declaration is not elided by TypeScript, and use its // name identifier to reference it at runtime. if (isAliasImportDeclaration(decl)) { referencedParameterTypes.add(decl); // If the entity name resolves to an alias import declaration, we reference the // entity based on the alias import name. This ensures that TypeScript properly // resolves the link to the import. Cloning the original entity name identifier // could lead to an incorrect resolution at local scope. e.g. Consider the following // snippet: `constructor(Dep: Dep) {}`. In such a case, the local `Dep` identifier // would resolve to the actual parameter name, and not to the desired import. // This happens because the entity name identifier symbol is internally considered // as type-only and therefore TypeScript tries to resolve it as value manually. // We can help TypeScript and avoid this non-reliable resolution by using an identifier // that is not type-only and is directly linked to the import alias declaration. if (decl.name !== undefined) { return ts.setOriginalNode(ts.factory.createIdentifier(decl.name.text), decl.name); } } // Clone the original entity name identifier so that it can be used to reference // its value at runtime. This is used when the identifier is resolving to a file // local declaration (otherwise it would resolve to an alias import declaration). return ts.setOriginalNode(ts.factory.createIdentifier(name.text), name); } /** * Transforms a class element. Returns a three tuple of name, transformed element, and * decorators found. Returns an undefined name if there are no decorators to lower on the * element, or the element has an exotic name. */ function transformClassElement( element: ts.ClassElement, ): [string | undefined, ts.ClassElement, ts.Decorator[]] { element = ts.visitEachChild(element, decoratorDownlevelVisitor, context); const decoratorsToKeep: ts.Decorator[] = []; const toLower: ts.Decorator[] = []; const decorators = host.getDecoratorsOfDeclaration(element) || []; for (const decorator of decorators) { // We only deal with concrete nodes in TypeScript sources, so we don't // need to handle synthetically created decorators. const decoratorNode = decorator.node! as ts.Decorator; if (!isAngularDecorator(decorator, isCore)) { decoratorsToKeep.push(decoratorNode); continue; } toLower.push(decoratorNode); } if (!toLower.length) return [undefined, element, []]; if (!element.name || !ts.isIdentifier(element.name)) { // Method has a weird name, e.g. // [Symbol.foo]() {...} diagnostics.push({ file: element.getSourceFile(), start: element.getStart(), length: element.getEnd() - element.getStart(), messageText: `Cannot process decorators for class element with non-analyzable name.`, category: ts.DiagnosticCategory.Error, code: 0, }); return [undefined, element, []]; } const elementModifiers = ts.canHaveModifiers(element) ? ts.getModifiers(element) : undefined; let modifiers: ts.NodeArray<ts.ModifierLike> | undefined; if (decoratorsToKeep.length || elementModifiers?.length) { modifiers = ts.setTextRange( ts.factory.createNodeArray([...decoratorsToKeep, ...(elementModifiers || [])]), (element as ts.HasModifiers).modifiers, ); } return [element.name.text, cloneClassElementWithModifiers(element, modifiers), toLower]; } /** * Transforms a constructor. Returns the transformed constructor and the list of parameter * information collected, consisting of decorators and optional type. */ function transformConstructor( ctor: ts.ConstructorDeclaration, ): [ts.ConstructorDeclaration, ParameterDecorationInfo[]] { ctor = ts.visitEachChild(ctor, decoratorDownlevelVisitor, context); const newParameters: ts.ParameterDeclaration[] = []; const oldParameters = ctor.parameters; const parametersInfo: ParameterDecorationInfo[] = []; for (const param of oldParameters) { const decoratorsToKeep: ts.Decorator[] = []; const paramInfo: ParameterDecorationInfo = {decorators: [], type: null}; const decorators = host.getDecoratorsOfDeclaration(param) || []; for (const decorator of decorators) { // We only deal with concrete nodes in TypeScript sources, so we don't // need to handle synthetically created decorators. const decoratorNode = decorator.node! as ts.Decorator; if (!isAngularDecorator(decorator, isCore)) { decoratorsToKeep.push(decoratorNode); continue; } paramInfo!.decorators.push(decoratorNode); } if (param.type) { // param has a type provided, e.g. "foo: Bar". // The type will be emitted as a value expression in entityNameToExpression, which takes // care not to emit anything for types that cannot be expressed as a value (e.g. // interfaces). paramInfo!.type = param.type; } parametersInfo.push(paramInfo); // Must pass 'undefined' to avoid emitting decorator metadata. let modifiers: ts.ModifierLike[] | undefined; const paramModifiers = ts.getModifiers(param); if (decoratorsToKeep.length || paramModifiers?.length) { modifiers = [...decoratorsToKeep, ...(paramModifiers || [])]; } const newParam = ts.factory.updateParameterDeclaration( param, modifiers, param.dotDotDotToken, param.name, param.questionToken, param.type, param.initializer, ); newParameters.push(newParam); } const updated = ts.factory.updateConstructorDeclaration( ctor, ts.getModifiers(ctor), newParameters, ctor.body, ); return [updated, parametersInfo]; } /** * Transforms a single class declaration: * - dispatches to strip decorators on members * - converts decorators on the class to annotations * - creates a ctorParameters property * - creates a propDecorators property */
{ "end_byte": 21242, "start_byte": 12806, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts_21247_26261
function transformClassDeclaration(classDecl: ts.ClassDeclaration): ts.ClassDeclaration { const newMembers: ts.ClassElement[] = []; const decoratedProperties = new Map<string, ts.Decorator[]>(); let classParameters: ParameterDecorationInfo[] | null = null; for (const member of classDecl.members) { switch (member.kind) { case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.SetAccessor: case ts.SyntaxKind.MethodDeclaration: { const [name, newMember, decorators] = transformClassElement(member); newMembers.push(newMember); if (name) decoratedProperties.set(name, decorators); continue; } case ts.SyntaxKind.Constructor: { const ctor = member as ts.ConstructorDeclaration; if (!ctor.body) break; const [newMember, parametersInfo] = transformConstructor( member as ts.ConstructorDeclaration, ); classParameters = parametersInfo; newMembers.push(newMember); continue; } default: break; } newMembers.push(ts.visitEachChild(member, decoratorDownlevelVisitor, context)); } // Note: The `ReflectionHost.getDecoratorsOfDeclaration()` method will not // return all decorators, but only ones that could be possible Angular decorators. const possibleAngularDecorators = host.getDecoratorsOfDeclaration(classDecl) || []; // Keep track if we come across an Angular class decorator. This is used // to determine whether constructor parameters should be captured or not. const hasAngularDecorator = possibleAngularDecorators.some((d) => isAngularDecorator(d, isCore), ); if (classParameters) { if (hasAngularDecorator || classParameters.some((p) => !!p.decorators.length)) { // Capture constructor parameters if the class has Angular decorator applied, // or if any of the parameters has decorators applied directly. newMembers.push( createCtorParametersClassProperty( diagnostics, entityNameToExpression, classParameters, isClosureCompilerEnabled, ), ); } } if (decoratedProperties.size) { newMembers.push(createPropDecoratorsClassProperty(diagnostics, decoratedProperties)); } const members = ts.setTextRange( ts.factory.createNodeArray(newMembers, classDecl.members.hasTrailingComma), classDecl.members, ); return ts.factory.updateClassDeclaration( classDecl, classDecl.modifiers, classDecl.name, classDecl.typeParameters, classDecl.heritageClauses, members, ); } /** * Transformer visitor that looks for Angular decorators and replaces them with * downleveled static properties. Also collects constructor type metadata for * class declaration that are decorated with an Angular decorator. */ function decoratorDownlevelVisitor(node: ts.Node): ts.Node { if ( ts.isClassDeclaration(node) && (shouldTransformClass === undefined || shouldTransformClass(node)) ) { return transformClassDeclaration(node); } return ts.visitEachChild(node, decoratorDownlevelVisitor, context); } return (sf: ts.SourceFile) => { // Downlevel decorators and constructor parameter types. We will keep track of all // referenced constructor parameter types so that we can instruct TypeScript to // not elide their imports if they previously were only type-only. return ts.visitEachChild(sf, decoratorDownlevelVisitor, context); }; }; } function cloneClassElementWithModifiers( node: ts.ClassElement, modifiers: readonly ts.ModifierLike[] | undefined, ): ts.ClassElement { let clone: ts.ClassElement; if (ts.isMethodDeclaration(node)) { clone = ts.factory.createMethodDeclaration( modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body, ); } else if (ts.isPropertyDeclaration(node)) { clone = ts.factory.createPropertyDeclaration( modifiers, node.name, node.questionToken, node.type, node.initializer, ); } else if (ts.isGetAccessor(node)) { clone = ts.factory.createGetAccessorDeclaration( modifiers, node.name, node.parameters, node.type, node.body, ); } else if (ts.isSetAccessor(node)) { clone = ts.factory.createSetAccessorDeclaration( modifiers, node.name, node.parameters, node.body, ); } else { throw new Error(`Unsupported decorated member with kind ${ts.SyntaxKind[node.kind]}`); } return ts.setOriginalNode(clone, node); }
{ "end_byte": 26261, "start_byte": 21247, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/index.ts_0_2636
/** * @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.dev/license */ import ts from 'typescript'; import {ImportedSymbolsTracker} from '../../../imports'; import {TypeScriptReflectionHost} from '../../../reflection'; import {getDownlevelDecoratorsTransform} from './downlevel_decorators_transform'; import {getInitializerApiJitTransform} from './initializer_api_transforms/transform'; export {getDownlevelDecoratorsTransform} from './downlevel_decorators_transform'; export {getInitializerApiJitTransform} from './initializer_api_transforms/transform'; /** * JIT transform for Angular applications. Used by the Angular CLI for unit tests and * explicit JIT applications. * * The transforms include: * * - A transform for downleveling Angular decorators and Angular-decorated class constructor * parameters for dependency injection. This transform can be used by the CLI for JIT-mode * compilation where constructor parameters and associated Angular decorators should be * downleveled so that apps are not exposed to the ES2015 temporal dead zone limitation * in TypeScript. See https://github.com/angular/angular-cli/pull/14473 for more details. * * - A transform for adding `@Input` to signal inputs. Signal inputs cannot be recognized * at runtime using reflection. That is because the class would need to be instantiated- * but is not possible before creation. To fix this for JIT, a decorator is automatically * added that will declare the input as a signal input while also capturing the necessary * metadata */ export function angularJitApplicationTransform( program: ts.Program, isCore = false, shouldTransformClass?: (node: ts.ClassDeclaration) => boolean, ): ts.TransformerFactory<ts.SourceFile> { const typeChecker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(typeChecker); const importTracker = new ImportedSymbolsTracker(); const downlevelDecoratorTransform = getDownlevelDecoratorsTransform( typeChecker, reflectionHost, [], isCore, /* enableClosureCompiler */ false, shouldTransformClass, ); const initializerApisJitTransform = getInitializerApiJitTransform( reflectionHost, importTracker, isCore, shouldTransformClass, ); return (ctx) => { return (sourceFile) => { sourceFile = initializerApisJitTransform(ctx)(sourceFile); sourceFile = downlevelDecoratorTransform(ctx)(sourceFile); return sourceFile; }; }; }
{ "end_byte": 2636, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/index.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/query_functions.ts_0_3297
/** * @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.dev/license */ import { getAngularDecorators, queryDecoratorNames, QueryFunctionName, tryParseSignalQueryFromInitializer, } from '../../../../annotations'; import { castAsAny, createSyntheticAngularCoreDecoratorAccess, PropertyTransform, } from './transform_api'; /** Maps a query function to its decorator. */ const queryFunctionToDecorator: Record<QueryFunctionName, string> = { viewChild: 'ViewChild', viewChildren: 'ViewChildren', contentChild: 'ContentChild', contentChildren: 'ContentChildren', }; /** * Transform that will automatically add query decorators for all signal-based * queries in Angular classes. The decorator will capture metadata of the signal * query, derived from the initializer-based API call. * * This transform is useful for JIT environments where signal queries would like to be * used. e.g. for Angular CLI unit testing. In such environments, signal queries are not * statically retrievable at runtime. JIT compilation needs to know about all possible queries * before instantiating directives to construct the definition. A decorator exposes this * information to the class without the class needing to be instantiated. */ export const queryFunctionsTransforms: PropertyTransform = ( member, sourceFile, host, factory, importTracker, importManager, classDecorator, isCore, ) => { const decorators = host.getDecoratorsOfDeclaration(member.node); // If the field already is decorated, we handle this gracefully and skip it. const queryDecorators = decorators && getAngularDecorators(decorators, queryDecoratorNames, isCore); if (queryDecorators !== null && queryDecorators.length > 0) { return member.node; } const queryDefinition = tryParseSignalQueryFromInitializer(member, host, importTracker); if (queryDefinition === null) { return member.node; } const callArgs = queryDefinition.call.arguments; const newDecorator = factory.createDecorator( factory.createCallExpression( createSyntheticAngularCoreDecoratorAccess( factory, importManager, classDecorator, sourceFile, queryFunctionToDecorator[queryDefinition.name], ), undefined, // All positional arguments of the query functions can be mostly re-used as is // for the decorator. i.e. predicate is always first argument. Options are second. [ queryDefinition.call.arguments[0], // Note: Casting as `any` because `isSignal` is not publicly exposed and this // transform might pre-transform TS sources. castAsAny( factory, factory.createObjectLiteralExpression([ ...(callArgs.length > 1 ? [factory.createSpreadAssignment(callArgs[1])] : []), factory.createPropertyAssignment('isSignal', factory.createTrue()), ]), ), ], ), ); return factory.updatePropertyDeclaration( member.node, [newDecorator, ...(member.node.modifiers ?? [])], member.node.name, member.node.questionToken, member.node.type, member.node.initializer, ); };
{ "end_byte": 3297, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/query_functions.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform.ts_0_4775
/** * @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.dev/license */ import ts from 'typescript'; import {isAngularDecorator} from '../../../../annotations'; import {ImportedSymbolsTracker} from '../../../../imports'; import {ReflectionHost} from '../../../../reflection'; import {reflectClassMember} from '../../../../reflection/src/typescript'; import {ImportManager} from '../../../../translator'; import {signalInputsTransform} from './input_function'; import {signalModelTransform} from './model_function'; import {initializerApiOutputTransform} from './output_function'; import {queryFunctionsTransforms} from './query_functions'; import {PropertyTransform} from './transform_api'; /** Decorators for classes that should be transformed. */ const decoratorsWithInputs = ['Directive', 'Component']; /** * List of possible property transforms. * The first one matched on a class member will apply. */ const propertyTransforms: PropertyTransform[] = [ signalInputsTransform, initializerApiOutputTransform, queryFunctionsTransforms, signalModelTransform, ]; /** * Creates an AST transform that looks for Angular classes and transforms * initializer-based declared members to work with JIT compilation. * * For example, an `input()` member may be transformed to add an `@Input` * decorator for JIT. * * @param host Reflection host * @param importTracker Import tracker for efficient import checking. * @param isCore Whether this transforms runs against `@angular/core`. * @param shouldTransformClass Optional function to check if a given class should be transformed. */ export function getInitializerApiJitTransform( host: ReflectionHost, importTracker: ImportedSymbolsTracker, isCore: boolean, shouldTransformClass?: (node: ts.ClassDeclaration) => boolean, ): ts.TransformerFactory<ts.SourceFile> { return (ctx) => { return (sourceFile) => { const importManager = new ImportManager(); sourceFile = ts.visitNode( sourceFile, createTransformVisitor( ctx, host, importManager, importTracker, isCore, shouldTransformClass, ), ts.isSourceFile, ); return importManager.transformTsFile(ctx, sourceFile); }; }; } function createTransformVisitor( ctx: ts.TransformationContext, host: ReflectionHost, importManager: ImportManager, importTracker: ImportedSymbolsTracker, isCore: boolean, shouldTransformClass?: (node: ts.ClassDeclaration) => boolean, ): ts.Visitor<ts.Node, ts.Node> { const visitor: ts.Visitor<ts.Node, ts.Node> = (node: ts.Node): ts.Node => { if (ts.isClassDeclaration(node) && node.name !== undefined) { const originalNode = ts.getOriginalNode(node, ts.isClassDeclaration); // Note: Attempt to detect the `angularDecorator` on the original node of the class. // That is because e.g. Tsickle or other transforms might have transformed the node // already to transform decorators. const angularDecorator = host .getDecoratorsOfDeclaration(originalNode) ?.find((d) => decoratorsWithInputs.some((name) => isAngularDecorator(d, name, isCore))); if ( angularDecorator !== undefined && (shouldTransformClass === undefined || shouldTransformClass(node)) ) { let hasChanged = false; const sourceFile = originalNode.getSourceFile(); const members = node.members.map((memberNode) => { if (!ts.isPropertyDeclaration(memberNode)) { return memberNode; } const member = reflectClassMember(memberNode); if (member === null) { return memberNode; } // Find the first matching transform and update the class member. for (const transform of propertyTransforms) { const newNode = transform( {...member, node: memberNode}, sourceFile, host, ctx.factory, importTracker, importManager, angularDecorator, isCore, ); if (newNode !== member.node) { hasChanged = true; return newNode; } } return memberNode; }); if (hasChanged) { return ctx.factory.updateClassDeclaration( node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members, ); } } } return ts.visitEachChild(node, visitor, ctx); }; return visitor; }
{ "end_byte": 4775, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/input_function.ts_0_3221
/** * @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.dev/license */ import {core} from '@angular/compiler'; import ts from 'typescript'; import {isAngularDecorator, tryParseSignalInputMapping} from '../../../../annotations'; import { castAsAny, createSyntheticAngularCoreDecoratorAccess, PropertyTransform, } from './transform_api'; /** * Transform that will automatically add an `@Input` decorator for all signal * inputs in Angular classes. The decorator will capture metadata of the signal * input, derived from the `input()/input.required()` initializer. * * This transform is useful for JIT environments where signal inputs would like to be * used. e.g. for Angular CLI unit testing. In such environments, signal inputs are not * statically retrievable at runtime. JIT compilation needs to know about all possible inputs * before instantiating directives. A decorator exposes this information to the class without * the class needing to be instantiated. */ export const signalInputsTransform: PropertyTransform = ( member, sourceFile, host, factory, importTracker, importManager, classDecorator, isCore, ) => { // If the field already is decorated, we handle this gracefully and skip it. if ( host .getDecoratorsOfDeclaration(member.node) ?.some((d) => isAngularDecorator(d, 'Input', isCore)) ) { return member.node; } const inputMapping = tryParseSignalInputMapping(member, host, importTracker); if (inputMapping === null) { return member.node; } const fields: Record<keyof Required<core.Input>, ts.Expression> = { 'isSignal': factory.createTrue(), 'alias': factory.createStringLiteral(inputMapping.bindingPropertyName), 'required': inputMapping.required ? factory.createTrue() : factory.createFalse(), // For signal inputs, transforms are captured by the input signal. The runtime will // determine whether a transform needs to be run via the input signal, so the `transform` // option is always `undefined`. 'transform': factory.createIdentifier('undefined'), }; const newDecorator = factory.createDecorator( factory.createCallExpression( createSyntheticAngularCoreDecoratorAccess( factory, importManager, classDecorator, sourceFile, 'Input', ), undefined, [ // Cast to `any` because `isSignal` will be private, and in case this // transform is used directly as a pre-compilation step, the decorator should // not fail. It is already validated now due to us parsing the input metadata. castAsAny( factory, factory.createObjectLiteralExpression( Object.entries(fields).map(([name, value]) => factory.createPropertyAssignment(name, value), ), ), ), ], ), ); return factory.updatePropertyDeclaration( member.node, [newDecorator, ...(member.node.modifiers ?? [])], member.name, member.node.questionToken, member.node.type, member.node.initializer, ); };
{ "end_byte": 3221, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/input_function.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/model_function.ts_0_3156
/** * @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.dev/license */ import {Decorator} from '@angular/compiler-cli/src/ngtsc/reflection'; import ts from 'typescript'; import {isAngularDecorator, tryParseSignalModelMapping} from '../../../../annotations'; import {ImportManager} from '../../../../translator'; import {createSyntheticAngularCoreDecoratorAccess, PropertyTransform} from './transform_api'; /** * Transform that automatically adds `@Input` and `@Output` to members initialized as `model()`. * It is useful for JIT environments where models can't be recognized based on the initializer. */ export const signalModelTransform: PropertyTransform = ( member, sourceFile, host, factory, importTracker, importManager, classDecorator, isCore, ) => { if ( host.getDecoratorsOfDeclaration(member.node)?.some((d) => { return isAngularDecorator(d, 'Input', isCore) || isAngularDecorator(d, 'Output', isCore); }) ) { return member.node; } const modelMapping = tryParseSignalModelMapping(member, host, importTracker); if (modelMapping === null) { return member.node; } const inputConfig = factory.createObjectLiteralExpression([ factory.createPropertyAssignment( 'isSignal', modelMapping.input.isSignal ? factory.createTrue() : factory.createFalse(), ), factory.createPropertyAssignment( 'alias', factory.createStringLiteral(modelMapping.input.bindingPropertyName), ), factory.createPropertyAssignment( 'required', modelMapping.input.required ? factory.createTrue() : factory.createFalse(), ), ]); const inputDecorator = createDecorator( 'Input', // Config is cast to `any` because `isSignal` will be private, and in case this // transform is used directly as a pre-compilation step, the decorator should // not fail. It is already validated now due to us parsing the input metadata. factory.createAsExpression( inputConfig, factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ), classDecorator, factory, sourceFile, importManager, ); const outputDecorator = createDecorator( 'Output', factory.createStringLiteral(modelMapping.output.bindingPropertyName), classDecorator, factory, sourceFile, importManager, ); return factory.updatePropertyDeclaration( member.node, [inputDecorator, outputDecorator, ...(member.node.modifiers ?? [])], member.node.name, member.node.questionToken, member.node.type, member.node.initializer, ); }; function createDecorator( name: string, config: ts.Expression, classDecorator: Decorator, factory: ts.NodeFactory, sourceFile: ts.SourceFile, importManager: ImportManager, ): ts.Decorator { const callTarget = createSyntheticAngularCoreDecoratorAccess( factory, importManager, classDecorator, sourceFile, name, ); return factory.createDecorator(factory.createCallExpression(callTarget, undefined, [config])); }
{ "end_byte": 3156, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/model_function.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform_api.ts_0_2291
/** * @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.dev/license */ import ts from 'typescript'; import {ImportedSymbolsTracker} from '../../../../imports'; import {ClassMember, Decorator, ReflectionHost} from '../../../../reflection'; import {ImportManager} from '../../../../translator'; /** Function that can be used to transform class properties. */ export type PropertyTransform = ( member: Pick<ClassMember, 'name' | 'accessLevel' | 'value'> & {node: ts.PropertyDeclaration}, sourceFile: ts.SourceFile, host: ReflectionHost, factory: ts.NodeFactory, importTracker: ImportedSymbolsTracker, importManager: ImportManager, classDecorator: Decorator, isCore: boolean, ) => ts.PropertyDeclaration; /** * Creates an import and access for a given Angular core import while * ensuring the decorator symbol access can be traced back to an Angular core * import in order to make the synthetic decorator compatible with the JIT * decorator downlevel transform. */ export function createSyntheticAngularCoreDecoratorAccess( factory: ts.NodeFactory, importManager: ImportManager, ngClassDecorator: Decorator, sourceFile: ts.SourceFile, decoratorName: string, ): ts.PropertyAccessExpression { const classDecoratorIdentifier = ts.isIdentifier(ngClassDecorator.identifier) ? ngClassDecorator.identifier : ngClassDecorator.identifier.expression; return factory.createPropertyAccessExpression( importManager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: null, requestedFile: sourceFile, }), // The synthetic identifier may be checked later by the downlevel decorators // transform to resolve to an Angular import using `getSymbolAtLocation`. We trick // the transform to think it's not synthetic and comes from Angular core. ts.setOriginalNode(factory.createIdentifier(decoratorName), classDecoratorIdentifier), ); } /** Casts the given expression as `any`. */ export function castAsAny(factory: ts.NodeFactory, expr: ts.Expression): ts.Expression { return factory.createAsExpression(expr, factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)); }
{ "end_byte": 2291, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform_api.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/output_function.ts_0_2039
/** * @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.dev/license */ import {isAngularDecorator, tryParseInitializerBasedOutput} from '../../../../annotations'; import {createSyntheticAngularCoreDecoratorAccess, PropertyTransform} from './transform_api'; /** * Transform that will automatically add an `@Output` decorator for all initializer API * outputs in Angular classes. The decorator will capture metadata of the output, such * as the alias. * * This transform is useful for JIT environments. In such environments, such outputs are not * statically retrievable at runtime. JIT compilation needs to know about all possible outputs * before instantiating directives. A decorator exposes this information to the class without * the class needing to be instantiated. */ export const initializerApiOutputTransform: PropertyTransform = ( member, sourceFile, host, factory, importTracker, importManager, classDecorator, isCore, ) => { // If the field already is decorated, we handle this gracefully and skip it. if ( host .getDecoratorsOfDeclaration(member.node) ?.some((d) => isAngularDecorator(d, 'Output', isCore)) ) { return member.node; } const output = tryParseInitializerBasedOutput(member, host, importTracker); if (output === null) { return member.node; } const newDecorator = factory.createDecorator( factory.createCallExpression( createSyntheticAngularCoreDecoratorAccess( factory, importManager, classDecorator, sourceFile, 'Output', ), undefined, [factory.createStringLiteral(output.metadata.bindingPropertyName)], ), ); return factory.updatePropertyDeclaration( member.node, [newDecorator, ...(member.node.modifiers ?? [])], member.node.name, member.node.questionToken, member.node.type, member.node.initializer, ); };
{ "end_byte": 2039, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/output_function.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/transform.ts_0_3800
/** * @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.dev/license */ import {ConstantPool} from '@angular/compiler'; import ts from 'typescript'; import { DefaultImportTracker, ImportRewriter, LocalCompilationExtraImportsTracker, } from '../../imports'; import {getDefaultImportDeclaration} from '../../imports/src/default'; import {PerfPhase, PerfRecorder} from '../../perf'; import {Decorator, ReflectionHost} from '../../reflection'; import { ImportManager, presetImportManagerForceNamespaceImports, RecordWrappedNodeFn, translateExpression, translateStatement, TranslatorOptions, } from '../../translator'; import {visit, VisitListEntryResult, Visitor} from '../../util/src/visitor'; import {CompileResult} from './api'; import {TraitCompiler} from './compilation'; const NO_DECORATORS = new Set<ts.Decorator>(); const CLOSURE_FILE_OVERVIEW_REGEXP = /\s+@fileoverview\s+/i; /** * Metadata to support @fileoverview blocks (Closure annotations) extracting/restoring. */ interface FileOverviewMeta { comments: ts.SynthesizedComment[]; host: ts.Statement; trailing: boolean; } export function ivyTransformFactory( compilation: TraitCompiler, reflector: ReflectionHost, importRewriter: ImportRewriter, defaultImportTracker: DefaultImportTracker, localCompilationExtraImportsTracker: LocalCompilationExtraImportsTracker | null, perf: PerfRecorder, isCore: boolean, isClosureCompilerEnabled: boolean, ): ts.TransformerFactory<ts.SourceFile> { const recordWrappedNode = createRecorderFn(defaultImportTracker); return (context: ts.TransformationContext): ts.Transformer<ts.SourceFile> => { return (file: ts.SourceFile): ts.SourceFile => { return perf.inPhase(PerfPhase.Compile, () => transformIvySourceFile( compilation, context, reflector, importRewriter, localCompilationExtraImportsTracker, file, isCore, isClosureCompilerEnabled, recordWrappedNode, ), ); }; }; } /** * Visits all classes, performs Ivy compilation where Angular decorators are present and collects * result in a Map that associates a ts.ClassDeclaration with Ivy compilation results. This visitor * does NOT perform any TS transformations. */ class IvyCompilationVisitor extends Visitor { public classCompilationMap = new Map<ts.ClassDeclaration, CompileResult[]>(); public deferrableImports = new Set<ts.ImportDeclaration>(); constructor( private compilation: TraitCompiler, private constantPool: ConstantPool, ) { super(); } override visitClassDeclaration( node: ts.ClassDeclaration, ): VisitListEntryResult<ts.Statement, ts.ClassDeclaration> { // Determine if this class has an Ivy field that needs to be added, and compile the field // to an expression if so. const result = this.compilation.compile(node, this.constantPool); if (result !== null) { this.classCompilationMap.set(node, result); // Collect all deferrable imports declarations into a single set, // so that we can pass it to the transform visitor that will drop // corresponding regular import declarations. for (const classResult of result) { if (classResult.deferrableImports !== null && classResult.deferrableImports.size > 0) { classResult.deferrableImports.forEach((importDecl) => this.deferrableImports.add(importDecl), ); } } } return {node}; } } /** * Visits all classes and performs transformation of corresponding TS nodes based on the Ivy * compilation results (provided as an argument). */
{ "end_byte": 3800, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/transform.ts_3801_12367
class IvyTransformationVisitor extends Visitor { constructor( private compilation: TraitCompiler, private classCompilationMap: Map<ts.ClassDeclaration, CompileResult[]>, private reflector: ReflectionHost, private importManager: ImportManager, private recordWrappedNodeExpr: RecordWrappedNodeFn<ts.Expression>, private isClosureCompilerEnabled: boolean, private isCore: boolean, private deferrableImports: Set<ts.ImportDeclaration>, ) { super(); } override visitClassDeclaration( node: ts.ClassDeclaration, ): VisitListEntryResult<ts.Statement, ts.ClassDeclaration> { // If this class is not registered in the map, it means that it doesn't have Angular decorators, // thus no further processing is required. if (!this.classCompilationMap.has(node)) { return {node}; } const translateOptions: TranslatorOptions<ts.Expression> = { recordWrappedNode: this.recordWrappedNodeExpr, annotateForClosureCompiler: this.isClosureCompilerEnabled, }; // There is at least one field to add. const statements: ts.Statement[] = []; const members = [...node.members]; // Note: Class may be already transformed by e.g. Tsickle and // not have a direct reference to the source file. const sourceFile = ts.getOriginalNode(node).getSourceFile(); for (const field of this.classCompilationMap.get(node)!) { // Type-only member. if (field.initializer === null) { continue; } // Translate the initializer for the field into TS nodes. const exprNode = translateExpression( sourceFile, field.initializer, this.importManager, translateOptions, ); // Create a static property declaration for the new field. const property = ts.factory.createPropertyDeclaration( [ts.factory.createToken(ts.SyntaxKind.StaticKeyword)], field.name, undefined, undefined, exprNode, ); if (this.isClosureCompilerEnabled) { // Closure compiler transforms the form `Service.ɵprov = X` into `Service$ɵprov = X`. To // prevent this transformation, such assignments need to be annotated with @nocollapse. // Note that tsickle is typically responsible for adding such annotations, however it // doesn't yet handle synthetic fields added during other transformations. ts.addSyntheticLeadingComment( property, ts.SyntaxKind.MultiLineCommentTrivia, '* @nocollapse ', /* hasTrailingNewLine */ false, ); } field.statements .map((stmt) => translateStatement(sourceFile, stmt, this.importManager, translateOptions)) .forEach((stmt) => statements.push(stmt)); members.push(property); } const filteredDecorators = // Remove the decorator which triggered this compilation, leaving the others alone. maybeFilterDecorator(ts.getDecorators(node), this.compilation.decoratorsFor(node)); const nodeModifiers = ts.getModifiers(node); let updatedModifiers: ts.ModifierLike[] | undefined; if (filteredDecorators?.length || nodeModifiers?.length) { updatedModifiers = [...(filteredDecorators || []), ...(nodeModifiers || [])]; } // Replace the class declaration with an updated version. node = ts.factory.updateClassDeclaration( node, updatedModifiers, node.name, node.typeParameters, node.heritageClauses || [], // Map over the class members and remove any Angular decorators from them. members.map((member) => this._stripAngularDecorators(member)), ); return {node, after: statements}; } override visitOtherNode<T extends ts.Node>(node: T): T { if (ts.isImportDeclaration(node) && this.deferrableImports.has(node)) { // Return `null` as an indication that this node should not be present // in the final AST. Symbols from this import would be imported via // dynamic imports. return null!; } return node; } /** * Return all decorators on a `Declaration` which are from @angular/core, or an empty set if none * are. */ private _angularCoreDecorators(decl: ts.Declaration): Set<ts.Decorator> { const decorators = this.reflector.getDecoratorsOfDeclaration(decl); if (decorators === null) { return NO_DECORATORS; } const coreDecorators = decorators .filter((dec) => this.isCore || isFromAngularCore(dec)) .map((dec) => dec.node as ts.Decorator); if (coreDecorators.length > 0) { return new Set<ts.Decorator>(coreDecorators); } else { return NO_DECORATORS; } } private _nonCoreDecoratorsOnly(node: ts.HasDecorators): ts.NodeArray<ts.Decorator> | undefined { const decorators = ts.getDecorators(node); // Shortcut if the node has no decorators. if (decorators === undefined) { return undefined; } // Build a Set of the decorators on this node from @angular/core. const coreDecorators = this._angularCoreDecorators(node); if (coreDecorators.size === decorators.length) { // If all decorators are to be removed, return `undefined`. return undefined; } else if (coreDecorators.size === 0) { // If no decorators need to be removed, return the original decorators array. return nodeArrayFromDecoratorsArray(decorators); } // Filter out the core decorators. const filtered = decorators.filter((dec) => !coreDecorators.has(dec)); // If no decorators survive, return `undefined`. This can only happen if a core decorator is // repeated on the node. if (filtered.length === 0) { return undefined; } // Create a new `NodeArray` with the filtered decorators that sourcemaps back to the original. return nodeArrayFromDecoratorsArray(filtered); } /** * Remove Angular decorators from a `ts.Node` in a shallow manner. * * This will remove decorators from class elements (getters, setters, properties, methods) as well * as parameters of constructors. */ private _stripAngularDecorators<T extends ts.Node>(node: T): T { const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; const nonCoreDecorators = ts.canHaveDecorators(node) ? this._nonCoreDecoratorsOnly(node) : undefined; const combinedModifiers = [...(nonCoreDecorators || []), ...(modifiers || [])]; if (ts.isParameter(node)) { // Strip decorators from parameters (probably of the constructor). node = ts.factory.updateParameterDeclaration( node, combinedModifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer, ) as T & ts.ParameterDeclaration; } else if (ts.isMethodDeclaration(node)) { // Strip decorators of methods. node = ts.factory.updateMethodDeclaration( node, combinedModifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body, ) as T & ts.MethodDeclaration; } else if (ts.isPropertyDeclaration(node)) { // Strip decorators of properties. node = ts.factory.updatePropertyDeclaration( node, combinedModifiers, node.name, node.questionToken, node.type, node.initializer, ) as T & ts.PropertyDeclaration; } else if (ts.isGetAccessor(node)) { // Strip decorators of getters. node = ts.factory.updateGetAccessorDeclaration( node, combinedModifiers, node.name, node.parameters, node.type, node.body, ) as T & ts.GetAccessorDeclaration; } else if (ts.isSetAccessor(node)) { // Strip decorators of setters. node = ts.factory.updateSetAccessorDeclaration( node, combinedModifiers, node.name, node.parameters, node.body, ) as T & ts.SetAccessorDeclaration; } else if (ts.isConstructorDeclaration(node)) { // For constructors, strip decorators of the parameters. const parameters = node.parameters.map((param) => this._stripAngularDecorators(param)); node = ts.factory.updateConstructorDeclaration(node, modifiers, parameters, node.body) as T & ts.ConstructorDeclaration; } return node; } } /** * A transformer which operates on ts.SourceFiles and applies changes from an `IvyCompilation`. */ f
{ "end_byte": 12367, "start_byte": 3801, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/transform.ts_12368_19344
nction transformIvySourceFile( compilation: TraitCompiler, context: ts.TransformationContext, reflector: ReflectionHost, importRewriter: ImportRewriter, localCompilationExtraImportsTracker: LocalCompilationExtraImportsTracker | null, file: ts.SourceFile, isCore: boolean, isClosureCompilerEnabled: boolean, recordWrappedNode: RecordWrappedNodeFn<ts.Expression>, ): ts.SourceFile { const constantPool = new ConstantPool(isClosureCompilerEnabled); const importManager = new ImportManager({ ...presetImportManagerForceNamespaceImports, rewriter: importRewriter, }); // The transformation process consists of 2 steps: // // 1. Visit all classes, perform compilation and collect the results. // 2. Perform actual transformation of required TS nodes using compilation results from the first // step. // // This is needed to have all `o.Expression`s generated before any TS transforms happen. This // allows `ConstantPool` to properly identify expressions that can be shared across multiple // components declared in the same file. // Step 1. Go though all classes in AST, perform compilation and collect the results. const compilationVisitor = new IvyCompilationVisitor(compilation, constantPool); visit(file, compilationVisitor, context); // Step 2. Scan through the AST again and perform transformations based on Ivy compilation // results obtained at Step 1. const transformationVisitor = new IvyTransformationVisitor( compilation, compilationVisitor.classCompilationMap, reflector, importManager, recordWrappedNode, isClosureCompilerEnabled, isCore, compilationVisitor.deferrableImports, ); let sf = visit(file, transformationVisitor, context); // Generate the constant statements first, as they may involve adding additional imports // to the ImportManager. const downlevelTranslatedCode = getLocalizeCompileTarget(context) < ts.ScriptTarget.ES2015; const constants = constantPool.statements.map((stmt) => translateStatement(file, stmt, importManager, { recordWrappedNode, downlevelTaggedTemplates: downlevelTranslatedCode, downlevelVariableDeclarations: downlevelTranslatedCode, annotateForClosureCompiler: isClosureCompilerEnabled, }), ); // Preserve @fileoverview comments required by Closure, since the location might change as a // result of adding extra imports and constant pool statements. const fileOverviewMeta = isClosureCompilerEnabled ? getFileOverviewComment(sf.statements) : null; // Add extra imports. if (localCompilationExtraImportsTracker !== null) { for (const moduleName of localCompilationExtraImportsTracker.getImportsForFile(sf)) { importManager.addSideEffectImport(sf, moduleName); } } // Add new imports for this file. sf = importManager.transformTsFile(context, sf, constants); if (fileOverviewMeta !== null) { sf = insertFileOverviewComment(sf, fileOverviewMeta); } return sf; } /** * Compute the correct target output for `$localize` messages generated by Angular * * In some versions of TypeScript, the transformation of synthetic `$localize` tagged template * literals is broken. See https://github.com/microsoft/TypeScript/issues/38485 * * Here we compute what the expected final output target of the compilation will * be so that we can generate ES5 compliant `$localize` calls instead of relying upon TS to do the * downleveling for us. */ function getLocalizeCompileTarget( context: ts.TransformationContext, ): Exclude<ts.ScriptTarget, ts.ScriptTarget.JSON> { const target = context.getCompilerOptions().target || ts.ScriptTarget.ES2015; return target !== ts.ScriptTarget.JSON ? target : ts.ScriptTarget.ES2015; } function getFileOverviewComment(statements: ts.NodeArray<ts.Statement>): FileOverviewMeta | null { if (statements.length > 0) { const host = statements[0]; let trailing = false; let comments = ts.getSyntheticLeadingComments(host); // If @fileoverview tag is not found in source file, tsickle produces fake node with trailing // comment and inject it at the very beginning of the generated file. So we need to check for // leading as well as trailing comments. if (!comments || comments.length === 0) { trailing = true; comments = ts.getSyntheticTrailingComments(host); } if (comments && comments.length > 0 && CLOSURE_FILE_OVERVIEW_REGEXP.test(comments[0].text)) { return {comments, host, trailing}; } } return null; } function insertFileOverviewComment( sf: ts.SourceFile, fileoverview: FileOverviewMeta, ): ts.SourceFile { const {comments, host, trailing} = fileoverview; // If host statement is no longer the first one, it means that extra statements were added at the // very beginning, so we need to relocate @fileoverview comment and cleanup the original statement // that hosted it. if (sf.statements.length > 0 && host !== sf.statements[0]) { if (trailing) { ts.setSyntheticTrailingComments(host, undefined); } else { ts.setSyntheticLeadingComments(host, undefined); } // Note: Do not use the first statement as it may be elided at runtime. // E.g. an import declaration that is type only. const commentNode = ts.factory.createNotEmittedStatement(sf); ts.setSyntheticLeadingComments(commentNode, comments); return ts.factory.updateSourceFile( sf, [commentNode, ...sf.statements], sf.isDeclarationFile, sf.referencedFiles, sf.typeReferenceDirectives, sf.hasNoDefaultLib, sf.libReferenceDirectives, ); } return sf; } function maybeFilterDecorator( decorators: readonly ts.Decorator[] | undefined, toRemove: ts.Decorator[], ): ts.NodeArray<ts.Decorator> | undefined { if (decorators === undefined) { return undefined; } const filtered = decorators.filter( (dec) => toRemove.find((decToRemove) => ts.getOriginalNode(dec) === decToRemove) === undefined, ); if (filtered.length === 0) { return undefined; } return ts.factory.createNodeArray(filtered); } function isFromAngularCore(decorator: Decorator): boolean { return decorator.import !== null && decorator.import.from === '@angular/core'; } function createRecorderFn( defaultImportTracker: DefaultImportTracker, ): RecordWrappedNodeFn<ts.Expression> { return (node) => { const importDecl = getDefaultImportDeclaration(node); if (importDecl !== null) { defaultImportTracker.recordUsedImport(importDecl); } }; } /** Creates a `NodeArray` with the correct offsets from an array of decorators. */ function nodeArrayFromDecoratorsArray( decorators: readonly ts.Decorator[], ): ts.NodeArray<ts.Decorator> { const array = ts.factory.createNodeArray(decorators); if (array.length > 0) { (array.pos as number) = decorators[0].pos; (array.end as number) = decorators[decorators.length - 1].end; } return array; }
{ "end_byte": 19344, "start_byte": 12368, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/transform.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts_0_2748
/** * @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.dev/license */ import {ConstantPool} from '@angular/compiler'; import ts from 'typescript'; import {SourceFileTypeIdentifier} from '../../core/api'; import {ErrorCode, FatalDiagnosticError} from '../../diagnostics'; import {IncrementalBuild} from '../../incremental/api'; import {SemanticDepGraphUpdater, SemanticSymbol} from '../../incremental/semantic_graph'; import {IndexingContext} from '../../indexer'; import {PerfEvent, PerfRecorder} from '../../perf'; import { ClassDeclaration, DeclarationNode, Decorator, isNamedClassDeclaration, ReflectionHost, } from '../../reflection'; import {ProgramTypeCheckAdapter, TypeCheckContext} from '../../typecheck/api'; import {getSourceFile} from '../../util/src/typescript'; import {Xi18nContext} from '../../xi18n'; import { AnalysisOutput, CompilationMode, CompileResult, DecoratorHandler, HandlerPrecedence, ResolveResult, } from './api'; import {DtsTransformRegistry} from './declaration'; import {PendingTrait, Trait, TraitState} from './trait'; /** * Records information about a specific class that has matched traits. */ export interface ClassRecord { /** * The `ClassDeclaration` of the class which has Angular traits applied. */ node: ClassDeclaration; /** * All traits which matched on the class. */ traits: Trait<unknown, unknown, SemanticSymbol | null, unknown>[]; /** * Meta-diagnostics about the class, which are usually related to whether certain combinations of * Angular decorators are not permitted. */ metaDiagnostics: ts.Diagnostic[] | null; // Subsequent fields are "internal" and used during the matching of `DecoratorHandler`s. This is // mutable state during the `detect`/`analyze` phases of compilation. /** * Whether `traits` contains traits matched from `DecoratorHandler`s marked as `WEAK`. */ hasWeakHandlers: boolean; /** * Whether `traits` contains a trait from a `DecoratorHandler` matched as `PRIMARY`. */ hasPrimaryHandler: boolean; } /** * The heart of Angular compilation. * * The `TraitCompiler` is responsible for processing all classes in the program. Any time a * `DecoratorHandler` matches a class, a "trait" is created to represent that Angular aspect of the * class (such as the class having a component definition). * * The `TraitCompiler` transitions each trait through the various phases of compilation, culminating * in the production of `CompileResult`s instructing the compiler to apply various mutations to the * class (like adding fields or type declarations). */
{ "end_byte": 2748, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts_2749_9355
export class TraitCompiler implements ProgramTypeCheckAdapter { /** * Maps class declarations to their `ClassRecord`, which tracks the Ivy traits being applied to * those classes. */ private classes = new Map<ClassDeclaration, ClassRecord>(); /** * Maps source files to any class declaration(s) within them which have been discovered to contain * Ivy traits. */ private fileToClasses = new Map<ts.SourceFile, Set<ClassDeclaration>>(); /** * Tracks which source files have been analyzed but did not contain any traits. This set allows * the compiler to skip analyzing these files in an incremental rebuild. */ private filesWithoutTraits = new Set<ts.SourceFile>(); private reexportMap = new Map<string, Map<string, [string, string]>>(); private handlersByName = new Map< string, DecoratorHandler<unknown, unknown, SemanticSymbol | null, unknown> >(); constructor( private handlers: DecoratorHandler<unknown, unknown, SemanticSymbol | null, unknown>[], private reflector: ReflectionHost, private perf: PerfRecorder, private incrementalBuild: IncrementalBuild<ClassRecord, unknown>, private compileNonExportedClasses: boolean, private compilationMode: CompilationMode, private dtsTransforms: DtsTransformRegistry, private semanticDepGraphUpdater: SemanticDepGraphUpdater | null, private sourceFileTypeIdentifier: SourceFileTypeIdentifier, ) { for (const handler of handlers) { this.handlersByName.set(handler.name, handler); } } analyzeSync(sf: ts.SourceFile): void { this.analyze(sf, false); } analyzeAsync(sf: ts.SourceFile): Promise<void> | undefined { return this.analyze(sf, true); } private analyze(sf: ts.SourceFile, preanalyze: false): void; private analyze(sf: ts.SourceFile, preanalyze: true): Promise<void> | undefined; private analyze(sf: ts.SourceFile, preanalyze: boolean): Promise<void> | undefined { // We shouldn't analyze declaration, shim, or resource files. if ( sf.isDeclarationFile || this.sourceFileTypeIdentifier.isShim(sf) || this.sourceFileTypeIdentifier.isResource(sf) ) { return undefined; } // analyze() really wants to return `Promise<void>|void`, but TypeScript cannot narrow a return // type of 'void', so `undefined` is used instead. const promises: Promise<void>[] = []; // Local compilation does not support incremental build. const priorWork = this.compilationMode !== CompilationMode.LOCAL ? this.incrementalBuild.priorAnalysisFor(sf) : null; if (priorWork !== null) { this.perf.eventCount(PerfEvent.SourceFileReuseAnalysis); if (priorWork.length > 0) { for (const priorRecord of priorWork) { this.adopt(priorRecord); } this.perf.eventCount(PerfEvent.TraitReuseAnalysis, priorWork.length); } else { this.filesWithoutTraits.add(sf); } // Skip the rest of analysis, as this file's prior traits are being reused. return; } const visit = (node: ts.Node): void => { if (this.reflector.isClass(node)) { this.analyzeClass(node, preanalyze ? promises : null); } ts.forEachChild(node, visit); }; visit(sf); if (!this.fileToClasses.has(sf)) { // If no traits were detected in the source file we record the source file itself to not have // any traits, such that analysis of the source file can be skipped during incremental // rebuilds. this.filesWithoutTraits.add(sf); } if (preanalyze && promises.length > 0) { return Promise.all(promises).then(() => undefined as void); } else { return undefined; } } recordFor(clazz: ClassDeclaration): ClassRecord | null { if (this.classes.has(clazz)) { return this.classes.get(clazz)!; } else { return null; } } getAnalyzedRecords(): Map<ts.SourceFile, ClassRecord[]> { const result = new Map<ts.SourceFile, ClassRecord[]>(); for (const [sf, classes] of this.fileToClasses) { const records: ClassRecord[] = []; for (const clazz of classes) { records.push(this.classes.get(clazz)!); } result.set(sf, records); } for (const sf of this.filesWithoutTraits) { result.set(sf, []); } return result; } /** * Import a `ClassRecord` from a previous compilation (only to be used in global compilation * modes) * * Traits from the `ClassRecord` have accurate metadata, but the `handler` is from the old program * and needs to be updated (matching is done by name). A new pending trait is created and then * transitioned to analyzed using the previous analysis. If the trait is in the errored state, * instead the errors are copied over. */ private adopt(priorRecord: ClassRecord): void { const record: ClassRecord = { hasPrimaryHandler: priorRecord.hasPrimaryHandler, hasWeakHandlers: priorRecord.hasWeakHandlers, metaDiagnostics: priorRecord.metaDiagnostics, node: priorRecord.node, traits: [], }; for (const priorTrait of priorRecord.traits) { const handler = this.handlersByName.get(priorTrait.handler.name)!; let trait: Trait<unknown, unknown, SemanticSymbol | null, unknown> = Trait.pending( handler, priorTrait.detected, ); if (priorTrait.state === TraitState.Analyzed || priorTrait.state === TraitState.Resolved) { const symbol = this.makeSymbolForTrait(handler, record.node, priorTrait.analysis); trait = trait.toAnalyzed(priorTrait.analysis, priorTrait.analysisDiagnostics, symbol); if (trait.analysis !== null && trait.handler.register !== undefined) { trait.handler.register(record.node, trait.analysis); } } else if (priorTrait.state === TraitState.Skipped) { trait = trait.toSkipped(); } record.traits.push(trait); } this.classes.set(record.node, record); const sf = record.node.getSourceFile(); if (!this.fileToClasses.has(sf)) { this.fileToClasses.set(sf, new Set<ClassDeclaration>()); } this.fileToClasses.get(sf)!.add(record.node); } private scanClassForTraits( clazz: ClassDeclaration, ): PendingTrait<unknown, unknown, SemanticSymbol | null, unknown>[] | null { if (!this.compileNonExportedClasses && !this.reflector.isStaticallyExported(clazz)) { return null; } const decorators = this.reflector.getDecoratorsOfDeclaration(clazz); return this.detectTraits(clazz, decorators); }
{ "end_byte": 9355, "start_byte": 2749, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts_9359_17028
protected detectTraits( clazz: ClassDeclaration, decorators: Decorator[] | null, ): PendingTrait<unknown, unknown, SemanticSymbol | null, unknown>[] | null { let record: ClassRecord | null = this.recordFor(clazz); let foundTraits: PendingTrait<unknown, unknown, SemanticSymbol | null, unknown>[] = []; // A set to track the non-Angular decorators in local compilation mode. An error will be issued // if non-Angular decorators is found in local compilation mode. const nonNgDecoratorsInLocalMode = this.compilationMode === CompilationMode.LOCAL ? new Set(decorators) : null; for (const handler of this.handlers) { const result = handler.detect(clazz, decorators); if (result === undefined) { continue; } if (nonNgDecoratorsInLocalMode !== null && result.decorator !== null) { nonNgDecoratorsInLocalMode.delete(result.decorator); } const isPrimaryHandler = handler.precedence === HandlerPrecedence.PRIMARY; const isWeakHandler = handler.precedence === HandlerPrecedence.WEAK; const trait = Trait.pending(handler, result); foundTraits.push(trait); if (record === null) { // This is the first handler to match this class. This path is a fast path through which // most classes will flow. record = { node: clazz, traits: [trait], metaDiagnostics: null, hasPrimaryHandler: isPrimaryHandler, hasWeakHandlers: isWeakHandler, }; this.classes.set(clazz, record); const sf = clazz.getSourceFile(); if (!this.fileToClasses.has(sf)) { this.fileToClasses.set(sf, new Set<ClassDeclaration>()); } this.fileToClasses.get(sf)!.add(clazz); } else { // This is at least the second handler to match this class. This is a slower path that some // classes will go through, which validates that the set of decorators applied to the class // is valid. // Validate according to rules as follows: // // * WEAK handlers are removed if a non-WEAK handler matches. // * Only one PRIMARY handler can match at a time. Any other PRIMARY handler matching a // class with an existing PRIMARY handler is an error. if (!isWeakHandler && record.hasWeakHandlers) { // The current handler is not a WEAK handler, but the class has other WEAK handlers. // Remove them. record.traits = record.traits.filter( (field) => field.handler.precedence !== HandlerPrecedence.WEAK, ); record.hasWeakHandlers = false; } else if (isWeakHandler && !record.hasWeakHandlers) { // The current handler is a WEAK handler, but the class has non-WEAK handlers already. // Drop the current one. continue; } if (isPrimaryHandler && record.hasPrimaryHandler) { // The class already has a PRIMARY handler, and another one just matched. record.metaDiagnostics = [ { category: ts.DiagnosticCategory.Error, code: Number('-99' + ErrorCode.DECORATOR_COLLISION), file: getSourceFile(clazz), start: clazz.getStart(undefined, false), length: clazz.getWidth(), messageText: 'Two incompatible decorators on class', }, ]; record.traits = foundTraits = []; break; } // Otherwise, it's safe to accept the multiple decorators here. Update some of the metadata // regarding this class. record.traits.push(trait); record.hasPrimaryHandler = record.hasPrimaryHandler || isPrimaryHandler; } } if ( nonNgDecoratorsInLocalMode !== null && nonNgDecoratorsInLocalMode.size > 0 && record !== null && record.metaDiagnostics === null ) { // Custom decorators found in local compilation mode! In this mode we don't support custom // decorators yet. But will eventually do (b/320536434). For now a temporary error is thrown. record.metaDiagnostics = [...nonNgDecoratorsInLocalMode].map((decorator) => ({ category: ts.DiagnosticCategory.Error, code: Number('-99' + ErrorCode.DECORATOR_UNEXPECTED), file: getSourceFile(clazz), start: decorator.node.getStart(), length: decorator.node.getWidth(), messageText: 'In local compilation mode, Angular does not support custom decorators. Ensure all class decorators are from Angular.', })); record.traits = foundTraits = []; } return foundTraits.length > 0 ? foundTraits : null; } private makeSymbolForTrait( handler: DecoratorHandler<unknown, unknown, SemanticSymbol | null, unknown>, decl: ClassDeclaration, analysis: Readonly<unknown> | null, ): SemanticSymbol | null { if (analysis === null) { return null; } const symbol = handler.symbol(decl, analysis); if (symbol !== null && this.semanticDepGraphUpdater !== null) { const isPrimary = handler.precedence === HandlerPrecedence.PRIMARY; if (!isPrimary) { throw new Error( `AssertionError: ${handler.name} returned a symbol but is not a primary handler.`, ); } this.semanticDepGraphUpdater.registerSymbol(symbol); } return symbol; } private analyzeClass(clazz: ClassDeclaration, preanalyzeQueue: Promise<void>[] | null): void { const traits = this.scanClassForTraits(clazz); if (traits === null) { // There are no Ivy traits on the class, so it can safely be skipped. return; } for (const trait of traits) { const analyze = () => this.analyzeTrait(clazz, trait); let preanalysis: Promise<void> | null = null; if (preanalyzeQueue !== null && trait.handler.preanalyze !== undefined) { // Attempt to run preanalysis. This could fail with a `FatalDiagnosticError`; catch it if it // does. try { preanalysis = trait.handler.preanalyze(clazz, trait.detected.metadata) || null; } catch (err) { if (err instanceof FatalDiagnosticError) { trait.toAnalyzed(null, [err.toDiagnostic()], null); return; } else { throw err; } } } if (preanalysis !== null) { preanalyzeQueue!.push(preanalysis.then(analyze)); } else { analyze(); } } } private analyzeTrait( clazz: ClassDeclaration, trait: Trait<unknown, unknown, SemanticSymbol | null, unknown>, ): void { if (trait.state !== TraitState.Pending) { throw new Error( `Attempt to analyze trait of ${clazz.name.text} in state ${ TraitState[trait.state] } (expected DETECTED)`, ); } this.perf.eventCount(PerfEvent.TraitAnalyze); // Attempt analysis. This could fail with a `FatalDiagnosticError`; catch it if it does. let result: AnalysisOutput<unknown>; try { result = trait.handler.analyze(clazz, trait.detected.metadata); } catch (err) { if (err instanceof FatalDiagnosticError) { trait.toAnalyzed(null, [err.toDiagnostic()], null); return; } else { throw err; } } const symbol = this.makeSymbolForTrait(trait.handler, clazz, result.analysis ?? null); if (result.analysis !== undefined && trait.handler.register !== undefined) { trait.handler.register(clazz, result.analysis); } trait = trait.toAnalyzed(result.analysis ?? null, result.diagnostics ?? null, symbol); }
{ "end_byte": 17028, "start_byte": 9359, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts" }
angular/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts_17032_25883
resolve(): void { const classes = this.classes.keys(); for (const clazz of classes) { const record = this.classes.get(clazz)!; for (let trait of record.traits) { const handler = trait.handler; switch (trait.state) { case TraitState.Skipped: continue; case TraitState.Pending: throw new Error( `Resolving a trait that hasn't been analyzed: ${clazz.name.text} / ${trait.handler.name}`, ); case TraitState.Resolved: throw new Error(`Resolving an already resolved trait`); } if (trait.analysis === null) { // No analysis results, cannot further process this trait. continue; } if (handler.resolve === undefined) { // No resolution of this trait needed - it's considered successful by default. trait = trait.toResolved(null, null); continue; } let result: ResolveResult<unknown>; try { result = handler.resolve(clazz, trait.analysis as Readonly<unknown>, trait.symbol); } catch (err) { if (err instanceof FatalDiagnosticError) { trait = trait.toResolved(null, [err.toDiagnostic()]); continue; } else { throw err; } } trait = trait.toResolved(result.data ?? null, result.diagnostics ?? null); if (result.reexports !== undefined) { const fileName = clazz.getSourceFile().fileName; if (!this.reexportMap.has(fileName)) { this.reexportMap.set(fileName, new Map<string, [string, string]>()); } const fileReexports = this.reexportMap.get(fileName)!; for (const reexport of result.reexports) { fileReexports.set(reexport.asAlias, [reexport.fromModule, reexport.symbolName]); } } } } } /** * Generate type-checking code into the `TypeCheckContext` for any components within the given * `ts.SourceFile`. */ typeCheck(sf: ts.SourceFile, ctx: TypeCheckContext): void { if (!this.fileToClasses.has(sf) || this.compilationMode === CompilationMode.LOCAL) { return; } for (const clazz of this.fileToClasses.get(sf)!) { const record = this.classes.get(clazz)!; for (const trait of record.traits) { if (trait.state !== TraitState.Resolved) { continue; } else if (trait.handler.typeCheck === undefined) { continue; } if (trait.resolution !== null) { trait.handler.typeCheck(ctx, clazz, trait.analysis, trait.resolution); } } } } runAdditionalChecks( sf: ts.SourceFile, check: ( clazz: ts.ClassDeclaration, handler: DecoratorHandler<unknown, unknown, SemanticSymbol | null, unknown>, ) => ts.Diagnostic[] | null, ): ts.Diagnostic[] { if (this.compilationMode === CompilationMode.LOCAL) { return []; } const classes = this.fileToClasses.get(sf); if (classes === undefined) { return []; } const diagnostics: ts.Diagnostic[] = []; for (const clazz of classes) { if (!isNamedClassDeclaration(clazz)) { continue; } const record = this.classes.get(clazz)!; for (const trait of record.traits) { const result = check(clazz, trait.handler); if (result !== null) { diagnostics.push(...result); } } } return diagnostics; } index(ctx: IndexingContext): void { for (const clazz of this.classes.keys()) { const record = this.classes.get(clazz)!; for (const trait of record.traits) { if (trait.state !== TraitState.Resolved) { // Skip traits that haven't been resolved successfully. continue; } else if (trait.handler.index === undefined) { // Skip traits that don't affect indexing. continue; } if (trait.resolution !== null) { trait.handler.index(ctx, clazz, trait.analysis, trait.resolution); } } } } xi18n(bundle: Xi18nContext): void { for (const clazz of this.classes.keys()) { const record = this.classes.get(clazz)!; for (const trait of record.traits) { if (trait.state !== TraitState.Analyzed && trait.state !== TraitState.Resolved) { // Skip traits that haven't been analyzed successfully. continue; } else if (trait.handler.xi18n === undefined) { // Skip traits that don't support xi18n. continue; } if (trait.analysis !== null) { trait.handler.xi18n(bundle, clazz, trait.analysis); } } } } updateResources(clazz: DeclarationNode): void { // Local compilation does not support incremental if ( this.compilationMode === CompilationMode.LOCAL || !this.reflector.isClass(clazz) || !this.classes.has(clazz) ) { return; } const record = this.classes.get(clazz)!; for (const trait of record.traits) { if (trait.state !== TraitState.Resolved || trait.handler.updateResources === undefined) { continue; } trait.handler.updateResources(clazz, trait.analysis, trait.resolution); } } compile(clazz: DeclarationNode, constantPool: ConstantPool): CompileResult[] | null { const original = ts.getOriginalNode(clazz) as typeof clazz; if ( !this.reflector.isClass(clazz) || !this.reflector.isClass(original) || !this.classes.has(original) ) { return null; } const record = this.classes.get(original)!; let res: CompileResult[] = []; for (const trait of record.traits) { let compileRes: CompileResult | CompileResult[]; if ( trait.state !== TraitState.Resolved || containsErrors(trait.analysisDiagnostics) || containsErrors(trait.resolveDiagnostics) ) { // Cannot compile a trait that is not resolved, or had any errors in its declaration. continue; } if (this.compilationMode === CompilationMode.LOCAL) { // `trait.analysis` is non-null asserted here because TypeScript does not recognize that // `Readonly<unknown>` is nullable (as `unknown` itself is nullable) due to the way that // `Readonly` works. compileRes = trait.handler.compileLocal( clazz, trait.analysis!, trait.resolution!, constantPool, ); } else { // `trait.resolution` is non-null asserted below because TypeScript does not recognize that // `Readonly<unknown>` is nullable (as `unknown` itself is nullable) due to the way that // `Readonly` works. if ( this.compilationMode === CompilationMode.PARTIAL && trait.handler.compilePartial !== undefined ) { compileRes = trait.handler.compilePartial(clazz, trait.analysis, trait.resolution!); } else { compileRes = trait.handler.compileFull( clazz, trait.analysis, trait.resolution!, constantPool, ); } } const compileMatchRes = compileRes; if (Array.isArray(compileMatchRes)) { for (const result of compileMatchRes) { if (!res.some((r) => r.name === result.name)) { res.push(result); } } } else if (!res.some((result) => result.name === compileMatchRes.name)) { res.push(compileMatchRes); } } // Look up the .d.ts transformer for the input file and record that at least one field was // generated, which will allow the .d.ts to be transformed later. this.dtsTransforms .getIvyDeclarationTransform(original.getSourceFile()) .addFields(original, res); // Return the instruction to the transformer so the fields will be added. return res.length > 0 ? res : null; } compileHmrUpdateCallback(clazz: DeclarationNode): ts.FunctionDeclaration | null { const original = ts.getOriginalNode(clazz) as typeof clazz; if ( !this.reflector.isClass(clazz) || !this.reflector.isClass(original) || !this.classes.has(original) ) { return null; } const record = this.classes.get(original)!; for (const trait of record.traits) { // Cannot compile a trait that is not resolved, or had any errors in its declaration. if ( trait.state === TraitState.Resolved && trait.handler.compileHmrUpdateDeclaration !== undefined && !containsErrors(trait.analysisDiagnostics) && !containsErrors(trait.resolveDiagnostics) ) { return trait.handler.compileHmrUpdateDeclaration(clazz, trait.analysis, trait.resolution!); } } return null; }
{ "end_byte": 25883, "start_byte": 17032, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts" }