Skip to content

Commit ea1aa8c

Browse files
Brooooooklynclaude
andauthored
fix(compiler): align five small emit shapes with ngtsc (#623) (#657)
- Invalid ctor deps: a param without a usable token makes the whole factory `ɵɵinvalidFactory()` (full) / `deps: "invalid"` (partial), like ngtsc's `unwrapConstructorDependencies` (annotations/common/src/ di.ts). The linker's `ɵɵinvalidFactoryDep` is unchanged. - NgModule schemas: `ɵmod` no longer lists them. The NgModule handler passes `schemas: []` (ng_module/src/handler.ts, "FW-1004" TODO); setClassMetadata still keeps them. - Directive queries: predicates are pooled (`const _c0 = [...]`), content queries first, like `baseDirectiveFields` in render3/view/compiler.ts. Host binding constants continue the index. - Default-imported tokens stay `Foo`, not `i1.default` (typeToValue's LOCAL reference with `defaultImportStatement`). - `@Inject(TOKEN)` tokens stay as written (`getConstructorDependencies` wraps the decorator argument), not `i1.TOKEN` / `i0.DOCUMENT`. Import elision keeps these imports, also without class metadata. A default import used only as a ctor param type is kept when the factory or metadata names it; without metadata, `@Inject` / `@Attribute` replace the type as the token, so it is dropped. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4551864 commit ea1aa8c

18 files changed

Lines changed: 542 additions & 148 deletions

‎crates/oxc_angular_compiler/src/component/decorator.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -784,6 +784,7 @@ fn extract_param_dependency<'a>(
784784
// Determine the token:
785785
// 1. If @Inject(TOKEN) is present, use TOKEN
786786
// 2. Otherwise, use the type annotation
787+
let from_inject = inject_token.is_some();
787788
let (token, member_path) = inject_token
788789
.or_else(|| extract_param_token(allocator, param))
789790
.map_or((None, &[][..]), |(t, m)| (Some(t), m));
@@ -823,10 +824,10 @@ fn extract_param_dependency<'a>(
823824
// Carry the exported name so namespaced refs (`i1.X`) use the export
824825
// name, not the local alias, for aliased imports.
825826
d.token_imported_name = import_info.imported_name.clone();
826-
// Always use namespace imports for DI tokens (has_named_import = false).
827-
// Import elision removes @Inject(TOKEN) argument imports since they're
828-
// only used in decorator positions that get compiled away.
829-
// Using bare TOKEN would fail at runtime because the import is gone.
827+
// Type-annotation tokens use namespace imports (`i1.X`). Like ngtsc,
828+
// an `@Inject(TOKEN)` token keeps the expression as written and a
829+
// default import keeps its local name; import elision keeps both.
830+
d.has_named_import = from_inject || import_info.is_default_import;
830831
d
831832
}
832833
} else {

‎crates/oxc_angular_compiler/src/component/definition.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -632,11 +632,11 @@ fn generate_constructor_factory<'a>(
632632
&allocator,
633633
));
634634

635-
// If any constructor parameter resolved to a type-only import, the whole
636-
// factory cannot be formed at runtime. Emit `i0.ɵɵinvalidFactory()` instead
637-
// of a `new ClassCtor(...)` expression — matching Angular's
638-
// `ValueUnavailableKind.TYPE_ONLY_IMPORT` behaviour. See issue #288.
639-
if deps.iter().any(|d| d.type_only_invalid) {
635+
// If any constructor parameter has no usable token (or resolved to a
636+
// type-only import), the whole factory cannot be formed at runtime. Emit
637+
// `i0.ɵɵinvalidFactory()` instead of a `new ClassCtor(...)` expression —
638+
// matching ngtsc's `'invalid'` constructor deps. See issue #288.
639+
if deps.iter().any(R3DependencyMetadata::is_invalid) {
640640
statements.push(OutputStatement::Expression(Box::new_in(
641641
crate::output::ast::ExpressionStatement {
642642
expr: create_invalid_factory_call(

‎crates/oxc_angular_compiler/src/component/dependency.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,17 @@ impl<'a> R3DependencyMetadata<'a> {
149149
}
150150
}
151151

152+
/// Whether this dependency makes the whole factory invalid.
153+
///
154+
/// ngtsc never emits `ɵɵinvalidFactoryDep` in AOT: a parameter without a
155+
/// usable token turns the constructor deps into `'invalid'`, which becomes
156+
/// `ɵɵinvalidFactory()`.
157+
/// See: `packages/compiler-cli/src/ngtsc/annotations/common/src/di.ts`
158+
/// (`unwrapConstructorDependencies`).
159+
pub fn is_invalid(&self) -> bool {
160+
self.type_only_invalid || (self.token.is_none() && self.attribute_name.is_none())
161+
}
162+
152163
/// Create a dependency with `@Optional()` decorator.
153164
pub fn with_optional(mut self) -> Self {
154165
self.optional = true;
@@ -693,6 +704,11 @@ mod tests {
693704
let dep = R3DependencyMetadata::invalid();
694705
let mut registry = NamespaceRegistry::new(&allocator);
695706

707+
// A dep without a token makes the whole factory `ɵɵinvalidFactory()`,
708+
// so factory compilation never reaches the per-dep call below.
709+
assert!(dep.is_invalid());
710+
assert!(!R3DependencyMetadata::attribute(Ident::from("title")).is_invalid());
711+
696712
let result =
697713
compile_inject_dependency(&allocator, &dep, FactoryTarget::Component, 2, &mut registry);
698714

‎crates/oxc_angular_compiler/src/component/import_elision.rs‎

Lines changed: 64 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,15 @@
1717
//! - `import { type X }` - explicit type-only specifiers
1818
//! - Types only used in type annotations (e.g., `userId?: UserId`)
1919
//! - Interfaces only used in `implements` clause
20-
//! - Constructor parameter types (DI tokens are provided via namespace imports)
20+
//! - Constructor parameter types (DI tokens are provided via namespace imports),
21+
//! except default imports, which the factory names by their local name
2122
//! - Constructor parameter decorators (`@Inject`, `@Optional`, etc.) - Angular removes these
22-
//! - DI tokens used only in `@Inject(TOKEN)` arguments
2323
//!
24-
//! The last two apply only when no `ɵsetClassMetadata` is emitted: the
25-
//! metadata's `ctorParameters` callback names the param decorators and
26-
//! `@Inject` tokens as bare identifiers, so their imports must survive
27-
//! (matching ngtsc, which keeps them).
24+
//! The last one applies only when no `ɵsetClassMetadata` is emitted: the
25+
//! metadata's `ctorParameters` callback names the param decorators as bare
26+
//! identifiers, so their imports must survive (matching ngtsc, which keeps
27+
//! them). `@Inject(TOKEN)` tokens are always kept: the factory names them as
28+
//! written, like ngtsc.
2829
//!
2930
//! ## What gets preserved
3031
//!
@@ -78,11 +79,11 @@ impl<'a> ImportElisionAnalyzer<'a> {
7879
/// `emit_metadata` must mirror whether the transform will emit
7980
/// `ɵsetClassMetadata` for this file (`emit_class_metadata &&
8081
/// !advanced_optimizations`). The metadata callback names constructor
81-
/// parameter decorators (`{type: Optional}`), `@Inject(TOKEN)` argument
82-
/// tokens (`args: [TOKEN]`), and member decorators (`{type: Input}`) by
83-
/// their local (imported) name, so those imports must survive elision —
84-
/// like ngtsc, which keeps them. When no metadata is emitted, the
85-
/// decorators are stripped outright and the imports can be dropped.
82+
/// parameter decorators (`{type: Optional}`) and member decorators
83+
/// (`{type: Input}`) by their local (imported) name, so those imports must
84+
/// survive elision — like ngtsc, which keeps them. When no metadata is
85+
/// emitted, the decorators are stripped outright and the imports can be
86+
/// dropped.
8687
pub fn analyze(program: &'a Program<'a>, emit_metadata: bool) -> Self {
8788
let semantic_ret = SemanticBuilder::new().build(program);
8889
Self::analyze_with_semantic(program, &semantic_ret.semantic, emit_metadata)
@@ -197,19 +198,18 @@ impl<'a> ImportElisionAnalyzer<'a> {
197198
}
198199
let mut kept_by_output = computed_key_idents;
199200

200-
// Post-pass: when class metadata is emitted, a default import used as a
201-
// bare ctor-param type reference is emitted into the metadata's
202-
// `ctorParameters` `type:` by its local name — ngtsc keeps the import
203-
// via `defaultImportStatement` (`type_to_value.ts` +
201+
// Post-pass: a default import used as a bare ctor-param type reference
202+
// is emitted by its local name, in the factory (`ɵɵinject(Foo)`) and in
203+
// the metadata's `ctorParameters` `type:` — ngtsc keeps the import via
204+
// `defaultImportStatement` (`type_to_value.ts` +
204205
// `attachDefaultImportDeclaration`). Keep it here too, or the emitted
205-
// `type: Foo` would dangle.
206-
if emit_metadata {
207-
let ctor_type_names = Self::collect_ctor_param_type_leftmost_names(program, &consts);
208-
for name in &ctor_type_names {
209-
type_only_specifiers.remove(name);
210-
}
211-
kept_by_output.extend(ctor_type_names);
206+
// `Foo` would dangle.
207+
let ctor_type_names =
208+
Self::collect_ctor_param_type_leftmost_names(program, &consts, emit_metadata);
209+
for name in &ctor_type_names {
210+
type_only_specifiers.remove(name);
212211
}
212+
kept_by_output.extend(ctor_type_names);
213213

214214
Self {
215215
type_only_specifiers,
@@ -228,9 +228,13 @@ impl<'a> ImportElisionAnalyzer<'a> {
228228
/// Only default imports need this: named/namespace imports emit
229229
/// `i{reg}.Export`, which re-anchors the module import, while a default
230230
/// import emits its local name (upstream's LOCAL + defaultImportStatement).
231+
///
232+
/// Without metadata, only the factory names the type, and only for a
233+
/// param whose token is not overridden by `@Inject` / `@Attribute`.
231234
fn collect_ctor_param_type_leftmost_names(
232235
program: &'a Program<'a>,
233236
consts: &crate::directive::StringConsts<'a>,
237+
emit_metadata: bool,
234238
) -> FxHashSet<Ident<'a>> {
235239
let mut default_imports: FxHashSet<&'a str> = FxHashSet::default();
236240
for stmt in &program.body {
@@ -261,6 +265,7 @@ impl<'a> ImportElisionAnalyzer<'a> {
261265
class,
262266
&default_imports,
263267
consts,
268+
emit_metadata,
264269
&mut names,
265270
);
266271
}
@@ -272,6 +277,7 @@ impl<'a> ImportElisionAnalyzer<'a> {
272277
class,
273278
&default_imports,
274279
consts,
280+
emit_metadata,
275281
&mut names,
276282
);
277283
}
@@ -283,6 +289,7 @@ impl<'a> ImportElisionAnalyzer<'a> {
283289
class,
284290
&default_imports,
285291
consts,
292+
emit_metadata,
286293
&mut names,
287294
);
288295
}
@@ -301,6 +308,7 @@ impl<'a> ImportElisionAnalyzer<'a> {
301308
class: &'a oxc_ast::ast::Class<'a>,
302309
default_imports: &FxHashSet<&'a str>,
303310
consts: &crate::directive::StringConsts<'a>,
311+
emit_metadata: bool,
304312
names: &mut FxHashSet<Ident<'a>>,
305313
) {
306314
let has_angular_decorator = class
@@ -313,6 +321,20 @@ impl<'a> ImportElisionAnalyzer<'a> {
313321
let type_params = crate::class_metadata::type_param_names_of(class);
314322
if let Some(method) = crate::util::find_constructor(class) {
315323
for param in &method.value.params.items {
324+
// `@Inject(TOKEN)` / `@Attribute('x')` replace the type as the
325+
// factory's token (`getConstructorDependencies` in
326+
// `annotations/common/src/di.ts`), so only the metadata's
327+
// `type:` still names it.
328+
if !emit_metadata
329+
&& param.decorators.iter().any(|d| {
330+
matches!(
331+
crate::directive::angular_param_decorator(d, Some(consts)),
332+
Some("Inject" | "Attribute")
333+
)
334+
})
335+
{
336+
continue;
337+
}
316338
let Some(annotation) = &param.type_annotation else {
317339
continue;
318340
};
@@ -550,9 +572,8 @@ impl<'a> ImportElisionAnalyzer<'a> {
550572
///
551573
/// - an Angular constructor parameter decorator of the constructor implementation (the one
552574
/// `collect_constructor_decorator_spans` strips and the factory reads, see
553-
/// [`crate::util::find_constructor`]), with the root of `@Inject(X)` /
554-
/// `@Inject(X.sub)`: the factory names `X` through a namespace import (`i1.X.sub`), while any other
555-
/// argument (`TOKEN['sub']`, `forwardRef(() => TOKEN)`) is copied as written
575+
/// [`crate::util::find_constructor`]), but not its arguments: the factory names an `@Inject(X)`
576+
/// token as written, like ngtsc
556577
/// - the Angular member decorator itself on a `declare` property, not its arguments: a query predicate
557578
/// (`viewQuery(Foo)`) or an input `transform` is compiled into the definition by its local name
558579
///
@@ -581,23 +602,6 @@ impl<'a> ImportElisionAnalyzer<'a> {
581602
}
582603
}
583604
}
584-
/// The name a token resolves through: `TOKEN` in `TOKEN` or `TOKEN.a?.b`, like
585-
/// `resolve_factory_dep_namespaces` does. `(TOKEN).a` or `TOKEN['a']` is copied as written.
586-
fn member_chain_root<'b, 'a>(
587-
expression: &'b Expression<'a>,
588-
) -> Option<&'b oxc_ast::ast::IdentifierReference<'a>> {
589-
match expression {
590-
Expression::Identifier(id) => Some(id),
591-
Expression::StaticMemberExpression(member) => member_chain_root(&member.object),
592-
Expression::ChainExpression(chain) => match &chain.expression {
593-
oxc_ast::ast::ChainElement::StaticMemberExpression(member) => {
594-
member_chain_root(&member.object)
595-
}
596-
_ => None,
597-
},
598-
_ => None,
599-
}
600-
}
601605
let mut references = References::default();
602606
for stmt in &program.body {
603607
let class = match stmt {
@@ -621,22 +625,11 @@ impl<'a> ImportElisionAnalyzer<'a> {
621625
for param in constructor.into_iter().flat_map(|ctor| &ctor.value.params.items) {
622626
for decorator in &param.decorators {
623627
// by what it resolves to: `@I(TOKEN)` for `import { Inject as I }` is removed too
624-
let Some(name) =
625-
crate::directive::angular_param_decorator(decorator, Some(consts))
626-
else {
627-
continue;
628-
};
629-
references.visit_callee(decorator);
630-
if name == "Inject"
631-
&& let Expression::CallExpression(call) = &decorator.expression
632-
&& let Some(token) = call
633-
.arguments
634-
.first()
635-
.and_then(oxc_ast::ast::Argument::as_expression)
636-
.and_then(member_chain_root)
628+
if crate::directive::angular_param_decorator(decorator, Some(consts)).is_none()
637629
{
638-
references.visit_identifier_reference(token);
630+
continue;
639631
}
632+
references.visit_callee(decorator);
640633
}
641634
}
642635
for element in &class.body.body {
@@ -1616,8 +1609,8 @@ export class BitLabelComponent {
16161609

16171610
#[test]
16181611
fn test_inject_token_used_elsewhere_in_the_file_is_kept() {
1619-
// `@Inject(TOKEN)` is removed, but TOKEN is also a value elsewhere in the file: an exported const, a
1620-
// function, a nested scope. Each needs the import.
1612+
// `@Inject(TOKEN)` is removed and TOKEN is also a value elsewhere in the file: an exported const, a
1613+
// function, a nested scope. The import is kept (the factory names TOKEN too).
16211614
for elsewhere in [
16221615
"export const providers = [{ provide: TOKEN, useValue: 1 }];",
16231616
"export function token() { return TOKEN; }",
@@ -1649,7 +1642,8 @@ export class TestService {{
16491642

16501643
#[test]
16511644
fn test_aliased_inject_counts_as_removed() {
1652-
// `@I(TOKEN)` is Angular's Inject under an alias, which compilation removes like `@Inject(TOKEN)`
1645+
// `@I(TOKEN)` is Angular's Inject under an alias, which compilation removes like `@Inject(TOKEN)`.
1646+
// TOKEN stays: the factory names it as written.
16531647
let source = r#"
16541648
import { Injectable, Inject } from "@angular/core";
16551649
import { Inject as I } from "@angular/core";
@@ -1665,12 +1659,15 @@ export class B {
16651659
constructor(@Inject(TOKEN) private value: unknown) {}
16661660
}
16671661
"#;
1668-
assert!(analyze_source(source).contains("TOKEN"));
1662+
let type_only = analyze_source(source);
1663+
assert!(type_only.contains("I"), "the aliased Inject should be elided");
1664+
assert!(!type_only.contains("TOKEN"), "TOKEN should be kept");
16691665
}
16701666

16711667
#[test]
1672-
fn test_inject_decorator_and_token_elided() {
1673-
// @Inject(TOKEN) - both the decorator and the token should be elided
1668+
fn test_inject_decorator_elided_and_token_kept() {
1669+
// @Inject(TOKEN) - the decorator is elided, but the factory names the
1670+
// token as written (`ɵɵdirectiveInject(DOCUMENT)`), like ngtsc
16741671
let source = r#"
16751672
import { Component, Inject } from "@angular/core";
16761673
import { DOCUMENT } from "@angular/common";
@@ -1687,10 +1684,10 @@ export class TestComponent {
16871684
// Inject should be elided (ctor param decorator)
16881685
assert!(type_only.contains("Inject"), "Inject decorator should be elided");
16891686

1690-
// DOCUMENT token should be elided (only used in @Inject argument)
1687+
// DOCUMENT token should be kept (the factory uses it)
16911688
assert!(
1692-
type_only.contains("DOCUMENT"),
1693-
"DOCUMENT token should be elided (only used in @Inject)"
1689+
!type_only.contains("DOCUMENT"),
1690+
"DOCUMENT token should be kept (the factory uses it)"
16941691
);
16951692

16961693
// Component should be preserved
@@ -1721,8 +1718,8 @@ export class TestComponent {
17211718
assert!(type_only.contains(decorator), "{} decorator should be elided", decorator);
17221719
}
17231720

1724-
// LOCALE_ID token should be elided
1725-
assert!(type_only.contains("LOCALE_ID"), "LOCALE_ID token should be elided");
1721+
// LOCALE_ID token should be kept (the factory uses it)
1722+
assert!(!type_only.contains("LOCALE_ID"), "LOCALE_ID token should be kept");
17261723

17271724
// Component should be preserved
17281725
assert!(!type_only.contains("Component"), "Component should be preserved");

0 commit comments

Comments
 (0)