Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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),
Expand All @@ -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`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<XrefId, String>) -> Vec<String> {
/// 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<XrefId, String, FxBuildHasher>) -> Vec<String> {
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.
Expand Down Expand Up @@ -471,8 +472,9 @@ struct TempVarTracker {
assigned: FxHashSet<XrefId>,
/// Set of XrefIds that have been released (final read encountered).
released: FxHashSet<XrefId>,
/// Map from XrefId to generated variable name.
defs: FxHashMap<XrefId, String>,
/// Map from XrefId to generated variable name, in the order the names were
/// first assigned (Angular's `defs` Map).
defs: IndexMap<XrefId, String, FxBuildHasher>,
/// Total number of reads per xref (from first pass).
total_reads: FxHashMap<XrefId, usize>,
/// Current read count per xref (incremented during second pass).
Expand All @@ -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(),
}
Expand Down
17 changes: 1 addition & 16 deletions crates/oxc_angular_compiler/src/transform/boundaries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -33,22 +34,6 @@ pub struct BoundaryErrorParams<'a> {
pub expression_errors: std::vec::Vec<ParseError>,
}

/// 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)
Expand Down
55 changes: 52 additions & 3 deletions crates/oxc_angular_compiler/tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand All @@ -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}"
Expand All @@ -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;
Expand All @@ -4165,14 +4180,48 @@ 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 += i + part.len();
}
}

/// 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
Expand Down
Loading