From c17731fc9a523accc4de3423877542fd4299e26a Mon Sep 17 00:00:00 2001 From: naoki <0512.naoki.job@gmail.com> Date: Wed, 25 Nov 2026 21:33:19 +0900 Subject: [PATCH 1/4] fix(parser): preserve regex literals ending in an escaped slash --- crates/angular_conformance/README.md | 2 +- .../snapshots/angular.snap.md | 20 +- .../src/subsystems/ast_spans.rs | 209 +++++++----------- .../src/parser/expression/mod.rs | 25 +-- .../src/parser/expression/parser.rs | 44 +--- .../src/transform/html_to_r3.rs | 27 +-- .../tests/r3_template_transform_test.rs | 23 ++ 7 files changed, 129 insertions(+), 221 deletions(-) diff --git a/crates/angular_conformance/README.md b/crates/angular_conformance/README.md index d44d7d17c2..295bd347f9 100644 --- a/crates/angular_conformance/README.md +++ b/crates/angular_conformance/README.md @@ -4,7 +4,7 @@ A conformance testing framework that validates the oxc Angular compiler implemen ## Overview -This crate extracts test cases from Angular's TypeScript spec files and runs them against the Rust implementation to ensure compatibility. It currently passes **1,430** of **1,456** extracted test assertions (the rest cover other new 22.3 features not yet ported) against Angular **v22.3.0-next.4**. +This crate extracts test cases from Angular's TypeScript spec files and runs them against the Rust implementation to ensure compatibility. It currently passes **1,432** of **1,456** extracted test assertions (the rest cover other new 22.3 features not yet ported) against Angular **v22.3.0-next.4**. ## Architecture diff --git a/crates/angular_conformance/snapshots/angular.snap.md b/crates/angular_conformance/snapshots/angular.snap.md index 812e9a9916..c3a1c91bf1 100644 --- a/crates/angular_conformance/snapshots/angular.snap.md +++ b/crates/angular_conformance/snapshots/angular.snap.md @@ -7,7 +7,7 @@ | ast_serializer | 6 | 0 | 0 | 0 | 6 | 100.0% | | ast_spans | 55 | 0 | 0 | 0 | 55 | 100.0% | | expression_lexer | 154 | 0 | 0 | 0 | 154 | 100.0% | -| expression_parser | 390 | 10 | 3 | 0 | 403 | 96.8% | +| expression_parser | 392 | 10 | 1 | 0 | 403 | 97.3% | | expression_serializer | 44 | 0 | 0 | 0 | 44 | 100.0% | | html_lexer | 291 | 6 | 0 | 0 | 297 | 98.0% | | html_parser | 89 | 1 | 0 | 0 | 90 | 98.9% | @@ -15,7 +15,7 @@ | r3_transform | 180 | 4 | 0 | 0 | 184 | 97.8% | | shadow_css | 185 | 2 | 0 | 0 | 187 | 98.9% | | style_parser | 15 | 0 | 0 | 0 | 15 | 100.0% | -| **Total** | **1430** | **23** | **3** | **0** | **1456** | **98.2%** | +| **Total** | **1432** | **23** | **1** | **0** | **1456** | **98.4%** | ## Failed Tests @@ -159,22 +159,6 @@ Error containing: Unterminated template literal No errors ``` -#### should parse a regular expression literal that ends with an escaped slash: CheckBinding { input: "/^https?:\\/\\//", expected: None } -Path: `parser/parseAction/regular expression literals/should parse a regular expression literal that ends with an escaped slash` - -**Error:** -``` -Unexpected parse errors: ["Lexer Error: Unterminated regular expression at column 12 in expression [/^https?:\\/\\]", "Unexpected token 'Lexer Error: Unterminated regular expression at column 12 in expression [/^https?:\\/\\]' at column 13 in [/^https?:\\/\\//]"] -``` - -#### should parse a regular expression literal that ends with an escaped slash: CheckBinding { input: "url.replace(/^\\//, \"\") //comment", expected: Some("url.replace(/^\\//, \"\")") } -Path: `parser/parseAction/regular expression literals/should parse a regular expression literal that ends with an escaped slash` - -**Error:** -``` -Unexpected parse errors: ["Lexer Error: Unterminated regular expression at column 15 in expression [url.replace(/^\\]", "Missing expected ) at column 16"] -``` - ### html_lexer #### should parse a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.EOF")]], options: None } diff --git a/crates/angular_conformance/src/subsystems/ast_spans.rs b/crates/angular_conformance/src/subsystems/ast_spans.rs index 31677fe45b..08edf248ce 100644 --- a/crates/angular_conformance/src/subsystems/ast_spans.rs +++ b/crates/angular_conformance/src/subsystems/ast_spans.rs @@ -1,7 +1,5 @@ use oxc_allocator::Allocator; -use oxc_angular_compiler::ast::expression::{ - AbsoluteSourceSpan, AngularExpression, BinaryOperator, -}; +use oxc_angular_compiler::ast::expression::{AngularExpression, BinaryOperator}; use oxc_angular_compiler::ast::r3::{ R3BoundText, R3BoundaryErrorBlock, R3DeferredBlock, R3Element, R3ForLoopBlock, R3IfBlock, R3SwitchBlock, R3Template, R3TemplateAttr, R3Visitor, visit_all, @@ -174,19 +172,32 @@ impl<'a> ExpressionSourceCollector<'a> { } } - /// Extract source text from an absolute span - fn extract_source(&self, span: AbsoluteSourceSpan) -> Option { - let start = span.start as usize; - let end = span.end as usize; - if start <= end && end <= self.source.len() { - Some(self.source[start..end].to_string()) + fn record_expression(&mut self, expr: &AngularExpression<'_>) { + self.sources.push(vec![unparse_expression(expr)]); + } + + fn record_source(&mut self, expr: &AngularExpression<'_>) { + if let Some(source) = self.extract_expression_source(expr) { + self.sources.push(vec![source]); + } + } + + // Event expressions are parsed from decoded attribute values, so their offsets + // cannot be used to slice the original HTML when it contains character references. + fn visit_event_handler(&mut self, handler: &AngularExpression<'_>) { + if self.extract_sub_expressions { + self.collect_sub_expressions(handler, Self::record_expression); } else { - None + self.record_expression(handler); } } /// Collect sub-expressions from an expression based on its type - fn collect_sub_expressions(&mut self, expr: &AngularExpression<'_>) { + fn collect_sub_expressions( + &mut self, + expr: &AngularExpression<'_>, + record: fn(&mut Self, &AngularExpression<'_>), + ) { match expr { // Binary: for assignments, only collect from right side; for others, both sides AngularExpression::Binary(bin) => { @@ -194,169 +205,120 @@ impl<'a> ExpressionSourceCollector<'a> { // For assignment expressions (property write), only collect the value (right side) // unless left is a keyed expression which has interesting sub-expressions if let AngularExpression::KeyedRead(_) = &bin.left { - self.collect_sub_expressions(&bin.left); + self.collect_sub_expressions(&bin.left, record); } - self.collect_sub_expressions(&bin.right); + self.collect_sub_expressions(&bin.right, record); } else { // For other binary operators, collect from both sides - self.collect_sub_expressions(&bin.left); - self.collect_sub_expressions(&bin.right); + self.collect_sub_expressions(&bin.left, record); + self.collect_sub_expressions(&bin.right, record); } } // Conditional: collect condition, true, and false expressions AngularExpression::Conditional(cond) => { - if let Some(s) = self.extract_source(cond.condition.source_span()) { - self.sources.push(vec![s]); - } - if let Some(s) = self.extract_source(cond.true_exp.source_span()) { - self.sources.push(vec![s]); - } - if let Some(s) = self.extract_source(cond.false_exp.source_span()) { - self.sources.push(vec![s]); - } + record(self, &cond.condition); + record(self, &cond.true_exp); + record(self, &cond.false_exp); } // Chain: collect each expression in the chain AngularExpression::Chain(chain) => { for child in &chain.expressions { - if let Some(s) = self.extract_source(child.source_span()) { - self.sources.push(vec![s]); - } + record(self, child); } } // PropertyRead: output the receiver's source or recurse to find ImplicitReceiver AngularExpression::PropertyRead(prop) => { if self.find_implicit_receiver { // Recurse to find ImplicitReceiver and output its (empty) span - self.collect_sub_expressions(&prop.receiver); + self.collect_sub_expressions(&prop.receiver, record); } else { - // Output the receiver's span directly - match &prop.receiver { - AngularExpression::ImplicitReceiver(_) => { - // For ImplicitReceiver, output empty string - self.sources.push(vec![String::new()]); - } - receiver => { - if let Some(s) = self.extract_source(receiver.source_span()) { - self.sources.push(vec![s]); - } - } + if matches!(&prop.receiver, AngularExpression::ImplicitReceiver(_)) { + self.sources.push(vec![String::new()]); + } else { + record(self, &prop.receiver); } } } // SafePropertyRead: output the receiver's source (for safe method call tests) AngularExpression::SafePropertyRead(prop) => { - if let Some(s) = self.extract_source(prop.receiver.source_span()) { - self.sources.push(vec![s]); - } + record(self, &prop.receiver); } // KeyedRead: collect the key AngularExpression::KeyedRead(keyed) => { - if let Some(s) = self.extract_source(keyed.key.source_span()) { - self.sources.push(vec![s]); - } + record(self, &keyed.key); } // SafeKeyedRead: collect the key AngularExpression::SafeKeyedRead(keyed) => { - if let Some(s) = self.extract_source(keyed.key.source_span()) { - self.sources.push(vec![s]); - } + record(self, &keyed.key); } // Call: collect from SafePropertyRead receiver (for safe method calls), then arguments AngularExpression::Call(call) => { // For safe method calls like prop?.safe(), collect from SafePropertyRead receiver - if let AngularExpression::SafePropertyRead(safe_prop) = &call.receiver - && let Some(s) = self.extract_source(safe_prop.receiver.source_span()) - { - self.sources.push(vec![s]); + if let AngularExpression::SafePropertyRead(safe_prop) = &call.receiver { + record(self, &safe_prop.receiver); } // Collect arguments for arg in &call.args { - if let Some(s) = self.extract_source(arg.source_span()) { - self.sources.push(vec![s]); - } + record(self, arg); } } // SafeCall: collect receiver (for safe method calls) AngularExpression::SafeCall(call) => { // First collect the receiver - if let Some(s) = self.extract_source(call.receiver.source_span()) { - self.sources.push(vec![s]); - } + record(self, &call.receiver); // Then collect arguments for arg in &call.args { - if let Some(s) = self.extract_source(arg.source_span()) { - self.sources.push(vec![s]); - } + record(self, arg); } } // LiteralArray: collect elements AngularExpression::LiteralArray(arr) => { for elem in &arr.expressions { - if let Some(s) = self.extract_source(elem.source_span()) { - self.sources.push(vec![s]); - } + record(self, elem); } } // LiteralMap: collect values AngularExpression::LiteralMap(map) => { for value in &map.values { - if let Some(s) = self.extract_source(value.source_span()) { - self.sources.push(vec![s]); - } + record(self, value); } } // PrefixNot: collect the operand AngularExpression::PrefixNot(not) => { - if let Some(s) = self.extract_source(not.expression.source_span()) { - self.sources.push(vec![s]); - } + record(self, ¬.expression); } // Unary: collect the operand AngularExpression::Unary(unary) => { - if let Some(s) = self.extract_source(unary.expr.source_span()) { - self.sources.push(vec![s]); - } + record(self, &unary.expr); } // NonNullAssert: collect the expression AngularExpression::NonNullAssert(nna) => { - if let Some(s) = self.extract_source(nna.expression.source_span()) { - self.sources.push(vec![s]); - } + record(self, &nna.expression); } // BindingPipe: collect the input expression AngularExpression::BindingPipe(pipe) => { - if let Some(s) = self.extract_source(pipe.exp.source_span()) { - self.sources.push(vec![s]); - } + record(self, &pipe.exp); } // Interpolation: recursively collect from each expression AngularExpression::Interpolation(interp) => { for expr in &interp.expressions { - self.collect_sub_expressions(expr); + self.collect_sub_expressions(expr, record); } } // LiteralPrimitive: output the value (for binary operands, array elements, etc.) - AngularExpression::LiteralPrimitive(lit) => { - if let Some(s) = self.extract_source(lit.source_span) { - self.sources.push(vec![s]); - } - } + AngularExpression::LiteralPrimitive(_) => record(self, expr), // Empty expression or ImplicitReceiver: output empty string AngularExpression::Empty(_) | AngularExpression::ImplicitReceiver(_) => { self.sources.push(vec![String::new()]); } // SpreadElement: collect the expression being spread AngularExpression::SpreadElement(spread) => { - if let Some(s) = self.extract_source(spread.expression.source_span()) { - self.sources.push(vec![s]); - } + record(self, &spread.expression); } // ArrowFunction: collect the body and parameter spans AngularExpression::ArrowFunction(arrow) => { // Collect the body expression - if let Some(s) = self.extract_source(arrow.body.source_span()) { - self.sources.push(vec![s]); - } + record(self, &arrow.body); } // Terminal expressions - no sub-expressions to extract AngularExpression::ThisReceiver(_) @@ -372,12 +334,11 @@ impl<'a> ExpressionSourceCollector<'a> { /// Process an expression - either extract the whole thing or its sub-expressions fn process_expression(&mut self, expr: &AngularExpression<'_>) { if self.extract_sub_expressions { - self.collect_sub_expressions(expr); + self.collect_sub_expressions(expr, Self::record_source); } else if self.use_unparser { - let unparsed = unparse_expression(expr); - self.sources.push(vec![unparsed]); - } else if let Some(source) = self.extract_expression_source(expr) { - self.sources.push(vec![source]); + self.record_expression(expr); + } else { + self.record_source(expr); } } } @@ -420,7 +381,7 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { self.process_expression(expr); } } else if self.extract_sub_expressions { - self.collect_sub_expressions(&attr.value); + self.collect_sub_expressions(&attr.value, Self::record_source); } else if let Some(ref value_span) = attr.value_span { let start = value_span.start as usize; let end = value_span.end as usize; @@ -431,19 +392,7 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { } // Visit bound outputs (events) for event in &element.outputs { - if self.extract_sub_expressions { - self.collect_sub_expressions(&event.handler); - } else if self.use_unparser { - // Use unparser for proper formatting (e.g., "foo(); bar();" with space after semicolon) - let unparsed = unparse_expression(&event.handler); - self.sources.push(vec![unparsed]); - } else { - let start = event.handler_span.start as usize; - let end = event.handler_span.end as usize; - if end <= self.source.len() { - self.sources.push(vec![self.source[start..end].to_string()]); - } - } + self.visit_event_handler(&event.handler); } } // Visit children @@ -466,7 +415,7 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { self.process_expression(expr); } } else if self.extract_sub_expressions { - self.collect_sub_expressions(&attr.value); + self.collect_sub_expressions(&attr.value, Self::record_source); } else if let Some(ref value_span) = attr.value_span { let start = value_span.start as usize; let end = value_span.end as usize; @@ -483,19 +432,7 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { } // Visit bound outputs for event in &template.outputs { - if self.extract_sub_expressions { - self.collect_sub_expressions(&event.handler); - } else if self.use_unparser { - // Use unparser for proper formatting - let unparsed = unparse_expression(&event.handler); - self.sources.push(vec![unparsed]); - } else { - let start = event.handler_span.start as usize; - let end = event.handler_span.end as usize; - if end <= self.source.len() { - self.sources.push(vec![self.source[start..end].to_string()]); - } - } + self.visit_event_handler(&event.handler); } // Visit children visit_all(self, &template.children); @@ -545,3 +482,27 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { } } } + +#[cfg(test)] +mod tests { + use super::AstSpansRunner; + + #[test] + fn event_expression_text_uses_decoded_attribute_values() { + for tag in ["button", "ng-template"] { + let html = format!(r#"<{tag} (click)="save("x") // tail">"#); + for (sub_expressions, expected) in [(false, r#"save("x")"#), (true, r#""x""#)] { + let texts = AstSpansRunner::new().extract_expression_sources( + &html, + None, + sub_expressions, + false, + false, + false, + false, + ); + assert_eq!(texts, [vec![expected]], "{html}"); + } + } + } +} diff --git a/crates/oxc_angular_compiler/src/parser/expression/mod.rs b/crates/oxc_angular_compiler/src/parser/expression/mod.rs index f7d65587b7..3e21204683 100644 --- a/crates/oxc_angular_compiler/src/parser/expression/mod.rs +++ b/crates/oxc_angular_compiler/src/parser/expression/mod.rs @@ -52,20 +52,17 @@ pub fn find_comment_start(input: &str) -> Option { let bytes = input.as_bytes(); let mut outer_quote: Option = None; - for i in 0..bytes.len().saturating_sub(1) { - let ch = bytes[i]; - let next_ch = bytes[i + 1]; - - // Check for // outside of quotes - if ch == b'/' && next_ch == b'/' && outer_quote.is_none() { - return Some(i); - } - - // Track quote state - if outer_quote == Some(ch) { - outer_quote = None; - } else if outer_quote.is_none() && (ch == b'\'' || ch == b'"' || ch == b'`') { - outer_quote = Some(ch); + let mut chars = bytes.iter().copied().enumerate(); + while let Some((i, ch)) = chars.next() { + match ch { + // Angular's _commentStart skips escaped slashes and quotes alike. + b'\\' => { + chars.next(); + } + b'/' if outer_quote.is_none() && bytes.get(i + 1) == Some(&b'/') => return Some(i), + _ if outer_quote == Some(ch) => outer_quote = None, + b'\'' | b'"' | b'`' if outer_quote.is_none() => outer_quote = Some(ch), + _ => {} } } diff --git a/crates/oxc_angular_compiler/src/parser/expression/parser.rs b/crates/oxc_angular_compiler/src/parser/expression/parser.rs index 8b093708af..7b5aa10f20 100644 --- a/crates/oxc_angular_compiler/src/parser/expression/parser.rs +++ b/crates/oxc_angular_compiler/src/parser/expression/parser.rs @@ -20,8 +20,8 @@ use crate::ast::expression::{ }; use crate::util::ParseError; -use super::TemplateBindingParseResult; use super::lexer::{Lexer, Token}; +use super::{TemplateBindingParseResult, strip_comments}; /// Angular's error for an interpolation with a blank expression (`{{ }}`), raised by /// `splitInterpolation`; `column` is the offset of the `{{` in `input`. @@ -117,7 +117,7 @@ impl<'a> Parser<'a> { pub fn new(allocator: &'a Allocator, source: &'a str) -> Self { // Strip comments from the source before tokenizing. The stripped source is a prefix // of `source`, so it is borrowed rather than copied. - let lexer = Lexer::new(allocator, Self::strip_comments(source)); + let lexer = Lexer::new(allocator, strip_comments(source).stripped); let tokens = lexer.tokenize(); // Collect error tokens from the lexer @@ -171,43 +171,6 @@ impl<'a> Parser<'a> { } } - /// Strips single-line comments (`//`) from the input. - /// - /// Comments are only recognized outside of quoted strings. - /// This matches Angular's behavior in `_stripComments`. - fn strip_comments(input: &str) -> &str { - match Self::find_comment_start(input) { - Some(idx) => &input[..idx], - None => input, - } - } - - /// Finds the start index of a `//` comment, respecting quoted strings. - /// - /// Returns `None` if no comment is found. - fn find_comment_start(input: &str) -> Option { - let bytes = input.as_bytes(); - let mut outer_quote: Option = None; - - for i in 0..input.len().saturating_sub(1) { - let ch = bytes[i]; - let next_ch = bytes[i + 1]; - - // Check for // outside of quotes - if ch == b'/' && next_ch == b'/' && outer_quote.is_none() { - return Some(i); - } - - // Track quote state - if outer_quote == Some(ch) { - outer_quote = None; - } else if outer_quote.is_none() && (ch == b'\'' || ch == b'"' || ch == b'`') { - outer_quote = Some(ch); - } - } - None - } - /// Checks for interpolation syntax (`{{` and `}}`) in the input. /// /// If found, adds an error: "Got interpolation ({{}}) where expression was expected". @@ -1857,7 +1820,6 @@ impl<'a> Parser<'a> { if self.is_assignment_operator(token) { // Clone the operation first to avoid borrow issues let operation = token.str_value.clone(); - let result_span = result.span(); // In binding mode, still parse the full expression but emit an error // This ensures spans cover the entire expression @@ -1878,7 +1840,7 @@ impl<'a> Parser<'a> { // Create Binary expression for assignment let end = self.current_end_index(); - let assign_span = ParseSpan::new(result_span.start, end); + let assign_span = ParseSpan::new(start, end); let assign_source_span = assign_span.to_absolute(self.absolute_offset); let binary_op = self.string_to_binary_operator(&operation); let binary = Binary { 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 c21d81ddc6..b4cca8b6b3 100644 --- a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs +++ b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs @@ -28,7 +28,7 @@ use crate::ast::r3::{ }; use crate::i18n::parser::I18nMessageFactory; use crate::i18n::placeholder::PlaceholderRegistry; -use crate::parser::expression::{BindingParser, blank_interpolation_error, find_comment_start}; +use crate::parser::expression::{BindingParser, blank_interpolation_error}; use crate::parser::html::{decode_entities_in_string, get_html_tag_definition, split_ns_name}; use crate::schema::{ element_security_context_for, is_known_element, is_trusted_types_sink_at, @@ -4066,7 +4066,7 @@ impl<'a> HtmlToR3Transform<'a> { attr: &HtmlAttribute<'a>, key_span: Span, ) -> R3BoundEvent<'a> { - let handler_span = self.calculate_event_handler_span(attr); + let handler_span = attr.value_span.unwrap_or(attr.span); let handler = self.parse_event_expression(&attr.value, handler_span); // Check for animation events (animate.xxx) @@ -4146,7 +4146,7 @@ impl<'a> HtmlToR3Transform<'a> { attr: &HtmlAttribute<'a>, key_span: Span, ) -> R3BoundEvent<'a> { - let handler_span = self.calculate_event_handler_span(attr); + let handler_span = attr.value_span.unwrap_or(attr.span); // Angular parses the handler first, so its errors come before the name errors. let handler = self.parse_event_expression(&attr.value, handler_span); @@ -4203,7 +4203,7 @@ impl<'a> HtmlToR3Transform<'a> { if let Some(anim_name) = name.strip_prefix('@') { return self.create_legacy_animation_event(anim_name, attr, key_span); } - let handler_span = self.calculate_event_handler_span(attr); + let handler_span = attr.value_span.unwrap_or(attr.span); let name_atom = Ident::from(self.allocator.alloc_str(name)); let errors_before = self.errors.len(); @@ -4261,25 +4261,6 @@ impl<'a> HtmlToR3Transform<'a> { result.ast } - /// Calculates the handler span for an event binding, adjusting for comments. - /// - /// Angular strips `//` comments from action bindings before parsing. - /// The handler span should exclude the comment portion and trailing whitespace. - fn calculate_event_handler_span(&self, attr: &HtmlAttribute<'a>) -> Span { - let base_span = attr.value_span.unwrap_or(attr.span); - let value_str = attr.value.as_str(); - - // Check if there's a comment to strip - if let Some(comment_pos) = find_comment_start(value_str) { - // Get the portion before the comment and trim trailing whitespace - let before_comment = &value_str[..comment_pos]; - let trimmed_len = before_comment.trim_end().len(); - Span::new(base_span.start, base_span.start + trimmed_len as u32) - } else { - base_span - } - } - /// Creates a variable with validation. /// Returns None if validation fails (error is reported). fn create_validated_variable( 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 68a02bb616..bb030bc27b 100644 --- a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs +++ b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs @@ -1010,6 +1010,29 @@ mod bound_attributes { mod events { use super::*; + #[test] + fn event_handler_span_includes_regex_ending_with_escaped_slash() { + for (handler, expression) in [ + (r"url.replace(/^\//, '')", r"url.replace(/^\//, '')"), + (r"url.replace(/^\//, '') //comment", r"url.replace(/^\//, '')"), + ("result = save("x") //comment", r#"result = save("x")"#), + ] { + let html = format!(r#""#); + let allocator = Allocator::default(); + let parsed = HtmlParser::new(&allocator, &html, "test.html").parse(); + let result = HtmlToR3Transform::new(&allocator, &html, TransformOptions::default()) + .transform(&parsed.nodes); + let R3Node::Element(button) = &result.nodes[0] else { panic!("expected button") }; + let event = &button.outputs[0]; + let start = html.find(handler).unwrap() as u32; + let attr_span = event.handler_span; + let expr_span = event.handler.source_span(); + assert_eq!((attr_span.start, attr_span.end), (start, start + handler.len() as u32)); + assert_eq!((expr_span.start, expr_span.end), (start, start + expression.len() as u32)); + assert!(result.errors.is_empty(), "{:?}", result.errors); + } + } + #[test] fn should_parse_event_bindings() { // TS: expectFromHtml('
') From fc5472b362b4df1e547c4dbad3a35df317f0df4b Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 22:15:22 +0800 Subject: [PATCH 2/4] test(conformance): keep checking event handler spans Cut the expected text out of the source by the parsed handler's own span instead of by handler_span. handler_span is now the whole attribute value (comment included, like Angular), while the spec expects the parsed expression. Unparsing the handler instead would pass even if every event span were wrong. Co-Authored-By: Claude Opus 5.5 --- .../src/subsystems/ast_spans.rs | 201 ++++++++++-------- 1 file changed, 116 insertions(+), 85 deletions(-) diff --git a/crates/angular_conformance/src/subsystems/ast_spans.rs b/crates/angular_conformance/src/subsystems/ast_spans.rs index 08edf248ce..34007a0375 100644 --- a/crates/angular_conformance/src/subsystems/ast_spans.rs +++ b/crates/angular_conformance/src/subsystems/ast_spans.rs @@ -1,5 +1,7 @@ use oxc_allocator::Allocator; -use oxc_angular_compiler::ast::expression::{AngularExpression, BinaryOperator}; +use oxc_angular_compiler::ast::expression::{ + AbsoluteSourceSpan, AngularExpression, BinaryOperator, +}; use oxc_angular_compiler::ast::r3::{ R3BoundText, R3BoundaryErrorBlock, R3DeferredBlock, R3Element, R3ForLoopBlock, R3IfBlock, R3SwitchBlock, R3Template, R3TemplateAttr, R3Visitor, visit_all, @@ -172,32 +174,19 @@ impl<'a> ExpressionSourceCollector<'a> { } } - fn record_expression(&mut self, expr: &AngularExpression<'_>) { - self.sources.push(vec![unparse_expression(expr)]); - } - - fn record_source(&mut self, expr: &AngularExpression<'_>) { - if let Some(source) = self.extract_expression_source(expr) { - self.sources.push(vec![source]); - } - } - - // Event expressions are parsed from decoded attribute values, so their offsets - // cannot be used to slice the original HTML when it contains character references. - fn visit_event_handler(&mut self, handler: &AngularExpression<'_>) { - if self.extract_sub_expressions { - self.collect_sub_expressions(handler, Self::record_expression); + /// Extract source text from an absolute span + fn extract_source(&self, span: AbsoluteSourceSpan) -> Option { + let start = span.start as usize; + let end = span.end as usize; + if start <= end && end <= self.source.len() { + Some(self.source[start..end].to_string()) } else { - self.record_expression(handler); + None } } /// Collect sub-expressions from an expression based on its type - fn collect_sub_expressions( - &mut self, - expr: &AngularExpression<'_>, - record: fn(&mut Self, &AngularExpression<'_>), - ) { + fn collect_sub_expressions(&mut self, expr: &AngularExpression<'_>) { match expr { // Binary: for assignments, only collect from right side; for others, both sides AngularExpression::Binary(bin) => { @@ -205,120 +194,169 @@ impl<'a> ExpressionSourceCollector<'a> { // For assignment expressions (property write), only collect the value (right side) // unless left is a keyed expression which has interesting sub-expressions if let AngularExpression::KeyedRead(_) = &bin.left { - self.collect_sub_expressions(&bin.left, record); + self.collect_sub_expressions(&bin.left); } - self.collect_sub_expressions(&bin.right, record); + self.collect_sub_expressions(&bin.right); } else { // For other binary operators, collect from both sides - self.collect_sub_expressions(&bin.left, record); - self.collect_sub_expressions(&bin.right, record); + self.collect_sub_expressions(&bin.left); + self.collect_sub_expressions(&bin.right); } } // Conditional: collect condition, true, and false expressions AngularExpression::Conditional(cond) => { - record(self, &cond.condition); - record(self, &cond.true_exp); - record(self, &cond.false_exp); + if let Some(s) = self.extract_source(cond.condition.source_span()) { + self.sources.push(vec![s]); + } + if let Some(s) = self.extract_source(cond.true_exp.source_span()) { + self.sources.push(vec![s]); + } + if let Some(s) = self.extract_source(cond.false_exp.source_span()) { + self.sources.push(vec![s]); + } } // Chain: collect each expression in the chain AngularExpression::Chain(chain) => { for child in &chain.expressions { - record(self, child); + if let Some(s) = self.extract_source(child.source_span()) { + self.sources.push(vec![s]); + } } } // PropertyRead: output the receiver's source or recurse to find ImplicitReceiver AngularExpression::PropertyRead(prop) => { if self.find_implicit_receiver { // Recurse to find ImplicitReceiver and output its (empty) span - self.collect_sub_expressions(&prop.receiver, record); + self.collect_sub_expressions(&prop.receiver); } else { - if matches!(&prop.receiver, AngularExpression::ImplicitReceiver(_)) { - self.sources.push(vec![String::new()]); - } else { - record(self, &prop.receiver); + // Output the receiver's span directly + match &prop.receiver { + AngularExpression::ImplicitReceiver(_) => { + // For ImplicitReceiver, output empty string + self.sources.push(vec![String::new()]); + } + receiver => { + if let Some(s) = self.extract_source(receiver.source_span()) { + self.sources.push(vec![s]); + } + } } } } // SafePropertyRead: output the receiver's source (for safe method call tests) AngularExpression::SafePropertyRead(prop) => { - record(self, &prop.receiver); + if let Some(s) = self.extract_source(prop.receiver.source_span()) { + self.sources.push(vec![s]); + } } // KeyedRead: collect the key AngularExpression::KeyedRead(keyed) => { - record(self, &keyed.key); + if let Some(s) = self.extract_source(keyed.key.source_span()) { + self.sources.push(vec![s]); + } } // SafeKeyedRead: collect the key AngularExpression::SafeKeyedRead(keyed) => { - record(self, &keyed.key); + if let Some(s) = self.extract_source(keyed.key.source_span()) { + self.sources.push(vec![s]); + } } // Call: collect from SafePropertyRead receiver (for safe method calls), then arguments AngularExpression::Call(call) => { // For safe method calls like prop?.safe(), collect from SafePropertyRead receiver - if let AngularExpression::SafePropertyRead(safe_prop) = &call.receiver { - record(self, &safe_prop.receiver); + if let AngularExpression::SafePropertyRead(safe_prop) = &call.receiver + && let Some(s) = self.extract_source(safe_prop.receiver.source_span()) + { + self.sources.push(vec![s]); } // Collect arguments for arg in &call.args { - record(self, arg); + if let Some(s) = self.extract_source(arg.source_span()) { + self.sources.push(vec![s]); + } } } // SafeCall: collect receiver (for safe method calls) AngularExpression::SafeCall(call) => { // First collect the receiver - record(self, &call.receiver); + if let Some(s) = self.extract_source(call.receiver.source_span()) { + self.sources.push(vec![s]); + } // Then collect arguments for arg in &call.args { - record(self, arg); + if let Some(s) = self.extract_source(arg.source_span()) { + self.sources.push(vec![s]); + } } } // LiteralArray: collect elements AngularExpression::LiteralArray(arr) => { for elem in &arr.expressions { - record(self, elem); + if let Some(s) = self.extract_source(elem.source_span()) { + self.sources.push(vec![s]); + } } } // LiteralMap: collect values AngularExpression::LiteralMap(map) => { for value in &map.values { - record(self, value); + if let Some(s) = self.extract_source(value.source_span()) { + self.sources.push(vec![s]); + } } } // PrefixNot: collect the operand AngularExpression::PrefixNot(not) => { - record(self, ¬.expression); + if let Some(s) = self.extract_source(not.expression.source_span()) { + self.sources.push(vec![s]); + } } // Unary: collect the operand AngularExpression::Unary(unary) => { - record(self, &unary.expr); + if let Some(s) = self.extract_source(unary.expr.source_span()) { + self.sources.push(vec![s]); + } } // NonNullAssert: collect the expression AngularExpression::NonNullAssert(nna) => { - record(self, &nna.expression); + if let Some(s) = self.extract_source(nna.expression.source_span()) { + self.sources.push(vec![s]); + } } // BindingPipe: collect the input expression AngularExpression::BindingPipe(pipe) => { - record(self, &pipe.exp); + if let Some(s) = self.extract_source(pipe.exp.source_span()) { + self.sources.push(vec![s]); + } } // Interpolation: recursively collect from each expression AngularExpression::Interpolation(interp) => { for expr in &interp.expressions { - self.collect_sub_expressions(expr, record); + self.collect_sub_expressions(expr); } } // LiteralPrimitive: output the value (for binary operands, array elements, etc.) - AngularExpression::LiteralPrimitive(_) => record(self, expr), + AngularExpression::LiteralPrimitive(lit) => { + if let Some(s) = self.extract_source(lit.source_span) { + self.sources.push(vec![s]); + } + } // Empty expression or ImplicitReceiver: output empty string AngularExpression::Empty(_) | AngularExpression::ImplicitReceiver(_) => { self.sources.push(vec![String::new()]); } // SpreadElement: collect the expression being spread AngularExpression::SpreadElement(spread) => { - record(self, &spread.expression); + if let Some(s) = self.extract_source(spread.expression.source_span()) { + self.sources.push(vec![s]); + } } // ArrowFunction: collect the body and parameter spans AngularExpression::ArrowFunction(arrow) => { // Collect the body expression - record(self, &arrow.body); + if let Some(s) = self.extract_source(arrow.body.source_span()) { + self.sources.push(vec![s]); + } } // Terminal expressions - no sub-expressions to extract AngularExpression::ThisReceiver(_) @@ -334,11 +372,12 @@ impl<'a> ExpressionSourceCollector<'a> { /// Process an expression - either extract the whole thing or its sub-expressions fn process_expression(&mut self, expr: &AngularExpression<'_>) { if self.extract_sub_expressions { - self.collect_sub_expressions(expr, Self::record_source); + self.collect_sub_expressions(expr); } else if self.use_unparser { - self.record_expression(expr); - } else { - self.record_source(expr); + let unparsed = unparse_expression(expr); + self.sources.push(vec![unparsed]); + } else if let Some(source) = self.extract_expression_source(expr) { + self.sources.push(vec![source]); } } } @@ -381,7 +420,7 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { self.process_expression(expr); } } else if self.extract_sub_expressions { - self.collect_sub_expressions(&attr.value, Self::record_source); + self.collect_sub_expressions(&attr.value); } else if let Some(ref value_span) = attr.value_span { let start = value_span.start as usize; let end = value_span.end as usize; @@ -392,7 +431,15 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { } // Visit bound outputs (events) for event in &element.outputs { - self.visit_event_handler(&event.handler); + if self.extract_sub_expressions { + self.collect_sub_expressions(&event.handler); + } else if self.use_unparser { + // Use unparser for proper formatting (e.g., "foo(); bar();" with space after semicolon) + let unparsed = unparse_expression(&event.handler); + self.sources.push(vec![unparsed]); + } else if let Some(source) = self.extract_expression_source(&event.handler) { + self.sources.push(vec![source]); + } } } // Visit children @@ -415,7 +462,7 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { self.process_expression(expr); } } else if self.extract_sub_expressions { - self.collect_sub_expressions(&attr.value, Self::record_source); + self.collect_sub_expressions(&attr.value); } else if let Some(ref value_span) = attr.value_span { let start = value_span.start as usize; let end = value_span.end as usize; @@ -432,7 +479,15 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { } // Visit bound outputs for event in &template.outputs { - self.visit_event_handler(&event.handler); + if self.extract_sub_expressions { + self.collect_sub_expressions(&event.handler); + } else if self.use_unparser { + // Use unparser for proper formatting + let unparsed = unparse_expression(&event.handler); + self.sources.push(vec![unparsed]); + } else if let Some(source) = self.extract_expression_source(&event.handler) { + self.sources.push(vec![source]); + } } // Visit children visit_all(self, &template.children); @@ -482,27 +537,3 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { } } } - -#[cfg(test)] -mod tests { - use super::AstSpansRunner; - - #[test] - fn event_expression_text_uses_decoded_attribute_values() { - for tag in ["button", "ng-template"] { - let html = format!(r#"<{tag} (click)="save("x") // tail">"#); - for (sub_expressions, expected) in [(false, r#"save("x")"#), (true, r#""x""#)] { - let texts = AstSpansRunner::new().extract_expression_sources( - &html, - None, - sub_expressions, - false, - false, - false, - false, - ); - assert_eq!(texts, [vec![expected]], "{html}"); - } - } - } -} From 2a7abf5a6d7a4c2b7a079e65ac8234c24c1d7406 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 22:16:13 +0800 Subject: [PATCH 3/4] fix(parser): find the end of an interpolation like Angular find_interpolation_end had three rules Angular's _getInterpolationEndIndex does not: `//` was a comment only after an even number of backslashes, a `//` comment ended at a newline, and `/* */` hid `}}`. When no end was found the whole `{{ ... }}` became static text, e.g. `{{ s.replace(/\//g, '').replace(/'/g, '') }}` and `{{ s.replace(/[/*]/g, '') }}`. Port Angular's loop (_getInterpolationEndIndex + _forEachUnquotedChar) directly. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/expression/parser.rs | 109 +++--------------- .../tests/expression_parser_test.rs | 18 +++ 2 files changed, 37 insertions(+), 90 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/expression/parser.rs b/crates/oxc_angular_compiler/src/parser/expression/parser.rs index 7b5aa10f20..5f28f419af 100644 --- a/crates/oxc_angular_compiler/src/parser/expression/parser.rs +++ b/crates/oxc_angular_compiler/src/parser/expression/parser.rs @@ -851,102 +851,31 @@ impl<'a> Parser<'a> { result } - /// Finds the end of an interpolation, respecting quotes, escapes, and comments. - /// Returns the index of the end delimiter (relative to the start of the input), - /// or None if no valid end is found. + /// Finds the end of an interpolation, as Angular's `_getInterpolationEndIndex` does: + /// the first `end_delimiter` outside quotes, or, after an unquoted `//`, the next + /// `end_delimiter` anywhere. A quote preceded by an odd number of backslashes does not + /// open or close a string (`_forEachUnquotedChar`). Returns a byte index into `input`. fn find_interpolation_end(input: &str, end_delimiter: &str) -> Option { - let mut current_quote: Option = None; - let mut escape_count = 0; - let mut in_single_line_comment = false; - let mut in_multi_line_comment = false; - let end_len = end_delimiter.len(); - let mut byte_pos = 0; - let input_bytes = input.as_bytes(); - - while byte_pos < input.len() { - // Get current char - let remaining = &input[byte_pos..]; - // Safety: byte_pos < input.len() guarantees at least one char - let Some(ch) = remaining.chars().next() else { break }; - let ch_len = ch.len_utf8(); - - // Get next char if available - let next_ch = remaining.chars().nth(1); - - // Handle single-line comment - // Note: In Angular interpolations, we still check for end delimiter inside comments - // because the interpolation end `}}` takes precedence over comment continuation - if in_single_line_comment { - if ch == '\n' || ch == '\r' { - in_single_line_comment = false; - } - // Check for end delimiter even inside single-line comment - // This is Angular-specific behavior for interpolations - if byte_pos + end_len <= input.len() - && &input_bytes[byte_pos..byte_pos + end_len] == end_delimiter.as_bytes() - { - return Some(byte_pos); - } - byte_pos += ch_len; - continue; - } - - // Handle multi-line comment end - if in_multi_line_comment { - if ch == '*' && next_ch == Some('/') { - in_multi_line_comment = false; - byte_pos += 2; // '*' and '/' are both 1 byte - continue; - } - byte_pos += ch_len; - continue; - } - - // Track escape sequences by counting consecutive backslashes - if ch == '\\' { - escape_count += 1; - byte_pos += ch_len; - continue; - } - - // Check for quotes (only if not escaped: even number of backslashes) - if (ch == '"' || ch == '\'' || ch == '`') - && (current_quote.is_none() || current_quote == Some(ch)) - && escape_count % 2 == 0 + let bytes = input.as_bytes(); + let mut quote: Option = None; + let mut escapes = 0usize; + for (i, &ch) in bytes.iter().enumerate() { + if matches!(ch, b'\'' | b'"' | b'`') + && quote.is_none_or(|q| q == ch) + && escapes.is_multiple_of(2) { - current_quote = if current_quote.is_none() { Some(ch) } else { None }; - } - - // Check for comment start (only when not in quotes) - if current_quote.is_none() && escape_count % 2 == 0 { - if ch == '/' && next_ch == Some('/') { - in_single_line_comment = true; - byte_pos += 2; // '//' is 2 bytes - escape_count = 0; - continue; + quote = if quote.is_none() { Some(ch) } else { None }; + } else if quote.is_none() { + if bytes[i..].starts_with(end_delimiter.as_bytes()) { + return Some(i); } - if ch == '/' && next_ch == Some('*') { - in_multi_line_comment = true; - byte_pos += 2; // '/*' is 2 bytes - escape_count = 0; - continue; + // `/` is ASCII, so `i` is a char boundary here. + if bytes[i..].starts_with(b"//") { + return input[i..].find(end_delimiter).map(|pos| i + pos); } } - - // If not inside quotes or comments, check for end delimiter - if current_quote.is_none() - && !in_single_line_comment - && !in_multi_line_comment - && byte_pos + end_len <= input.len() - && &input_bytes[byte_pos..byte_pos + end_len] == end_delimiter.as_bytes() - { - return Some(byte_pos); - } - - escape_count = 0; - byte_pos += ch_len; + escapes = if ch == b'\\' { escapes + 1 } else { 0 }; } - None } diff --git a/crates/oxc_angular_compiler/tests/expression_parser_test.rs b/crates/oxc_angular_compiler/tests/expression_parser_test.rs index e9cfb030c1..28404969cd 100644 --- a/crates/oxc_angular_compiler/tests/expression_parser_test.rs +++ b/crates/oxc_angular_compiler/tests/expression_parser_test.rs @@ -1565,6 +1565,24 @@ mod parse_interpolation { check_interpolation(r#"{{ "a'b`" //comment}}"#, Some(r"{{ 'a\'b`' }}")); } + #[test] + fn should_find_the_end_after_a_regex_with_an_escaped_slash() { + // Like Angular's _getInterpolationEndIndex: a `//` inside the regex is not a + // comment, and the `'` inside the second regex does not hide the `}}`. + check_interpolation(r"{{ s.replace(/\//g, '').replace(/'/g, '') }}", None); + } + + #[test] + fn should_not_treat_slash_star_as_a_block_comment() { + check_interpolation(r"{{ s.replace(/[/*]/g, '') }}", None); + } + + #[test] + fn should_find_the_end_after_a_comment_across_lines() { + // After `//`, Angular looks for the next `}}` anywhere, past the newline. + check_interpolation("{{ z // it\n 's z }}", Some("{{ z }}")); + } + #[test] fn should_ignore_quotes_inside_comment() { // TS: it("should ignore quotes inside a comment") From 08f62f0b3e7a5b3b4be858454812516b7fb264b0 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 22:20:03 +0800 Subject: [PATCH 4/4] test(parser): cover escaped quotes and event handler spans Port Angular's two spec cases (a regex ending in an escaped slash, escaped quotes before a comment), add a find_comment_start table, and check that handler_span keeps the trailing comment on on-, [()], bindon- and legacy animation events, as Angular's handlerSpan does. Update the find_comment_start doc. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/expression/mod.rs | 27 ++++++++++++++++++- .../tests/expression_parser_test.rs | 13 +++++++++ .../tests/r3_template_transform_test.rs | 24 +++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/crates/oxc_angular_compiler/src/parser/expression/mod.rs b/crates/oxc_angular_compiler/src/parser/expression/mod.rs index 3e21204683..122f3993ed 100644 --- a/crates/oxc_angular_compiler/src/parser/expression/mod.rs +++ b/crates/oxc_angular_compiler/src/parser/expression/mod.rs @@ -45,7 +45,10 @@ pub struct StripCommentsResult<'a> { pub comment_start: Option, } -/// Finds the start of a `//` comment, respecting string quotes. +/// Finds the start of a `//` comment outside string quotes. +/// +/// Like Angular's `_commentStart`, a backslash skips the next character, so +/// `/^\//` and `'it\'s'` do not start a comment. /// /// Returns `None` if no comment is found, or the byte position of `//`. pub fn find_comment_start(input: &str) -> Option { @@ -227,3 +230,25 @@ impl<'a> BindingParser<'a> { parser.parse_template_bindings(key_identifier) } } + +#[cfg(test)] +mod tests { + use super::find_comment_start; + + /// Same results as Angular's `_commentStart`, as byte offsets. + #[test] + fn find_comment_start_skips_escaped_chars() { + for (input, expected) in [ + ("a // b", Some(2)), + ("'a // b'", None), + (r"/\//", None), + (r"'\'//'", None), + (r"a\\//b", Some(3)), + (r"p.replace(/^\//, '') // c", Some(21)), + ("\\", None), + ("\\é//", Some(3)), + ] { + assert_eq!(find_comment_start(input), expected, "{input}"); + } + } +} diff --git a/crates/oxc_angular_compiler/tests/expression_parser_test.rs b/crates/oxc_angular_compiler/tests/expression_parser_test.rs index 28404969cd..8f9b0e2e93 100644 --- a/crates/oxc_angular_compiler/tests/expression_parser_test.rs +++ b/crates/oxc_angular_compiler/tests/expression_parser_test.rs @@ -870,6 +870,13 @@ mod parse_binding { ); } + #[test] + fn should_parse_regex_ending_with_escaped_slash() { + // TS: it('should parse a regular expression literal that ends with an escaped slash') + check_binding(r"/^https?:\/\//", None); + check_binding(r#"url.replace(/^\//, "") //comment"#, Some(r"url.replace(/^\//, '')")); + } + #[test] fn should_report_invalid_regex_flag() { expect_binding_error("\"foo\".match(/abc/O)", "Unsupported regular expression flag"); @@ -1565,6 +1572,12 @@ mod parse_interpolation { check_interpolation(r#"{{ "a'b`" //comment}}"#, Some(r"{{ 'a\'b`' }}")); } + #[test] + fn should_ignore_escaped_quotes_when_looking_for_comments() { + // TS: it('should ignore escaped quotes when looking for comments') + check_interpolation(r"{{ 'it\'s // here' //comment }}", Some(r"{{ 'it\'s // here' }}")); + } + #[test] fn should_find_the_end_after_a_regex_with_an_escaped_slash() { // Like Angular's _getInterpolationEndIndex: a `//` inside the regex is not 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 bb030bc27b..ca0135df12 100644 --- a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs +++ b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs @@ -1033,6 +1033,30 @@ mod events { } } + /// The handler span is the whole attribute value, comment included, on every + /// event path, like Angular's `handlerSpan` (`attribute.valueSpan`). + #[test] + fn event_handler_span_keeps_trailing_comment() { + for (attr, handler) in [ + ("on-click=\"a() // c\"", "a() // c"), + ("[(x)]=\"v // c\"", "v // c"), + ("bindon-x=\"v // c\"", "v // c"), + ("(@x.done)=\"a() // c\"", "a() // c"), + ] { + let html = format!(""); + let allocator = Allocator::default(); + let parsed = HtmlParser::new(&allocator, &html, "test.html").parse(); + let result = HtmlToR3Transform::new(&allocator, &html, TransformOptions::default()) + .transform(&parsed.nodes); + let R3Node::Element(a) = &result.nodes[0] else { panic!("expected element") }; + let event = a.outputs.last().expect("an output"); + let start = u32::try_from(html.find(handler).unwrap()).unwrap(); + let end = start + u32::try_from(handler.len()).unwrap(); + let span = event.handler_span; + assert_eq!((span.start, span.end), (start, end), "{attr}"); + } + } + #[test] fn should_parse_event_bindings() { // TS: expectFromHtml('
')