Skip to content

Commit 89dd9c6

Browse files
Brooooooklynclaude
andauthored
fix: close remaining ngtsc output gaps from #623 (#670)
* fix(metadata): give const enum ctor params `type: undefined` ngtsc's typeToValue has no value for a const enum outside local compilation, so full ɵsetClassMetadata and partial ɵɵngDeclareClassMetadata write `type: undefined` for a constructor parameter typed by one. oxc wrote the name, which for a `declare const enum` threw a ReferenceError when JIT or TestBed read it. - Same file: `const enum`, `declare const enum` and `ns.E` now give `undefined`. A name a namespace, interface or `declare global` also declares keeps the reference, and so does a class nested in a function or block, since one file can't be sure what it means there. - Imported: with `resolve_imported_values`, a named import the cross-file analyzer finds to be a const enum (also through `export { X } from` and `export *`) gives `undefined` and no `i1` import. The file read becomes a watch dependency. Namespace imports, packages, .d.ts-only modules and files with a bare namespace keep the reference. - Factories and DI tokens are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(metadata): say const enums now give `type: undefined` The LocalDecls and local-reference comments still listed const enums as emitted as written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ngmodule): leave directives and pipes out of the injector imports In full and partial compilation ngtsc builds the ɵinj `imports` from what each reference resolves to (NgModuleDecoratorHandler.resolve): it drops the directives and pipes of `imports`, and the directives, components and pipes of `exports`. Oxc copied ngtsc's local compilation and added both lists as written. The runtime's walkProviderTree skips those entries, so dropping them does not change which providers are registered. An entry is dropped only when Oxc knows what it is: - from this file: an `exports` entry that `declarations` also lists, a class of the file with an Angular @directive or @pipe decorator (aliases and namespace imports of the decorator count), and an exported @component that `imports` or `declarations` also lists; - with cross-file analysis (resolveImportedValues): imported classes, `const` lists and package .d.ts types, read through the NgModule scope code. A list is dropped only when all its classes drop, and an exported component only when it is in the module's compilation scope. Anything that does not resolve, an NgModule, a forRoot() call, and a standalone component in `imports` stay. Classes nested in a function keep their lists. The files read become watch dependencies like other cross-file reads. Not done: ngtsc also drops a standalone component from `imports` when it brings in no providers, and rewrites a partly dropped list into the references it keeps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ngmodule): list the NgModule of ModuleWithProviders imports in partial declarations In partial mode, ngtsc lists the NgModule each ModuleWithProviders entry names in the `ɵɵngDeclareNgModule` imports (`resolveTypeList` with `createModuleWithProvidersResolver`): `imports: [mwp, Holder.forRoot()]` becomes `imports: [DepModule, DepModule]`. Oxc listed the class the method is called on (`Holder`) and kept constants as is. When a JIT linker inlines that list into `ɵɵdefineNgModule`, the runtime got a class that is no module and a ModuleWithProviders object, which poisons the module scope. Same file, always on: a static method of a class in this file is read in ngtsc's order (a body that is a single `return { ngModule: T }` first, then a `ModuleWithProviders<T>` return type), and top-level constants of such calls or of `{ ngModule: T }` are followed. T must be a class declared before the module, or a binding whose import is kept anyway; otherwise the entry keeps its old output, since a type-only import is removed and a later class would be read before it exists. With cross-file analysis (`resolveImportedValues`), a method or constant of another file is read through ng_module_scope.rs, and the module is named through a namespace import (`i1.DepModule`), as ngtsc does. Only the partial declaration changes: the result goes to a separate `partial_imports` list, so the injector imports and the full-mode `ɵɵsetNgModuleScope` keep the entries as written. Full output is the same. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(component): add the forbidOrphanComponents option ngtsc's `forbidOrphanComponents` compiler option adds `forbidOrphanRendering: true` to the `ɵsetClassDebugInfo` call of every component, standalone or not. In dev mode with JIT support the runtime then throws NG0981 when a non-standalone component is rendered before its NgModule was loaded. oxc had no way to turn this on. Add `forbid_orphan_components` to the Rust TransformOptions (default false), `forbidOrphanComponents` to the napi TransformOptions, and a matching vite plugin option. Full mode only: partial output has no class debug info, as in ngtsc. The default output does not change. Checked against ngtsc 22.2.3 on a file with a non-standalone component, a standalone component, a directive and a pipe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(compiler): add enableTemplateSourceLocations and rootDirs options Angular's `enableTemplateSourceLocations` option ends each view's create block with one `ɵɵattachSourceLocations(path, [[slot, offset, line, column], ...])` call. oxc had a port of the phase, but it ran whenever advancedOptimizations was off, made one op per element with 1-based lines and UTF-8 offsets, and reify threw the ops away. Now it works like ngtsc full mode: - off by default; when off the phase does no work and output is the same - one call per view, at the end of the create block, not chained - 0-based line and column and UTF-16 offsets, counted like Angular's lexer cursor in the raw source: from the .ts file start for an inline literal (escapes sit at their backslash), from the .html start for templateUrl, and from the template start for any other inline value - slots come from the element ops' own slots - only for full compilation (the linker hard-codes it off) and Angular 19.1.0-next.3 or later (or no version given) The path is project-relative, like ngtsc's getProjectRelativePath, using a new `root_dirs` option. With no root dirs nothing is emitted (ngtsc would fall back to rootDir or the working directory, which oxc does not know). An inline literal whose raw text cannot be mapped (legacy octal or `\u` surrogate escapes) also emits nothing. With root dirs set, `ɵsetClassDebugInfo`'s `filePath` is also made project-relative, and left out for a file outside every root, as ngtsc's extractClassDebugInfo does. Without root dirs it stays the path given. oxc never lowercases paths; ngtsc does on a case-insensitive file system. The napi TransformOptions gain the same two options (`enableTemplateSourceLocations`, `rootDirs`). Refs #623. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(vite): expose enableTemplateSourceLocations and rootDirs The Vite plugin exposes both options. `rootDirs` defaults to Vite's resolved `root`, so `ɵsetClassDebugInfo` `filePath` is now relative to it, as in an ngtsc build, instead of the absolute module id. The e2e compare runner passes the root dirs that match where ngtsc compiles each fixture, so `filePath` now matches and the global DEBUG_INFO_PATH known difference is gone (all 1174 fixtures pass). Refs #623. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(e2e): list ɵinj's declared-exports filtering as a known difference The compare oracle runs ngtsc in local mode, which keeps an exported declaration in ɵinj. A full ngtsc build leaves it out, as Oxc now does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(metadata): count only exported namespace const enums `NS.E` reads an exported member. A const enum one `namespace NS` block keeps to itself hid an exported `class E` of another block, so the class's ctor param lost its type (ngtsc keeps `type: NS.E`). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ngmodule): keep an MWP entry whose module this file declares later Another file's ModuleWithProviders<Later> could name a class declared after the NgModule, and the partial ɵmod then read it before it was initialized (TDZ ReferenceError). Apply the same-file check: such an entry keeps today's name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(ngmodule): cover an exported component outside a readable scope Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vite): default rootDirs to workspaceRoot, like ngtsc's cwd fallback With Vite's root, a monorepo library outside the app lost filePath and lineNumber in ɵsetClassDebugInfo. ngtsc falls back to the working directory (the workspace root). Also list the new options in the README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(compiler): resolve a templateUrl of a bare file name against the working directory A component file with no directory gave `/./x.html`, a path from the root, so no source location was emitted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(vite): build the source-location test paths for the running OS On Windows the plugin resolves `rootDirs` to `D:\proj\src`, which a bare `/proj/...` module id never matches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(compiler): only unwrap forwardRef imported from @angular/core in cross-file lists A local function named `forwardRef` may return any class, so a `const` list built with it could be dropped from ɵinj with its providers. An aliased `forwardRef` from @angular/core is now read too, as ngtsc does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(compiler): keep a ModuleWithProviders whose ngModule is a member of a parameter `return { ngModule: modules.X }` reads the call's argument when `modules` is a parameter, not a namespace import of the same name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(compiler): read a ModuleWithProviders method in ngtsc's order for NgModule scopes The scope reader read the return type first and took a parameter or a type parameter for the module. It now uses the reader the partial imports use. With overloads, both read the first declaration, as ngtsc does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(compiler): follow a returned call and read the return type when ngtsc can't evaluate a ModuleWithProviders body ngtsc's evaluator looks only through parentheses, `as` and `!`, gives up on an object literal with a getter or method, and evaluates a returned `Class.method()` call. When the body gives no value, it reads the `ModuleWithProviders<T>` return type. Both the partial imports and the NgModule scope reader now do the same. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b179ed1 commit 89dd9c6

33 files changed

Lines changed: 4634 additions & 215 deletions

‎crates/oxc_angular_compiler/src/class_metadata/builders.rs‎

Lines changed: 113 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use oxc_allocator::{Allocator, Box, Vec as AllocVec};
77
use oxc_ast::ast::{
88
BindingPattern, ChainElement, Class, ClassElement, Declaration, Decorator, Expression,
9-
ForStatementInit, ForStatementLeft, FormalParameter, ObjectPropertyKind, PropertyKey,
9+
ForStatementInit, ForStatementLeft, FormalParameter, ObjectPropertyKind, Program, PropertyKey,
1010
Statement, TSNamespaceDeclarationBody, TSType, TSTypeName, VariableDeclaration,
1111
};
1212
use oxc_span::GetSpan;
@@ -449,6 +449,13 @@ pub fn build_ctor_params_metadata_in<'a>(
449449
// without it these checks are skipped.
450450
let class_type_params = type_param_names_of(class);
451451
let local_decls = consts.and_then(StringConsts::local_decls);
452+
// A `const enum` is read by its name only for a class declared at the
453+
// file top level: a class nested in a function or block may see another
454+
// declaration of that name, which one file's top-level scan can't rule
455+
// out, so it keeps today's output.
456+
let const_enums_visible = consts
457+
.and_then(StringConsts::program)
458+
.is_some_and(|program| is_top_level_class(program, class));
452459

453460
let mut param_entries = AllocVec::new_in(&allocator);
454461

@@ -464,6 +471,7 @@ pub fn build_ctor_params_metadata_in<'a>(
464471
import_map,
465472
&class_type_params,
466473
local_decls,
474+
const_enums_visible,
467475
)
468476
.unwrap_or_else(|| {
469477
OutputExpression::Literal(Box::new_in(
@@ -951,18 +959,26 @@ fn string_literal<'a>(allocator: &'a Allocator, value: Ident<'a>) -> OutputExpre
951959
/// `TSTypeReference` after `T | null` narrowing (parens, other unions,
952960
/// `typeof`, primitives, `this`), it's a bare class type parameter, a
953961
/// type-only or bare namespace import, or it ends at an interface or type
954-
/// alias declared in the file. In local mode other value-less names (const
955-
/// enums, vars, bare namespaces, missing members, undeclared names) emit as
956-
/// written — upstream wraps them in `/* @ts-ignore */` rather than emitting
962+
/// alias declared in the file. In local mode other value-less names (vars,
963+
/// bare namespaces, missing members, undeclared names) emit as written —
964+
/// upstream wraps them in `/* @ts-ignore */` rather than emitting
957965
/// `undefined`. The DI dependency is not consulted: upstream derives `type:`
958966
/// purely from the type annotation.
967+
///
968+
/// `const enum`s follow full and partial compilation instead, the modes the
969+
/// Angular CLI and ng-packagr run: there `typeToValue` gives
970+
/// `noValueDeclaration` for a `ConstEnum` symbol, so `type:` is `undefined`.
971+
/// That holds for one declared in the file and for a named import the
972+
/// cross-file analysis found to be one ([`crate::ImportInfo::is_const_enum`]),
973+
/// when `const_enums_visible` says the class sees the file-scope names.
959974
fn build_param_type_expression<'a>(
960975
allocator: &'a Allocator,
961976
param: &FormalParameter<'a>,
962977
namespace_registry: &mut NamespaceRegistry<'a>,
963978
import_map: &ImportMap<'a>,
964979
type_params: &FxHashSet<Ident<'a>>,
965980
local_decls: Option<&LocalDecls<'a>>,
981+
const_enums_visible: bool,
966982
) -> Option<OutputExpression<'a>> {
967983
// Upstream's getConstructorParameters first narrows `T | null` to `T`
968984
// (typescript.ts); `typeToValue` then requires a bare `TypeReferenceNode`
@@ -993,6 +1009,11 @@ fn build_param_type_expression<'a>(
9931009
if import_info.is_type_only || path.len() == 1 && !import_info.is_named_import {
9941010
return None;
9951011
}
1012+
// An imported `const enum` (`import { KeyCodes }`): no value in full
1013+
// or partial `typeToValue`, so no `i1` import either.
1014+
if const_enums_visible && path.len() == 1 && import_info.is_const_enum {
1015+
return None;
1016+
}
9961017
// `import Foo from 'm'`: upstream emits the local name itself (LOCAL
9971018
// with a `defaultImportStatement`), never `i1.default`. The specifier
9981019
// kind matters — `import { default as Foo }` is IMPORTED and emits
@@ -1027,14 +1048,15 @@ fn build_param_type_expression<'a>(
10271048
));
10281049
}
10291050

1030-
// A local reference: `undefined` only when the path ends at an interface
1031-
// or type alias — the type-only declarations local `typeToValue` still
1051+
// A local reference: `undefined` when the path ends at an interface or
1052+
// type alias — the type-only declarations local `typeToValue` still
10321053
// rejects (`isLocalCompilation` keeps only those three SyntaxKinds
1033-
// unavailable). Everything else — const enums, vars, functions, bare
1054+
// unavailable) — or at a `const enum`, which full and partial
1055+
// `typeToValue` reject too. Everything else — vars, functions, bare
10341056
// namespace names, missing members, undeclared or global names — emits
10351057
// as written, matching the upstream `/* @ts-ignore */ type: X` fallback.
10361058
if let Some(decls) = local_decls
1037-
&& decls.is_type_only(&path)
1059+
&& (decls.is_type_only(&path) || const_enums_visible && decls.is_const_enum(&path))
10381060
{
10391061
return None;
10401062
}
@@ -1048,6 +1070,26 @@ fn build_param_type_expression<'a>(
10481070
))
10491071
}
10501072

1073+
/// Whether `class` is declared in `program`'s body, not in a function, block
1074+
/// or namespace.
1075+
fn is_top_level_class(program: &Program<'_>, class: &Class<'_>) -> bool {
1076+
program.body.iter().any(|stmt| {
1077+
let top = match stmt {
1078+
Statement::ClassDeclaration(top) => top,
1079+
Statement::ExportDeclaration(export) => match &export.declaration {
1080+
Declaration::ClassDeclaration(top) => top,
1081+
_ => return false,
1082+
},
1083+
Statement::ExportDefaultDeclaration(export) => match &export.declaration {
1084+
oxc_ast::ast::ExportDefaultDeclarationKind::ClassDeclaration(top) => top,
1085+
_ => return false,
1086+
},
1087+
_ => return false,
1088+
};
1089+
std::ptr::eq(top.as_ref(), class)
1090+
})
1091+
}
1092+
10511093
/// The `TSTypeReference` a ctor-param annotation narrows to, mirroring
10521094
/// `getConstructorParameters` (`typescript.ts`): `T | null` unions keep the
10531095
/// single non-`null` member. Unlike `resolve_di_token_type` (DI tokens), this
@@ -1137,10 +1179,11 @@ pub fn type_param_names_of<'a>(class: &Class<'a>) -> FxHashSet<Ident<'a>> {
11371179
/// comparison and single-file transform target — `experimental-local`, which
11381180
/// matches what OXC can know from one file): only `TypeParameter`,
11391181
/// `TypeAliasDeclaration`, and `InterfaceDeclaration` are `UNAVAILABLE`;
1140-
/// everything else — vars, functions, const enums, bare namespace names,
1141-
/// missing members, undeclared names — is emitted as written with an
1142-
/// upstream `/* @ts-ignore */` (comparisons ignore the comment, and `Ident`
1143-
/// output can't carry one anyway). `type_decls` holds interfaces and type
1182+
/// everything else — vars, functions, bare namespace names, missing
1183+
/// members, undeclared names — is emitted as written with an upstream
1184+
/// `/* @ts-ignore */` (comparisons ignore the comment, and `Ident` output
1185+
/// can't carry one anyway). `const_enums` follows full and partial
1186+
/// compilation instead (see [`Self::is_const_enum`]). `type_decls` holds interfaces and type
11441187
/// aliases; `namespaces` records namespace bodies recursively, needed for
11451188
/// `ns.Interface` lookups and for the merged `interface I` + `namespace I`
11461189
/// case — the merged symbol's valueDeclaration is the namespace, so it emits.
@@ -1156,6 +1199,9 @@ pub(crate) struct LocalDecls<'a> {
11561199
/// Names a `declare global` block declares (root only). See
11571200
/// [`Self::is_type_only_token`].
11581201
global_names: FxHashSet<&'a str>,
1202+
/// Names declared by a `const enum` (also in `value_decls`). See
1203+
/// [`Self::is_const_enum`].
1204+
const_enums: FxHashSet<&'a str>,
11591205
}
11601206

11611207
impl<'a> LocalDecls<'a> {
@@ -1242,6 +1288,9 @@ impl<'a> LocalDecls<'a> {
12421288
}
12431289
Statement::TSEnumDeclaration(decl) => {
12441290
self.value_decls.insert(decl.id.name.as_str());
1291+
if decl.r#const {
1292+
self.const_enums.insert(decl.id.name.as_str());
1293+
}
12451294
}
12461295
Statement::TSImportEqualsDeclaration(decl) => {
12471296
if decl.import_kind.is_type() {
@@ -1350,6 +1399,9 @@ impl<'a> LocalDecls<'a> {
13501399
}
13511400
Declaration::TSEnumDeclaration(d) => {
13521401
self.value_decls.insert(d.id.name.as_str());
1402+
if d.r#const {
1403+
self.const_enums.insert(d.id.name.as_str());
1404+
}
13531405
}
13541406
Declaration::TSImportEqualsDeclaration(d) => {
13551407
if d.import_kind.is_type() {
@@ -1403,28 +1455,44 @@ impl<'a> LocalDecls<'a> {
14031455
decl: &'a oxc_ast::ast::TSNamespaceDeclaration<'a>,
14041456
globals: &mut std::vec::Vec<&'a Statement<'a>>,
14051457
) {
1406-
self.namespaces
1407-
.entry(decl.id.name.as_str())
1408-
.or_default()
1409-
.merge(Self::from_namespace_body(&decl.body, globals));
1458+
self.namespaces.entry(decl.id.name.as_str()).or_default().merge(Self::from_namespace_body(
1459+
&decl.body,
1460+
decl.declare,
1461+
globals,
1462+
));
14101463
}
14111464

1465+
/// `ambient` is whether the namespace is `declare`d, where every member
1466+
/// is visible from outside it.
14121467
fn from_namespace_body(
14131468
body: &'a TSNamespaceDeclarationBody<'a>,
1469+
ambient: bool,
14141470
globals: &mut std::vec::Vec<&'a Statement<'a>>,
14151471
) -> Self {
14161472
match body {
14171473
TSNamespaceDeclarationBody::TSModuleBlock(block) => {
14181474
let mut decls = LocalDecls::default();
14191475
decls.insert_all(&block.body, globals);
1476+
// `NS.E` reads an exported member only: a const enum the block
1477+
// keeps to itself must not hide an exported `E` that another
1478+
// `namespace NS` block declares.
1479+
if !ambient {
1480+
decls.const_enums.retain(|name| {
1481+
block.body.iter().any(|stmt| {
1482+
matches!(stmt, Statement::ExportDeclaration(export)
1483+
if matches!(&export.declaration,
1484+
Declaration::TSEnumDeclaration(e) if e.id.name == *name))
1485+
})
1486+
});
1487+
}
14201488
decls
14211489
}
14221490
// `namespace Outer.Inner { ... }` nests by qualified name.
14231491
TSNamespaceDeclarationBody::TSNamespaceDeclaration(nested) => {
14241492
let mut decls = LocalDecls::default();
14251493
decls.namespaces.insert(
14261494
nested.id.name.as_str(),
1427-
Self::from_namespace_body(&nested.body, globals),
1495+
Self::from_namespace_body(&nested.body, ambient || nested.declare, globals),
14281496
);
14291497
decls
14301498
}
@@ -1434,6 +1502,7 @@ impl<'a> LocalDecls<'a> {
14341502
fn merge(&mut self, other: LocalDecls<'a>) {
14351503
self.type_decls.extend(other.type_decls);
14361504
self.value_decls.extend(other.value_decls);
1505+
self.const_enums.extend(other.const_enums);
14371506
for (name, nested) in other.namespaces {
14381507
self.namespaces.entry(name).or_default().merge(nested);
14391508
}
@@ -1460,6 +1529,33 @@ impl<'a> LocalDecls<'a> {
14601529
}
14611530
}
14621531

1532+
/// Whether `path` — `["ns", ..., "Name"]` — ends at a `const enum`
1533+
/// (`declare const enum` too). ngtsc's `typeToValue` has no value for
1534+
/// it outside local compilation (`decl.flags & ts.SymbolFlags.ConstEnum`
1535+
/// gives `noValueDeclaration`), so full and partial metadata write
1536+
/// `type: undefined`. A name a namespace, interface, type alias or
1537+
/// `declare global` block also declares is left out: one file can't be
1538+
/// sure what it merges with, so it keeps today's output.
1539+
pub(crate) fn is_const_enum(&self, path: &[Ident<'_>]) -> bool {
1540+
match path.split_first() {
1541+
None => false,
1542+
Some((name, [])) => {
1543+
let name = name.as_str();
1544+
self.const_enums.contains(name)
1545+
&& !self.namespaces.contains_key(name)
1546+
&& !self.type_decls.contains(name)
1547+
&& !self.global_names.contains(name)
1548+
}
1549+
Some((name, rest)) => {
1550+
!self.global_names.contains(name.as_str())
1551+
&& self
1552+
.namespaces
1553+
.get(name.as_str())
1554+
.is_some_and(|nested| nested.is_const_enum(rest))
1555+
}
1556+
}
1557+
}
1558+
14631559
/// [`Self::is_type_only`] for a DI token of `class`'s constructor, leaving
14641560
/// out names one file can't prove have no value:
14651561
/// - the class's own name: a class nested in a block or function, named

0 commit comments

Comments
 (0)