Repository navigation
refactor(compiler-cli): implement extended template diagnostics in preprocessor - #71316
Conversation
dc273d2 to
b771ec2
Compare
4f48156 to
79be6d0
Compare
mattrbeck
left a comment
There was a problem hiding this comment.
I'll review this more closely in the morning! I just wanted to add what Jetski came up with now in case it's actionable. Please take these comments with a grain of salt, though :p
79be6d0 to
29a805f
Compare
9f7b427 to
f0895b0
Compare
There was a problem hiding this comment.
Hi! I've been working on our internal fork of oxc-angular-compiler so have a few suggestions here.
We'll be moving to your ngp + ngtsc setup soon, and have already had success with it! Great work.
Happy to share more on this if helpful cc @JeanMeche @mattlewis92
A few parity fixes and regression tests from our OXC/tsgo work. Longer term, I would share the TypeScript-independent check logic between ngtsc and NGP. The remaining type-dependent checks need semantic queries.
| function deduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] { | ||
| const result: Diagnostic[] = []; | ||
|
|
||
| for (const diag of diagnostics) { | ||
| const isDuplicate = result.some((existingDiag) => areDiagnosticsEqual(diag, existingDiag)); | ||
|
|
||
| if (!isDuplicate) { | ||
| result.push(diag); | ||
| } | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| function areDiagnosticsEqual(first: Diagnostic, second: Diagnostic): boolean { | ||
| return ( | ||
| first.typeCheckId === second.typeCheckId && | ||
| first.start === second.start && | ||
| first.end === second.end && | ||
| first.code === second.code | ||
| ); | ||
| } |
There was a problem hiding this comment.
This drops distinct warnings at the same span. For @defer (on immediate; on timer(100ms); prefetch on idle) { <div></div> }, ngtsc returns two NG8021 warnings, but this keeps only one. Include the message and category in the key, and use a Set to avoid the quadratic scan. Please add this combined-trigger regression case.
| function deduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] { | |
| const result: Diagnostic[] = []; | |
| for (const diag of diagnostics) { | |
| const isDuplicate = result.some((existingDiag) => areDiagnosticsEqual(diag, existingDiag)); | |
| if (!isDuplicate) { | |
| result.push(diag); | |
| } | |
| } | |
| return result; | |
| } | |
| function areDiagnosticsEqual(first: Diagnostic, second: Diagnostic): boolean { | |
| return ( | |
| first.typeCheckId === second.typeCheckId && | |
| first.start === second.start && | |
| first.end === second.end && | |
| first.code === second.code | |
| ); | |
| } | |
| function deduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] { | |
| const seen = new Set<string>(); | |
| return diagnostics.filter((diag) => { | |
| const key = JSON.stringify([ | |
| diag.typeCheckId, | |
| diag.sourceFilePath, | |
| diag.start, | |
| diag.end, | |
| diag.code, | |
| diag.category, | |
| diag.message, | |
| ]); | |
| if (seen.has(key)) { | |
| return false; | |
| } | |
| seen.add(key); | |
| return true; | |
| }); | |
| } |
| } | ||
| const defaultCategory = options.extendedDiagnostics.defaultCategory; | ||
| const allCategories: readonly DiagnosticCategoryLabel[] = ['warning', 'error', 'suppress']; | ||
| if (defaultCategory && !allCategories.includes(defaultCategory)) { |
There was a problem hiding this comment.
defaultCategory: "" passes this validation and then throws in diagnosticLabelToCategory. Validate every supplied value and return NG4004. Please cover empty strings and invalid JSON value types.
| if (defaultCategory && !allCategories.includes(defaultCategory)) { | |
| if (defaultCategory !== undefined && !allCategories.includes(defaultCategory)) { |
| const unusedStandaloneImportsCat = diagnosticLabelToCategory( | ||
| options?.checks?.unusedStandaloneImports ?? options?.defaultCategory ?? 'warning', | ||
| ); |
There was a problem hiding this comment.
Pass the resolved config.unusedStandaloneImports from tcb.ts into this function and convert that value here. Recomputing it from extendedDiagnostics ignores a direct TCB config override such as unusedStandaloneImports: 'suppress'.
Add a DiagnosticCategoryLabel parameter, forward config.unusedStandaloneImports at the call site, and replace this expression with:
const unusedStandaloneImportsCat = diagnosticLabelToCategory(unusedStandaloneImports);Please test direct warning, error, and suppress overrides.
| readonly message: string; | ||
| readonly start: number; | ||
| readonly end: number; | ||
| readonly sourceFilePath?: string; |
There was a problem hiding this comment.
NG8005 currently loses ngtsc's "'variable' is declared here" related location. Keep it as owned data, then thread it through makeTemplateDiagnostic, the semantics checker, processor mapping, and diagnostic serialization/conversion. An omitted source path should mean template-relative offsets; an explicit path should mean source-file offsets.
| readonly sourceFilePath?: string; | |
| readonly sourceFilePath?: string; | |
| readonly relatedInformation?: readonly { | |
| readonly message: string; | |
| readonly start: number; | |
| readonly end: number; | |
| readonly sourceFilePath?: string; | |
| }[]; |
| ); | ||
| }); | ||
|
|
||
| it('NG8113: unusedStandaloneImports reports all unused or individual unused imports', async () => { |
There was a problem hiding this comment.
maybe needs an edit/fix parity test that reuses the compiler across used -> unused -> used imports, then compares each result with fresh compilation. Also cover selector changes, barrel exports, and diagnostic configuration changes. Include inline/external templates and Unicode before the reported span. Assert code, category, message, file, span, and related information.
e141aec to
7e61f3e
Compare
7e61f3e to
eddb0c6
Compare
| Entry::Evaluated(_, evaluated_in_file) => { | ||
| if *evaluated_in_file == reference_id.file { | ||
| let mut found = None; | ||
| for (idx, imp) in | ||
| component.parsed_imports[parsed_cursor..].iter().enumerate() | ||
| { | ||
| let matches = if imp.import_source.is_none() { | ||
| reference.file == reference_id.file | ||
| && imp.local_name == class_info.class_name | ||
| } else { | ||
| reference.aliases.get(&reference_id.file) | ||
| == Some(&imp.local_name) | ||
| }; | ||
| if matches { | ||
| parsed_cursor += idx + 1; | ||
| found = Some(imp); | ||
| break; | ||
| } | ||
| } | ||
| found | ||
| } else { | ||
| None | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| let (is_potential_shared, usage_span) = match matched_import_info { | ||
| Some(imp) if imp.in_decorator => (false, Some(imp.span)), | ||
| Some(imp) if imp.import_source.is_some() && !imp.in_exported_variable => { | ||
| (false, Some(imp.span)) | ||
| } | ||
| _ => (true, None), | ||
| }; |
There was a problem hiding this comment.
✨ Could we use ValueReference.identifiers (identity_in_expression) directly here instead of matching evaluated imports back against component.parsed_imports with parsed_cursor?
The evaluator already records identifier spans on ValueReference the same way ngtsc does, whereas matching against parsed_imports (ImportsCollector) diverges from ngtsc in a couple of cases:
- Single-directive variables (
const Alias = UnusedDir; imports: [UsedDir, Alias]):ngtscreportsNG8113onAliasinimports(even ifAliasis exported orUnusedDiris in the same file), whereasImportsCollectorunwrapsAliasto itsconstdeclaration and suppressesNG8113when exported or same-file. - Expressions evaluated by the interpreter but skipped by
ImportsCollector(imports: [cond ? UsedDir : OtherDir, UnusedDir, UsedDir]):parsed_cursorscans pastUnusedDirto match the secondUsedDir, causingUnusedDirto be skipped.
…eprocessor Implements AST-only and scope-aware extended template diagnostics, template variable write checks, and unused standalone import checks in the NGP preprocessor.
…s in preprocessor
eddb0c6 to
02f45c8
Compare
|
This PR was merged into the repository. The changes were merged into the following branches:
|
Stacked on top of #71313.
Summary
Implements AST-only and scope-aware extended template diagnostics in the NGP (
packages/compiler-cli/preprocessor) pipeline:ExtendedTemplateChecker):deferTriggerMisconfiguration(NG8021)invalidBananaInBox(NG8101)missingControlFlowDirective(NG8103)textAttributeNotBinding(NG8104)missingNgForOfLet(NG8105)suffixNotSupported(NG8106)skipHydrationNotStatic(NG8108)uninvokedFunctionInEventBinding(NG8111— inline arrow/function expressions)unusedLetDeclaration(NG8112)unparenthesizedNullishCoalescing(NG8114)missingStructuralDirective(NG8116)checkTemplateVariableWrites):@let,@for, and template#ref/let-variables (NG8005).checkUnusedStandaloneImports):@Component.importsentries and spans inng-analyze(Rust) and emitsNG8113diagnostics for unused standalone imports intcb.ts.verifyExtendedDiagnosticsOptions):extendedDiagnosticsoption compatibility (strictTemplatesrequirement,defaultCategory, andchecksnames/categories).ngp_typecheck_testing.tsand removes newly passing tests fromNGP_KNOWN_EXTENDED_CHECK_FAILURESandNGP_KNOWN_NGTSC_FAILURES.