diff --git a/crates/angular_conformance/README.md b/crates/angular_conformance/README.md index d44d7d17c..295bd347f 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 812e9a991..c3a1c91bf 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 31677fe45..34007a037 100644 --- a/crates/angular_conformance/src/subsystems/ast_spans.rs +++ b/crates/angular_conformance/src/subsystems/ast_spans.rs @@ -437,12 +437,8 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { // 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()]); - } + } else if let Some(source) = self.extract_expression_source(&event.handler) { + self.sources.push(vec![source]); } } } @@ -489,12 +485,8 @@ impl<'b> R3Visitor<'b> for ExpressionSourceCollector<'b> { // 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()]); - } + } else if let Some(source) = self.extract_expression_source(&event.handler) { + self.sources.push(vec![source]); } } // Visit children diff --git a/crates/oxc_angular_compiler/src/parser/expression/mod.rs b/crates/oxc_angular_compiler/src/parser/expression/mod.rs index f7d65587b..122f3993e 100644 --- a/crates/oxc_angular_compiler/src/parser/expression/mod.rs +++ b/crates/oxc_angular_compiler/src/parser/expression/mod.rs @@ -45,27 +45,27 @@ 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 { 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), + _ => {} } } @@ -230,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/src/parser/expression/parser.rs b/crates/oxc_angular_compiler/src/parser/expression/parser.rs index 8b093708a..5f28f419a 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". @@ -888,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 } @@ -1857,7 +1749,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 +1769,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 c21d81ddc..b4cca8b6b 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/expression_parser_test.rs b/crates/oxc_angular_compiler/tests/expression_parser_test.rs index e9cfb030c..8f9b0e2e9 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,30 @@ 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 + // 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") 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 68a02bb61..ca0135df1 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,53 @@ 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); + } + } + + /// 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('
')