From a6f0d03b6a9aedcc0c1215b0adc50f2017fae97d Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 21:13:14 +0800 Subject: [PATCH 1/3] fix(expand-safe-reads): read guard temporaries back instead of calling again When a safe access copies a guard that has no temporary of its own, the copy re-ran every expression the guard had stored in a temporary, e.g. `(tmp_0_1 = ctx.f2())` twice, so calls and their side effects ran twice. Port Angular's eliminateTemporaryAssignments: in the copy, `tmp = expr` becomes `tmp = tmp`. Output now matches Angular's compliance file safe_access_temporaries_template_use_null.js. Co-Authored-By: Claude Opus 5.5 --- .../src/pipeline/phases/expand_safe_reads.rs | 45 +++++++++++++++++-- .../tests/integration_test.rs | 21 +++++++-- 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/crates/oxc_angular_compiler/src/pipeline/phases/expand_safe_reads.rs b/crates/oxc_angular_compiler/src/pipeline/phases/expand_safe_reads.rs index d2788be8b..b1162577a 100644 --- a/crates/oxc_angular_compiler/src/pipeline/phases/expand_safe_reads.rs +++ b/crates/oxc_angular_compiler/src/pipeline/phases/expand_safe_reads.rs @@ -77,7 +77,8 @@ use oxc_str::Ident; use crate::ir::expression::{ AssignTemporaryExpr, IrExpression, IrUnaryOperator, ReadTemporaryExpr, ResolvedCallExpr, ResolvedKeyedReadExpr, ResolvedPropertyReadExpr, SafeTernaryExpr, VisitorContextFlag, - transform_expressions_in_create_op, transform_expressions_in_update_op, + transform_expressions_in_create_op, transform_expressions_in_expression, + transform_expressions_in_update_op, }; use crate::ir::ops::XrefId; use crate::pipeline::compilation::{ComponentCompilationJob, HostBindingCompilationJob}; @@ -397,8 +398,11 @@ where source_span: None, } } else { - // Clone the guard for use in body - let guard_clone = guard.clone_in(allocator); + // Clone the guard for use in body. Temporaries assigned in the guard are + // already set when the body runs, so the clone reads them instead of + // evaluating their expressions (and side effects) a second time. + let mut guard_clone = guard.clone_in(allocator); + eliminate_temporary_assignments(&mut guard_clone, allocator); SafeTernaryExpr { guard: ArenaBox::new_in(guard, &allocator), @@ -408,6 +412,41 @@ where } } +/// Replaces every `tmp = expr` in `expr` with `tmp = tmp`. +/// +/// Used on the copy of a guard that has no temporary of its own: the guard +/// itself already assigned these temporaries, so the copy reads them back +/// instead of evaluating `expr` again. Angular keeps the assignment form +/// (`(tmp = tmp)`) rather than a plain read. +/// +/// Every temporary in the copy comes from the guard it was cloned from, so +/// all of them are replaced (Angular's `temporariesIn(guard)` check). +/// +/// Arrow functions inside the guard are left alone: they are their own scope +/// and assign their own temporaries when called, so reading one back there +/// would read a variable that was never set. (Angular walks into them too, +/// but then fails to name the temporary and stops with an error.) +/// +/// Reference: expand_safe_reads.ts (`eliminateTemporaryAssignments`) +fn eliminate_temporary_assignments<'a>(expr: &mut IrExpression<'a>, allocator: &'a Allocator) { + transform_expressions_in_expression( + expr, + &|e, flags| { + if flags.contains(VisitorContextFlag::IN_CHILD_OPERATION) { + return; + } + if let IrExpression::AssignTemporary(assign) = e { + let xref = assign.xref; + *assign.expr = IrExpression::ReadTemporary(ArenaBox::new_in( + ReadTemporaryExpr { xref, name: None, source_span: None }, + &allocator, + )); + } + }, + VisitorContextFlag::NONE, + ); +} + /// Data extracted from an access expression for processing. enum AccessInfo<'a> { /// Property read: `.name` diff --git a/crates/oxc_angular_compiler/tests/integration_test.rs b/crates/oxc_angular_compiler/tests/integration_test.rs index d2e56abe3..5690ce40b 100644 --- a/crates/oxc_angular_compiler/tests/integration_test.rs +++ b/crates/oxc_angular_compiler/tests/integration_test.rs @@ -4133,7 +4133,7 @@ fn test_temporaries_are_freed_at_the_last_read() { assert!( code.contains( "((tmp_0_0.b.c.d[(((tmp_0_1=ctx.g())==null)?null:tmp_0_1.h)]==null)?null:\ - tmp_0_0.b.c.d[(((tmp_0_1=ctx.g())==null)?null:tmp_0_1.h)]\ + tmp_0_0.b.c.d[(((tmp_0_1=tmp_0_1)==null)?null:tmp_0_1.h)]\ [(((tmp_0_0=ctx.k())==null)?null:tmp_0_0.m)])" ), "{code}" @@ -4144,7 +4144,7 @@ fn test_temporaries_are_freed_at_the_last_read() { assert!(code.contains("lettmp_0_0;lettmp_0_1;"), "{code}"); assert!( code.contains( - "tmp_0_0.b[(((tmp_0_1=ctx.c())==null)?null:tmp_0_1.d)]\ + "tmp_0_0.b[(((tmp_0_1=tmp_0_1)==null)?null:tmp_0_1.d)]\ .e((((tmp_0_0=ctx.f())==null)?null:tmp_0_0.g))" ), "{code}" @@ -4155,6 +4155,21 @@ fn test_temporaries_are_freed_at_the_last_read() { assert!(code.contains("{lettmp_0_0;lettmp_0_1;lettmp_0_2;lettmp_0_3;return"), "{code}"); assert!(code.contains("(tmp_0_2=tmp_0_1.c())"), "{code}"); assert!(code.contains("(tmp_0_3=ctx.d())"), "{code}"); + // The copy of the guard reads the temporaries back instead of calling again. + assert!(code.contains("(tmp_0_1=tmp_0_1)"), "{code}"); + assert!(code.contains("(tmp_0_2=tmp_0_2)"), "{code}"); + assert!(code.contains("(tmp_0_3=tmp_0_3)"), "{code}"); + assert_eq!(code.matches("ctx.b()").count(), 1, "{code}"); + assert_eq!(code.matches("ctx.d()").count(), 1, "{code}"); + + // An arrow function inside a copied guard is its own scope: it still sets + // its own temporary instead of reading one that was never set. + let code = compile("{{ (c || ((v) => g()?.h))?.y }}"); + assert!( + code.contains("{lettmp_0_0;return(((tmp_0_0=ctx.g())==null)?null:tmp_0_0.h);}"), + "{code}" + ); + assert!(!code.contains("_tmp)"), "{code}"); // Many siblings: each op keeps its own index and the same two names. let n = 40; @@ -4165,7 +4180,7 @@ fn test_temporaries_are_freed_at_the_last_read() { for op in 0..n { let (outer, inner) = (format!("tmp_{op}_0"), format!("tmp_{op}_1")); let part = format!( - "{outer}.b[((({inner}=ctx.c())==null)?null:{inner}.d)]\ + "{outer}.b[((({inner}={inner})==null)?null:{inner}.d)]\ .e(((({outer}=ctx.f())==null)?null:{outer}.g))" ); let Some(i) = code[from..].find(&part) else { panic!("missing op {op}: {code}") }; From a949f5e67815630b6804bd689ccdf3cb3c5e0e8a Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 21:13:15 +0800 Subject: [PATCH 2/3] fix(temporary-variables): declare temporaries in assignment order The declarations were sorted as strings, so with 11 or more temporaries in one op `tmp_0_10` came before `tmp_0_2`. Keep the order the names were first assigned, like Angular's `new Set(defs.values())`. Co-Authored-By: Claude Opus 5.5 --- .../pipeline/phases/temporary_variables.rs | 22 ++++++------ .../tests/integration_test.rs | 34 +++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/oxc_angular_compiler/src/pipeline/phases/temporary_variables.rs b/crates/oxc_angular_compiler/src/pipeline/phases/temporary_variables.rs index 6f091ab3f..e6d29fdb2 100644 --- a/crates/oxc_angular_compiler/src/pipeline/phases/temporary_variables.rs +++ b/crates/oxc_angular_compiler/src/pipeline/phases/temporary_variables.rs @@ -33,9 +33,10 @@ use std::cell::RefCell; +use indexmap::IndexMap; use oxc_allocator::Allocator; use oxc_str::Ident; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; use crate::ir::expression::{ IrExpression, VisitorContextFlag, transform_expressions_in_create_op, @@ -416,13 +417,13 @@ fn create_declare_var_statement<'a>(allocator: &'a Allocator, name: &str) -> Out )) } -/// Collect unique names from defs map, sorted for deterministic output. -fn collect_unique_names(defs: &FxHashMap) -> Vec { +/// Collect the unique names in `defs`, in the order they were first assigned. +/// +/// Matches Angular's `Array.from(new Set(defs.values()))`. Sorting the names as +/// strings would put `tmp_0_10` before `tmp_0_2`. +fn collect_unique_names(defs: &IndexMap) -> Vec { let mut seen = FxHashSet::default(); - let mut names: Vec<_> = defs.values().filter(|v| seen.insert(*v)).cloned().collect(); - // Sort for deterministic output (TypeScript uses Set which has insertion order) - names.sort(); - names + defs.values().filter(|v| seen.insert(*v)).cloned().collect() } /// Assigns a name to one temporary variable expression. @@ -471,8 +472,9 @@ struct TempVarTracker { assigned: FxHashSet, /// Set of XrefIds that have been released (final read encountered). released: FxHashSet, - /// Map from XrefId to generated variable name. - defs: FxHashMap, + /// Map from XrefId to generated variable name, in the order the names were + /// first assigned (Angular's `defs` Map). + defs: IndexMap, /// Total number of reads per xref (from first pass). total_reads: FxHashMap, /// Current read count per xref (incremented during second pass). @@ -487,7 +489,7 @@ impl TempVarTracker { count: 0, assigned: FxHashSet::default(), released: FxHashSet::default(), - defs: FxHashMap::default(), + defs: IndexMap::default(), total_reads, current_reads: FxHashMap::default(), } diff --git a/crates/oxc_angular_compiler/tests/integration_test.rs b/crates/oxc_angular_compiler/tests/integration_test.rs index 5690ce40b..c63d67d4e 100644 --- a/crates/oxc_angular_compiler/tests/integration_test.rs +++ b/crates/oxc_angular_compiler/tests/integration_test.rs @@ -4188,6 +4188,40 @@ fn test_temporaries_are_freed_at_the_last_read() { } } +/// With 11 or more temporaries in one op, the declarations keep the order the +/// names were first assigned, like Angular's `new Set(defs.values())`. Sorting +/// them as strings would put `tmp_0_10` before `tmp_0_2`. Matches ngc 22.3 with +/// `legacyOptionalChaining`. +#[test] +fn test_temporary_declarations_keep_assignment_order() { + let options = + ComponentTransformOptions { legacy_optional_chaining: Some(true), ..Default::default() }; + // f0()?.[f1()?.[ ... f10()?.x ... ]]?.y keeps 11 temporaries live at once. + let mut expr = String::from("f10()?.x"); + for i in (0..10).rev() { + expr = format!("f{i}()?.[{expr}]"); + } + let source = format!( + "import {{ Component }} from '@angular/core';\n\ + @Component({{ selector: 'c', template: `{{{{ a()?.b?.c }}}} {{{{ {expr}?.y }}}}` }})\n\ + export class C {{ [k: string]: any; }}\n" + ); + // Debug builds need a bigger stack for this nesting depth. + let code = std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(move || compile_compact(&source, Some(&options))) + .unwrap() + .join() + .unwrap(); + let mut decls = String::new(); + for i in 0..=10 { + decls.push_str("lettmp_0_"); + decls.push_str(&i.to_string()); + decls.push(';'); + } + assert!(code.contains(&decls), "{code}"); +} + /// Test that multiple components with host bindings in the same file have unique constant names. /// /// This test simulates the real-world scenario from Material Angular's fab.ts where From 66d1d2a811ad613b80b12de7361623958b14d3c4 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 21:13:15 +0800 Subject: [PATCH 3/3] refactor(boundaries): use the shared is_js_whitespace Co-Authored-By: Claude Opus 5.5 --- .../src/transform/boundaries.rs | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/crates/oxc_angular_compiler/src/transform/boundaries.rs b/crates/oxc_angular_compiler/src/transform/boundaries.rs index 6b53a46c8..cb32c9723 100644 --- a/crates/oxc_angular_compiler/src/transform/boundaries.rs +++ b/crates/oxc_angular_compiler/src/transform/boundaries.rs @@ -12,6 +12,7 @@ use crate::ast::html::HtmlBlockParameter; use crate::ast::r3::R3Variable; use crate::parser::expression::BindingParser; use crate::util::ParseError; +use crate::util::chars::is_js_whitespace; /// An error reported while parsing `@error` block parameters. pub struct BoundaryParamError { @@ -33,22 +34,6 @@ pub struct BoundaryErrorParams<'a> { pub expression_errors: std::vec::Vec, } -/// Matches JavaScript's `\s`, which is also what `String.prototype.trim` strips. Unlike -/// `char::is_whitespace`, it includes U+FEFF and leaves out U+0085. -fn is_js_whitespace(c: char) -> bool { - matches!( - c, - '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}' - ..='\u{200A}' - | '\u{2028}' - | '\u{2029}' - | '\u{202F}' - | '\u{205F}' - | '\u{3000}' - | '\u{FEFF}' - ) -} - /// `String.prototype.trim`. fn js_trim(s: &str) -> &str { s.trim_matches(is_js_whitespace)