diff --git a/crates/oxc_angular_compiler/src/component/metadata.rs b/crates/oxc_angular_compiler/src/component/metadata.rs index 5912678f2..0555013e7 100644 --- a/crates/oxc_angular_compiler/src/component/metadata.rs +++ b/crates/oxc_angular_compiler/src/component/metadata.rs @@ -113,6 +113,15 @@ impl AngularVersion { self.major > 20 || (self.major == 20 && self.minor >= 2) } + /// Check if a two-way binding rejects a `?.` anywhere on its target (v20.2.0+). + /// + /// Angular v20.2.0-next.3 (#62852) made `hasRecursiveSafeReceiver` part of the check, + /// so `[(x)]="a?.b.c"` is an error. Before, only a target that is itself a safe read + /// (`a?.b`) was. + pub fn rejects_safe_reads_in_two_way_bindings(&self) -> bool { + self.major > 20 || (self.major == 20 && self.minor >= 2) + } + /// Check if `animate.leave` needs `ɵɵAnimationsFeature()` (v20.2.0 to v20.3.0). /// /// In those versions only that feature sets up the registry `ɵɵanimateLeave` diff --git a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs index 3a4d82be5..6a6d42356 100644 --- a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs +++ b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs @@ -90,6 +90,45 @@ fn property_binding_key_span(name: &str, key_span: Span) -> Span { /// The key span of an event named `name` (the identifier `parseAttribute` passes to /// `parseEvent`): a legacy animation event's `@` is not part of it. /// Reference: binding_parser.ts lines 660-667 (`parseEvent`) +/// Angular's error for an event handler with no expression. +const EMPTY_EXPRESSION: &str = "Empty expressions are not allowed"; + +/// Whether a two-way binding can write `$event` back to `ast`: a property or keyed read, also +/// behind `!` or `$any(...)`, with no `?.` on the way to it when `rejects_safe_reads` (v20.2+). +/// Angular's `_isAllowedAssignmentEvent` in `binding_parser.ts`; `this.$any(a)` is not allowed. +fn is_allowed_assignment_event(ast: &AngularExpression<'_>, rejects_safe_reads: bool) -> bool { + match ast { + AngularExpression::NonNullAssert(e) => { + is_allowed_assignment_event(&e.expression, rejects_safe_reads) + } + AngularExpression::Call(call) if call.args.len() == 1 && is_any(&call.receiver) => { + is_allowed_assignment_event(&call.args[0], rejects_safe_reads) + } + AngularExpression::PropertyRead(_) | AngularExpression::KeyedRead(_) => { + !rejects_safe_reads || !has_recursive_safe_receiver(ast) + } + _ => false, + } +} + +/// Whether `ast` is `$any` read from the component, as in `$any(a)`. +fn is_any(ast: &AngularExpression<'_>) -> bool { + matches!(ast, AngularExpression::PropertyRead(read) + if read.name == "$any" && matches!(read.receiver, AngularExpression::ImplicitReceiver(_))) +} + +/// Whether a read goes through `?.` anywhere on its receiver chain (`hasRecursiveSafeReceiver`). +fn has_recursive_safe_receiver(ast: &AngularExpression<'_>) -> bool { + match ast { + AngularExpression::SafePropertyRead(_) | AngularExpression::SafeKeyedRead(_) => true, + AngularExpression::ParenthesizedExpression(e) => has_recursive_safe_receiver(&e.expression), + AngularExpression::PropertyRead(e) => has_recursive_safe_receiver(&e.receiver), + AngularExpression::KeyedRead(e) => has_recursive_safe_receiver(&e.receiver), + AngularExpression::Call(e) => has_recursive_safe_receiver(&e.receiver), + _ => false, + } +} + fn event_key_span(name: &str, key_span: Span) -> Span { if name.starts_with('@') { Span::new(key_span.start + 1, key_span.end) } else { key_span } } @@ -4073,32 +4112,42 @@ impl<'a> HtmlToR3Transform<'a> { ) -> R3BoundEvent<'a> { let handler_span = self.calculate_event_handler_span(attr); let name_atom = Ident::from(self.allocator.alloc_str(name)); + let errors_before = self.errors.len(); // From v20.2 `animate.xChange` is an animation event, as Angular's // `_parseRegularEvent` gives it that type over two-way. Its handler is // the action itself (`return ctx.x`), with no `$event` assignment. - if name.starts_with("animate.") && self.supports_animate() { - let handler = self.parse_event_expression(&attr.value, handler_span); - return R3BoundEvent { - name: name_atom, - event_type: ParsedEventType::Animation, - handler, - target: None, - phase: None, - source_span: attr.span, - handler_span, - key_span, - }; + let is_animation = name.starts_with("animate.") && self.supports_animate(); + let handler = if is_animation { + self.parse_event_expression(&attr.value, handler_span) + } else { + // For two-way binding, the handler is just the target expression (e.g., `name`) + // NOT the full assignment `name = $event`. + // The $event reference and TwoWayBindingSetExpr are created in the ingest phase. + let handler = self.parse_binding_expression(&attr.value, handler_span); + if self.errors.len() == errors_before && matches!(handler, AngularExpression::Empty(_)) + { + self.report_error(EMPTY_EXPRESSION, handler_span); + } + handler + }; + // As Angular's `_parseEvent` for an assignment event, an expression `$event` cannot be + // written to (`a + b`, `a?.b`) is an error, unless parsing reported one already. + let rejects_safe_reads = + self.angular_version.is_none_or(|v| v.rejects_safe_reads_in_two_way_bindings()); + if self.errors.len() == errors_before + && !is_allowed_assignment_event(&handler, rejects_safe_reads) + { + self.report_error("Unsupported expression in a two-way binding", attr.span); } - // For two-way binding, the handler is just the target expression (e.g., `name`) - // NOT the full assignment `name = $event`. - // The $event reference and TwoWayBindingSetExpr are created in the ingest phase. - let handler = self.parse_binding_expression(&attr.value, handler_span); - R3BoundEvent { name: name_atom, - event_type: ParsedEventType::TwoWay, + event_type: if is_animation { + ParsedEventType::Animation + } else { + ParsedEventType::TwoWay + }, handler, target: None, phase: None, @@ -4108,19 +4157,26 @@ impl<'a> HtmlToR3Transform<'a> { } } - /// Parses an event handler expression. + /// Parses an event handler expression. A handler with no expression is an error, as in + /// Angular's `_parseAction`. fn parse_event_expression(&mut self, value: &Ident<'a>, span: Span) -> AngularExpression<'a> { let value_str = value.as_str(); if value_str.is_empty() { + self.report_error(EMPTY_EXPRESSION, span); return self.create_empty_expression(span); } let result = self.binding_parser.parse_event(value_str, span); + let is_empty = + result.errors.is_empty() && matches!(result.ast, AngularExpression::Empty(_)); // Collect any parse errors for error in result.errors { self.errors.push(error); } + if is_empty { + self.report_error(EMPTY_EXPRESSION, span); + } result.ast } diff --git a/crates/oxc_angular_compiler/tests/integration_test.rs b/crates/oxc_angular_compiler/tests/integration_test.rs index 39bfa2315..c21980b7c 100644 --- a/crates/oxc_angular_compiler/tests/integration_test.rs +++ b/crates/oxc_angular_compiler/tests/integration_test.rs @@ -27,6 +27,20 @@ fn compile_template_to_js_with_version( component_name: &str, angular_version: Option, ) -> String { + let (js, errors) = compile_template_to_js_and_errors(template, component_name, angular_version); + if !errors.is_empty() { + panic!("Transform errors: {errors:?}"); + } + js +} + +/// Compiles an Angular template to JavaScript and returns the transform errors with it, for a +/// template Angular rejects that the compiler still emits code for. +fn compile_template_to_js_and_errors( + template: &str, + component_name: &str, + angular_version: Option, +) -> (String, Vec) { use oxc_angular_compiler::pipeline::ingest::{IngestOptions, ingest_component_with_options}; let allocator = Allocator::default(); @@ -49,11 +63,7 @@ fn compile_template_to_js_with_version( ); let r3_result = transformer.transform(&html_result.nodes); - // Check for transform errors - if !r3_result.errors.is_empty() { - let errors: Vec<_> = r3_result.errors.iter().map(|e| e.msg.clone()).collect(); - panic!("Transform errors: {errors:?}"); - } + let errors: Vec<_> = r3_result.errors.iter().map(|e| e.msg.clone()).collect(); // Stage 3: Ingest R3 AST into IR let mut job = if let Some(version) = angular_version { @@ -83,7 +93,7 @@ fn compile_template_to_js_with_version( // Emit the main template function output.push_str(&emit_function(&emitter, &result.template_fn)); - output + (output, errors) } /// Emit a FunctionExpr to JavaScript. @@ -2456,12 +2466,14 @@ fn test_two_way_binding_writeback_target_is_never_optional_v22() { // write-back assignment target. `a?.b = $event` is a JS SyntaxError (an // optional chain is not a legal assignment target), so the LHS of the // `|| (target = value)` clause must stay a plain member access even when the - // bound expression uses safe navigation under Angular v22. - let js = compile_template_to_js_with_version( + // bound expression uses safe navigation under Angular v22. Angular rejects such a + // target since v20.2, and so does the transform, but code is still emitted for it. + let (js, errors) = compile_template_to_js_and_errors( r#""#, "TestComponent", Some(AngularVersion::new(22, 0, 0)), ); + assert_eq!(errors, ["Unsupported expression in a two-way binding"]); // The twoWayBindingSet argument keeps its `?.` (it is only read, never assigned)... assert!(js.contains("ɵɵtwoWayBindingSet(ctx.a?.b"), "read side should keep `?.`, got:\n{js}"); // ...but the write-back assignment target must be a plain, assignable read. @@ -2472,6 +2484,24 @@ fn test_two_way_binding_writeback_target_is_never_optional_v22() { ); } +#[test] +fn test_two_way_binding_with_a_safe_read_in_its_target_before_v20_2() { + // Before v20.2 (#62852) Angular only rejects a target that is itself a safe read. + let v20_1 = Some(AngularVersion::new(20, 1, 0)); + let (_, errors) = + compile_template_to_js_and_errors(r#""#, "TestComponent", v20_1); + assert!(errors.is_empty(), "{errors:?}"); + let (_, errors) = + compile_template_to_js_and_errors(r#""#, "TestComponent", v20_1); + assert_eq!(errors, ["Unsupported expression in a two-way binding"]); + let (_, errors) = compile_template_to_js_and_errors( + r#""#, + "TestComponent", + Some(AngularVersion::new(20, 2, 0)), + ); + assert_eq!(errors, ["Unsupported expression in a two-way binding"]); +} + #[test] fn test_safe_navigation_migration_ignores_qualified_call() { // Only the *unqualified* `$safeNavigationMigration(...)` helper is magic. A diff --git a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs index e796a7d0a..cb035b44b 100644 --- a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs +++ b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs @@ -1013,6 +1013,80 @@ mod events { vec![h!["Element", "div"], h!["BoundEvent", 0, "event", "", "v"]] ); } + #[test] + fn should_report_an_event_binding_with_no_expression() { + // Angular's `_parseAction`: "Empty expressions are not allowed". + for html in [ + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#"
"#, + r#""#, + r#""#, + ] { + assert_eq!( + get_transform_errors(html), + vec!["Empty expressions are not allowed".to_string()], + "{html}" + ); + } + } + + #[test] + fn should_report_a_two_way_binding_that_cannot_be_written_to() { + // Angular's `_isAllowedAssignmentEvent`: the expressions ngc 22.2.2 rejects. + for expr in [ + "a + b", + "a?.b", + "a?.b.c", + "a?.[0]", + "(a?.b).c", + "a()", + "a.b()", + "$any(a, b)", + "$any(a + b)", + "this.$any(a)", + "!a", + "(a)", + ] { + for html in + [format!(r#""#), format!(r#""#)] + { + assert_eq!( + get_transform_errors(&html), + vec!["Unsupported expression in a two-way binding".to_string()], + "{html}" + ); + } + } + assert_eq!( + get_transform_errors(r#""#), + vec!["Unsupported expression in a two-way binding".to_string()], + "an animation binding is checked too" + ); + } + + #[test] + fn should_accept_a_two_way_binding_that_can_be_written_to() { + for expr in ["a", "a.b", "a[0]", "a!", "a.b!", "$any(a)", "$any(a.b)", "(a).b"] { + let html = format!(r#""#); + assert!( + get_transform_errors(&html).is_empty(), + "{html}: {:?}", + get_transform_errors(&html) + ); + } + } + + #[test] + fn should_report_only_the_parse_error_of_a_two_way_binding_that_fails_to_parse() { + // `isValid` in Angular's `_parseEvent`: no second error on top of a parse error. + let errors = get_transform_errors(r#""#); + assert!(!errors.is_empty()); + assert!(!errors.iter().any(|e| e.contains("two-way")), "{errors:?}"); + } } // ============================================================================