diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs index d599a6766f5..300c8a260e2 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/compiler/tests.rs @@ -1510,28 +1510,37 @@ fn app_module_scope_failed(meta: &AnalysisResult) -> bool { #[test] fn test_ngmodule_non_class_reference_from_dts_reports_ng1010_on_dts() { - let decl = "export declare const NotAClass: unknown;\n"; - let meta = analyze_app_module_importing_non_class(&[("/project/decl.d.ts", decl)], "./decl"); + for annotation in ["unknown", "NotAClassDecorator"] { + let decl = format!( + "export interface NotAClassDecorator {{}}\nexport declare const NotAClass: {annotation};\n" + ); + let meta = analyze_app_module_importing_non_class( + &[("/project/decl.d.ts", decl.as_str())], + "./decl", + ); - assert!( - app_module_scope_failed(&meta), - "AppModule analysis must fail" - ); - let ng1010: Vec<_> = meta.diagnostics.iter().filter(|d| d.code == 1010).collect(); - assert_eq!(ng1010.len(), 1, "{:?}", meta.diagnostics); - let diag = ng1010[0]; - assert_eq!(diag.file_path.as_deref(), Some("/project/decl.d.ts")); - assert_eq!( - diag.message_text, - "Value at position 0 in the NgModule.imports of AppModule is not a class\n \ - Value is a reference to 'NotAClass'." - ); - let start = decl.find("NotAClass").unwrap() as u32; - let span = diag.span.as_ref().expect("NG1010 span"); - assert_eq!( - (span.start, span.end), - (start, start + "NotAClass".len() as u32) - ); + assert!( + app_module_scope_failed(&meta), + "AppModule analysis must fail ({annotation})" + ); + let ng1010: Vec<_> = meta.diagnostics.iter().filter(|d| d.code == 1010).collect(); + assert_eq!(ng1010.len(), 1, "{annotation}: {:?}", meta.diagnostics); + let diag = ng1010[0]; + assert_eq!(diag.file_path.as_deref(), Some("/project/decl.d.ts")); + assert_eq!( + diag.message_text, + "Value at position 0 in the NgModule.imports of AppModule is not a class\n \ + Value is a reference to 'NotAClass'.", + "{annotation}" + ); + let start = decl.find("NotAClass:").unwrap() as u32; + let span = diag.span.as_ref().expect("NG1010 span"); + assert_eq!( + (span.start, span.end), + (start, start + "NotAClass".len() as u32), + "{annotation}" + ); + } } /// The same mistake with a declaration in a source file of the compilation is still NG1010, diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/interpreter.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/interpreter.rs index c41c643a1e9..eb01ee6a573 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/interpreter.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/interpreter.rs @@ -579,7 +579,7 @@ impl<'a, 'e, 'i> Interpreter<'a, 'e, 'i> { return return_type_val; } - match &type_ref.type_name { + let res = match &type_ref.type_name { TSTypeName::IdentifierReference(ident) => { let res = if let Some(ref_id) = ident.reference_id.get() { self.visit_reference(ref_id, &ident.name, type_ref.span, scope) @@ -606,6 +606,12 @@ impl<'a, 'e, 'i> Interpreter<'a, 'e, 'i> { TSTypeName::ThisExpression(_) => { self.dynamic(type_ref.span, DynamicReason::UnsupportedSyntax) } + }; + + match res { + ResolvedValue::Reference(ref r) if r.kind == DeclKind::Class => res, + ResolvedValue::Incomplete(_) => self.propagate_failure(type_ref.span, res), + _ => self.dynamic(type_ref.span, DynamicReason::UnsupportedSyntax), } } diff --git a/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/tests.rs b/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/tests.rs index a28d0e13080..b1d554cdfde 100644 --- a/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/tests.rs +++ b/packages/compiler-cli/preprocessor/ng-analyze/src/evaluator/tests.rs @@ -1141,6 +1141,30 @@ fn test_declared_readonly_tuple_evaluation() { assert_eq!(ref2.name, "BreadcrumbsItem"); } +#[test] +fn test_declared_variable_type_reference_resolves_to_class_only() { + let value = eval_source("class C {}\ndeclare const X: C;\nX;"); + let ResolvedValue::Reference(reference) = value.unwrap_named() else { + panic!("expected Reference, got {value:?}"); + }; + assert_eq!(reference.name, "C"); + assert_eq!(reference.kind, DeclKind::Class); + + for source in [ + "interface I {}\ndeclare const X: I;\nX;", + "type T = {a: string};\ndeclare const X: T;\nX;", + "enum E {A}\ndeclare const X: E;\nX;", + "declare const X: Function;\nX;", + ] { + let value = eval_source(source); + let ResolvedValue::Reference(reference) = value.unwrap_named() else { + panic!("expected Reference for {source:?}, got {value:?}"); + }; + assert_eq!(reference.name, "X", "{source:?}"); + assert_eq!(reference.kind, DeclKind::Variable, "{source:?}"); + } +} + #[test] fn test_unsupported_type_operator_evaluation() { let source = r#" @@ -1359,3 +1383,24 @@ fn array_shape_around_an_imported_spread() { let value = complete_list_consumer(&format!("{LIST_IMPORTS}[C, ...LIST].length;")); assert_number(&value, 3.0); } + +#[test] +fn declared_variable_typed_with_an_import_resolves_to_class_only() { + let value = complete_across_files( + &[ + ("/app/c.ts", "export class C {}"), + ("/app/consumer.ts", "import { C } from './c';\ndeclare const X: C;\n[X];"), + ], + "/app/consumer.ts", + ); + assert_eq!(reference_names(&value), ["C"]); + + let value = complete_across_files( + &[ + ("/app/i.ts", "export interface I {}"), + ("/app/consumer.ts", "import { I } from './i';\ndeclare const X: I;\n[X];"), + ], + "/app/consumer.ts", + ); + assert_eq!(reference_names(&value), ["X"]); +} diff --git a/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts b/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts index ba2b5c0a556..78301f15eab 100644 --- a/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts +++ b/packages/compiler-cli/preprocessor/src/hybrid_compiler.ts @@ -47,6 +47,8 @@ export function getDiagnosticPath(tsconfigPath: string): string { * deterministic; the sort is stable, so a file's diagnostics sharing a span keep their * reporting order. * + * Diagnostics anchored on a `.d.ts` file are left out, see `targetsDeclarationFile`. + * * Compiler option diagnostics (`verifyCompilerOptions`) are serialized separately under * `optionDiagnostics` so downstream consumers reading `diagnostics` for per-file reporting * do not mix option diagnostics into file diagnostics. @@ -57,8 +59,12 @@ export function serializeDiagnostics( optionDiagnostics: readonly nga.NgDiagnostic[] = [], ): string { const allDiagnostics: Array = []; - for (const diags of diagnosticsMap.values()) { - allDiagnostics.push(...diags); + for (const [analyzedPath, diags] of diagnosticsMap) { + for (const diag of diags) { + if (!targetsDeclarationFile(diag, analyzedPath)) { + allDiagnostics.push(diag); + } + } } allDiagnostics.sort( (a, b) => @@ -79,6 +85,23 @@ export function serializeDiagnostics( ) + '\n' ); } + +/** + * Whether `diag` is reported against a `.d.ts` file. `analyzedPath` (the `diagnosticsMap` key) + * is the file a diagnostic without its own `filePath` belongs to. + * + * The analyzer anchors some diagnostics on a declaration in a dependency, e.g. `NG1010` for an + * `@NgModule` that imports a non-class from a `.d.ts` is reported on that declaration, like + * ngtsc's `createValueHasWrongTypeError(entry.node, ...)`. ngtsc keeps such diagnostics in + * `NgCompiler.getDiagnostics()`, but a build that asks for the diagnostics of each source file + * of the compilation unit (`getDiagnosticsForFile`) never sees them, and that is what the + * `.ngdiag.json` consumers do. `diagnosticsMap` keeps them so that `getDiagnostics()` + * consumers still can. + */ +function targetsDeclarationFile(diag: nga.NgDiagnostic, analyzedPath: string): boolean { + return (diag.filePath ?? analyzedPath).endsWith('.d.ts'); +} + export interface IAnalyzer { analyze(): AsyncIterable; analyzeOptimized(): AsyncIterable; diff --git a/packages/compiler-cli/preprocessor/test/extended_diagnostics_spec.ts b/packages/compiler-cli/preprocessor/test/extended_diagnostics_spec.ts index 5973deafc38..240b464f38f 100644 --- a/packages/compiler-cli/preprocessor/test/extended_diagnostics_spec.ts +++ b/packages/compiler-cli/preprocessor/test/extended_diagnostics_spec.ts @@ -25,7 +25,7 @@ import { type ExtendedTemplateDiagnosticName, verifyExtendedDiagnosticsOptions, } from '../src/compiler_options.js'; -import type {Diagnostic} from '../src/diagnostic.js'; +import {type Diagnostic, flattenNgDiagnosticMessage} from '../src/diagnostic.js'; import { EXTENDED_ERROR_DETAILS_PAGE_BASE_URL, ExtendedTemplateCheckerImpl, @@ -367,6 +367,36 @@ describe('extendedDiagnostics configuration validation', () => { expect(report.optionDiagnostics.length).toBe(1); expect(report.optionDiagnostics[0].code).toBe(4003); }); + + it('keeps diagnostics anchored on .d.ts files out of .ngdiag.json but in diagnosticsMap', async () => { + const session = await createIncrementalSession({ + '/app.ts': ` + import {NgModule} from '@angular/core'; + + @NgModule({ + imports: [NgModule], + }) + export class MyModule {} + `, + }); + try { + expect(await session.compileCurrent()).toEqual([]); + + const collected = [...session.compiler.diagnosticsMap.values()].flat(); + expect(collected.length).toBe(1); + expect(collected[0].code).toBe(1010); + expect(collected[0].filePath).toMatch(/\.d\.ts$/); + expect(collected[0].filePath).not.toBe('/app.ts'); + expect(flattenNgDiagnosticMessage(collected[0])).toContain( + 'Value at position 0 in the NgModule.imports of MyModule is not a class', + ); + expect(flattenNgDiagnosticMessage(collected[0])).toContain( + "Value is a reference to 'NgModule'.", + ); + } finally { + session.close(); + } + }); }); describe('extended template diagnostics', () => { diff --git a/packages/compiler-cli/preprocessor/test/utils.ts b/packages/compiler-cli/preprocessor/test/utils.ts index 82d04daa99c..bede1ec34ea 100644 --- a/packages/compiler-cli/preprocessor/test/utils.ts +++ b/packages/compiler-cli/preprocessor/test/utils.ts @@ -562,16 +562,20 @@ export async function runPipeline( } } - const hasDiagnostics = - compiler.optionDiagnostics.length > 0 || - [...compiler.diagnosticsMap.values()].some((diags) => diags.length > 0); - if (hasDiagnostics) { - const diagPath = getDiagnosticPath(tsconfigFile.path); - const diagContent = serializeDiagnostics( - tsconfigFile.path, - compiler.diagnosticsMap, - compiler.optionDiagnostics, - ); + const diagPath = getDiagnosticPath(tsconfigFile.path); + const diagContent = serializeDiagnostics( + tsconfigFile.path, + compiler.diagnosticsMap, + compiler.optionDiagnostics, + ); + const serializedDiagnostics = JSON.parse(diagContent) as { + diagnostics: unknown[]; + optionDiagnostics?: unknown[]; + }; + if ( + serializedDiagnostics.diagnostics.length > 0 || + (serializedDiagnostics.optionDiagnostics?.length ?? 0) > 0 + ) { outputs.push({ path: diagPath, content: await formatContent(diagPath, diagContent),