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
2 changes: 1 addition & 1 deletion crates/angular_conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 2 additions & 18 deletions crates/angular_conformance/snapshots/angular.snap.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@
| 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% |
| html_whitespace | 21 | 0 | 0 | 0 | 21 | 100.0% |
| 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

Expand Down Expand Up @@ -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: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.EOF")]], options: None }
Expand Down
16 changes: 4 additions & 12 deletions crates/angular_conformance/src/subsystems/ast_spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
}
}
Expand Down Expand Up @@ -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
Expand Down
52 changes: 37 additions & 15 deletions crates/oxc_angular_compiler/src/parser/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,27 +45,27 @@ pub struct StripCommentsResult<'a> {
pub comment_start: Option<usize>,
}

/// 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<usize> {
let bytes = input.as_bytes();
let mut outer_quote: Option<u8> = 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),
_ => {}
}
}

Expand Down Expand Up @@ -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}");
}
}
}
153 changes: 22 additions & 131 deletions crates/oxc_angular_compiler/src/parser/expression/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<usize> {
let bytes = input.as_bytes();
let mut outer_quote: Option<u8> = 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".
Expand Down Expand Up @@ -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<usize> {
let mut current_quote: Option<char> = 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<u8> = 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
}

Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
Loading
Loading