Files
Charles Lyding ba7d313030 refactor(compiler-cli): drop filesystem type parameter from preprocessor query engine
After routing module resolution, component resource resolution, and file
loading through `AnalysisHost`, the `Fs` type parameter on `QueryEngine`
and `QueryContext` no longer described any state the engine holds. It
survived only as a `PhantomData` marker, yet it still forced roughly a
hundred query, evaluator, analyzer, and compiler functions to carry a
`ResourceResolverFs + Clone + 'static` bound and kept the engine's types
tied to the filesystem implementation that hosts are meant to abstract
away.

Make `QueryEngine`, `QueryContext`, and the `QueryCtx` aliases concrete
types and remove the marker field, then drop the bound from every
function, method, and helper type that existed only to thread it
through, including the NgModule scope `ScopeEnv` and `Resolver`, the
streaming coordinator, and `DirtyFilesSnapshot`. The filesystem type now
appears only on the `new`, `new_with_options`, and `new_default`
constructors that wrap a filesystem and resolver in a `DefaultFsHost`, so
existing callers infer it as before, while `new_with_host` and
`new_default_with_host` accept any host directly. Tests that named
`QueryEngine<OverlayFileSystem>` now use the plain engine type, and
imports left unused by the removal are dropped.

Also reword the preprocessor contributor guideline on paths and module
resolution to describe the host boundary: analysis code resolves and
loads only through `AnalysisHost`, only host implementations touch a
filesystem or `oxc_resolver`, path arithmetic applies solely to
path-backed module IDs, and the TypeScript code-generation layer remains
a pure consumer of pre-resolved metadata. There is no change in
behavior.
2026-11-11 10:26:46 -08:00

7.8 KiB

Coding Guidelines & Best Practices

When working on this codebase, adhere to the following rules:

  1. Production Quality Code: Ensure all code uses production-grade methods (e.g., no magic string regexes, lookups, etc. Use oxc AST interfaces correctly).
  2. Semantic Symbol & Scope Resolution (oxc_semantic): Always resolve identifiers, types, imports, and scope bindings through oxc_semantic (Semantic, Scoping, SymbolFlags). Look up the reference_id on AST nodes (ident.reference_id.get()), query scoping.get_reference(ref_id).symbol_id(), inspect flags with scoping.symbol_flags(symbol_id), and navigate to declarations with semantic.symbol_declaration(symbol_id). This guarantees proper lexical scoping and handles shadowed symbols correctly.
  3. AST-Driven Code Transformations: Perform all code rewrites, qualification, and emission using AST transformations or exact AST source spans (oxc_span::Span) with range-based splicing (e.g., MagicString). Avoid regex replacements on code strings to prevent corrupting string literals, property keys, or colliding identifiers.
  4. TypeScript Accuracy: Keep TypeScript types strict and accurate. Ensure all TS code passes noEmit type-checking.
  5. Feature Parity: Always verify your changes against the @angular/compiler-cli and @angular/compiler reference code. We are rewriting components and looking for feature parity. Add explicit TODO comments where reaching parity is not currently possible.
  6. Shared Utilities: Check for and utilize shared helper functions (e.g., in ng-analyze/src/analyzer/utils/mod.rs). When extracting properties from AST, always use helpers like extract_property_key or extract_string to correctly handle AST variants (like StringLiteral, TemplateLiteral, or NumericLiteral), ensuring you don't miss data that the compiler-cli handles properly.
  7. Early Returns (let...else and ?): In Rust and TypeScript, avoid deeply nested if let and conditional blocks. Prefer flattening the code structure using early returns. For matching Option/Result within functions returning those types, rely on the ? operator for automatic early returns. When you cannot use ? (e.g., returning specific fallback values or needing to continue in a loop), use let ... else blocks (e.g., let Some(x) = y else { return false; }). This mimics the flat structure and early-return style consistently used in compiler-cli.
    • Nesting Alert: It is very easy to accumulate nested if let or if blocks. Pay extra attention to these during reviews.
    • Helper Functions: If direct un-nesting via let else { continue; } is unsafe (e.g., it would skip other necessary processing in a loop), extract the nested block into a descriptive helper function to safely use early returns.
  8. Consolidate AST Analysis into Existing Visitors & Extractors: The analyzer already performs extensive AST and file analysis across source files and definition files (.d.ts). Integrate new features, fixes, and metadata extraction directly into the existing, appropriate analysis passes (such as visitor.rs, dts.rs, or shared extractors in analyzer/utils/mod.rs). When an existing visitor or helper already visits a node or inspects its symbols (such as type parameter constraints, class members, or decorator metadata), extend that pass to collect the additional information in a single traversal.
  9. Single Source of Truth for Paths & Module Resolution (Rust Analyzer Only): All module specifier resolution, component resource resolution, file loading, path diffing/joining, and import emit strategies (ReferenceEmitStrategy, ApfImportStrategy, PrefixImportStrategy) belong strictly in the Rust ng-analyze layer. Within ng-analyze, resolution and loading MUST go through the query engine's AnalysisHost (resolve_from_id/resolve_from_path, load, resolve_resource): only host implementations such as DefaultFsHost may touch a filesystem or oxc_resolver, so query, evaluator, analyzer, and compiler code never holds a filesystem or resolver of its own. Path arithmetic is only valid on IdKind::Path module IDs; IdKind::Virtual IDs are opaque and are handed back to the host verbatim. A host may be implemented outside Rust (e.g. a bundler adapter), but it only answers host requests; it never post-processes emitted specifiers. The TypeScript code-generation layer (src/tcb.ts, src/processor.ts, src/tcb_adapter.ts, etc.) is a pure downstream code generator that consumes pre-resolved metadata emitted by ng-analyze. It MUST NOT perform manual path manipulation, path.dirname/path.join rebasing, module resolution, or ad-hoc path arithmetic on module specifiers. If a module specifier or import path is incorrect in emitted code, the resolution logic MUST be implemented in the analyzer's reference projection and import emit strategies in Rust, not in TypeScript glue code.
    • Specifier Provenance: Every bare module specifier we emit must be a verbatim copy of one written in input source (an import/export … from). Never reconstruct a specifier from a file path (e.g. mapping /app/node_modules/@scope/pkg/deep/x.d.ts back to @scope/pkg). ngtsc carries owning modules as Reference.bestGuessOwningModule (imports/src/references.ts), seeded from viaModule — the literal text of a non-relative import, null for a relative one, never rewritten (reflection/src/typescript.ts) — and propagated through .d.ts metadata by APF convention (metadata/src/util.ts, extraReferenceFromTypeQuery). Before emitting one, AbsoluteModuleStrategy re-resolves it and checks the symbol is in that module's export map (imports/src/emitter.ts). In Rust, OwningReference::from_source_specifier is the only constructor; if you cannot honestly claim source provenance at a call site, the change is wrong, not the constructor. The one exception is PrefixImportStrategy, which builds specifiers from workspaceName + rootDirs (standing in for UnifiedModulesHost.fileNameToModuleName). paths is not a source of emitted specifiers in either compiler — it is module resolution (specifier → file), which does not invert.
    • No Fallback Where Upstream Fails: Where an ngtsc emit strategy cannot honour a reference it returns ReferenceEmitKind.Failed (imports/src/emitter.ts) instead of substituting a working-ish alternative, and we must reach the same outcome. Note Failed is a returned value, not a throw, and callers differ: those going through assertSuccessfulReferenceEmit raise FatalDiagnosticError NG3004 (IMPORT_GENERATION_FAILURE), the TCB defers it until the reference is actually used (typecheck/src/reference_emit_environment.ts), and canReferenceType and the language service's potential-import lookup (typecheck/src/checker.ts) treat it as a silent predicate. Match the caller, not a blanket diagnostic. A fallback upstream does not have is a bug even when its output looks better than the alternative.
  10. Cross-File Reference Projection Across Frames: Metadata extracted from AST during single-file analysis is evaluated in the frame of the declaring file (e.g. raw relative imports like ./models). When that declaration is consumed by a different file, NgModule scope, or serialized into wire metadata, all module specifiers and references MUST be projected into the consumer's frame via the query engine's ReferenceEmitStrategy (e.g. in contextualize_declaration and ClassData::to_wire). Never leak raw declaring-file-relative specifiers into consumer metadata.
  11. Matching ngtsc Strictness & Diagnostics: Match the exact behavior and strictness of ngtsc. We must not be more permissive than ngtsc. If ngtsc produces diagnostics or errors for a pattern or construct, this preprocessor should produce diagnostics as well rather than silently allowing or forgiving invalid code.