mirror of
https://github.com/angular/angular.git
synced 2026-11-23 07:05:14 -05:00
fix(compiler-cli): don't report diagnostics against .d.ts files in preprocessor
Fixes that referencing a non-class from a declaration file in an `NgModule` (e.g. passing `NgModule` itself into `imports`) produced a diagnostic pointing to the `.d.ts` file. There were two problems: 1. The evaluator was resolving a type reference to anything it could find, whereas ngtsc only resolves it if the target is a class. As a result, `declare const NgModule: NgModuleDecorator` was resolving to the interface instead of the variable. 2. ngtsc keeps diagnostics on `.d.ts` files, but they're never reported if the build only asks for the diagnostics of the compilation unit's source files, which is what the `.ngdiag.json` consumers do. We now omit them when serializing, but still keep them around so that `getDiagnostics`-style consumers can see them.
This commit is contained in:
committed by
Kristiyan Kostadinov
parent
b05f7ce15a
commit
def073ed0a
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"]);
|
||||
}
|
||||
|
||||
@@ -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<nga.NgDiagnostic> = [];
|
||||
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<nga.CompilationChunk>;
|
||||
analyzeOptimized(): AsyncIterable<nga.CompilationChunk>;
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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),
|
||||
|
||||
Reference in New Issue
Block a user