mirror of
https://github.com/angular/angular.git
synced 2026-11-23 07:05:14 -05:00
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.
7.8 KiB
7.8 KiB
Coding Guidelines & Best Practices
When working on this codebase, adhere to the following rules:
- Production Quality Code: Ensure all code uses production-grade methods (e.g., no magic string regexes, lookups, etc. Use
oxcAST interfaces correctly). - Semantic Symbol & Scope Resolution (
oxc_semantic): Always resolve identifiers, types, imports, and scope bindings throughoxc_semantic(Semantic,Scoping,SymbolFlags). Look up thereference_idon AST nodes (ident.reference_id.get()), queryscoping.get_reference(ref_id).symbol_id(), inspect flags withscoping.symbol_flags(symbol_id), and navigate to declarations withsemantic.symbol_declaration(symbol_id). This guarantees proper lexical scoping and handles shadowed symbols correctly. - 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. - TypeScript Accuracy: Keep TypeScript types strict and accurate. Ensure all TS code passes
noEmittype-checking. - Feature Parity: Always verify your changes against the
@angular/compiler-cliand@angular/compilerreference code. We are rewriting components and looking for feature parity. Add explicitTODOcomments where reaching parity is not currently possible. - 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 likeextract_property_keyorextract_stringto correctly handle AST variants (likeStringLiteral,TemplateLiteral, orNumericLiteral), ensuring you don't miss data that the compiler-cli handles properly. - Early Returns (
let...elseand?): In Rust and TypeScript, avoid deeply nestedif letand conditional blocks. Prefer flattening the code structure using early returns. For matchingOption/Resultwithin functions returning those types, rely on the?operator for automatic early returns. When you cannot use?(e.g., returning specific fallback values or needing tocontinuein a loop), uselet ... elseblocks (e.g.,let Some(x) = y else { return false; }). This mimics the flat structure and early-return style consistently used incompiler-cli.- Nesting Alert: It is very easy to accumulate nested
if letorifblocks. 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.
- Nesting Alert: It is very easy to accumulate nested
- 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 asvisitor.rs,dts.rs, or shared extractors inanalyzer/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. - 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 Rustng-analyzelayer. Withinng-analyze, resolution and loading MUST go through the query engine'sAnalysisHost(resolve_from_id/resolve_from_path,load,resolve_resource): only host implementations such asDefaultFsHostmay touch a filesystem oroxc_resolver, so query, evaluator, analyzer, and compiler code never holds a filesystem or resolver of its own. Path arithmetic is only valid onIdKind::Pathmodule IDs;IdKind::VirtualIDs 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 byng-analyze. It MUST NOT perform manual path manipulation,path.dirname/path.joinrebasing, 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.tsback to@scope/pkg). ngtsc carries owning modules asReference.bestGuessOwningModule(imports/src/references.ts), seeded fromviaModule— the literal text of a non-relative import,nullfor a relative one, never rewritten (reflection/src/typescript.ts) — and propagated through.d.tsmetadata by APF convention (metadata/src/util.ts,extraReferenceFromTypeQuery). Before emitting one,AbsoluteModuleStrategyre-resolves it and checks the symbol is in that module's export map (imports/src/emitter.ts). In Rust,OwningReference::from_source_specifieris the only constructor; if you cannot honestly claim source provenance at a call site, the change is wrong, not the constructor. The one exception isPrefixImportStrategy, which builds specifiers fromworkspaceName+rootDirs(standing in forUnifiedModulesHost.fileNameToModuleName).pathsis 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. NoteFailedis a returned value, not a throw, and callers differ: those going throughassertSuccessfulReferenceEmitraiseFatalDiagnosticErrorNG3004 (IMPORT_GENERATION_FAILURE), the TCB defers it until the reference is actually used (typecheck/src/reference_emit_environment.ts), andcanReferenceTypeand 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.
- Specifier Provenance: Every bare module specifier we emit must be a verbatim copy of one written in input source (an
- 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'sReferenceEmitStrategy(e.g. incontextualize_declarationandClassData::to_wire). Never leak raw declaring-file-relative specifiers into consumer metadata. - Matching
ngtscStrictness & Diagnostics: Match the exact behavior and strictness ofngtsc. We must not be more permissive thanngtsc. Ifngtscproduces diagnostics or errors for a pattern or construct, this preprocessor should produce diagnostics as well rather than silently allowing or forgiving invalid code.