From ada728e8f2037fa0a51c445688124179350439e6 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 16:47:05 +0800 Subject: [PATCH 01/47] fix(parser): read line continuations in escaped strings like Angular Angular's EscapedCharacterCursor skips a line continuation (a backslash and one CR or LF, so a CRLF leaves its LF) when it lands on one, and then reads the next character as is: an escape right after it is not decoded, and a NUL there ends the input. The skipped characters are part of the previous token's span. We read a continuation only when advancing from it: peek() returned the newline, advance() also moved past the next character, and the text decoder dropped the LF of a CRLF and decoded an escape after it. Now the cursor skips a continuation when it lands on one (and at the start), the character after it is read as is by peek, peek_at, advance and the text decoder, and errors after an escaped NUL that ends the text are dropped, as Angular reads nothing after it. Example (escaped, one backslash): `\0y?>z` Angular: PI 'x\0y' 0-10, Text 'z' before: PI 'x' 0-10, 'z' lost `\{` Angular: PI 0-5, Text '{' 5-6; before: PI 0-3, Text 3-6 Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 207 +++++++++++------- .../tests/html_lexer_test.rs | 71 ++++++ 2 files changed, 199 insertions(+), 79 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index e01260611..5ee281a69 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -482,14 +482,12 @@ fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) i += 2; } } - '\n' => { - // Line continuation - skip both backslash and newline + '\n' | '\r' => { + // A line continuation: as Angular's cursor, skip the backslash and one CR or LF (so a CRLF + // leaves its LF), and read the character after it as is. i += 2; - } - '\r' => { - // Line continuation with CR or CRLF - i += 2; - if i < chars.len() && chars[i] == '\n' { + if let Some(&ch) = chars.get(i) { + result.push(ch); i += 1; } } @@ -614,6 +612,9 @@ pub struct HtmlLexer<'a> { range_start_pos: u32, /// Range end position. range_end_pos: u32, + /// In an escaped string, the byte offsets right after each line continuation the cursor skips, in order. + /// Angular's cursor reads the character there as is: an escape starting there is not decoded. + continuation_ends: Vec, /// Line offset for range mode. range_line_offset: u32, /// Column offset for range mode. @@ -646,6 +647,7 @@ impl<'a> HtmlLexer<'a> { leading_trivia_chars: None, range_start_pos: 0, range_end_pos: length, + continuation_ends: Vec::new(), range_line_offset: 0, range_col_offset: 0, } @@ -750,6 +752,8 @@ impl<'a> HtmlLexer<'a> { /// Tokenizes the input. pub fn tokenize(mut self) -> HtmlTokenizeResult { + self.find_line_continuations(); + self.skip_line_continuation(); // Like Angular's loop, stop at a NUL: its cursor peeks one as `$EOF`. while self.index < self.length && self.peek() != chars::EOF { self.scan_token(); @@ -758,7 +762,7 @@ impl<'a> HtmlLexer<'a> { self.tokens.push(HtmlToken::empty(HtmlTokenType::Eof, self.index, self.index)); // Merge adjacent text tokens (Angular does this to combine empty text tokens with adjacent text) - let mut tokens = merge_text_tokens(self.tokens); + let mut tokens = merge_text_tokens(std::mem::take(&mut self.tokens)); // Process escape sequences if enabled if self.escaped_string { @@ -783,6 +787,12 @@ impl<'a> HtmlLexer<'a> { if has_null { null_encountered = true; null_token_idx = Some(token_idx); + // Angular's text ends at the NUL, which ends the input: nothing after it is read + if token.token_type == HtmlTokenType::Text + && let Some(nul_end) = self.first_nul_end(token.start, token.end) + { + self.errors.retain(|error| error.offset as usize <= nul_end); + } break; } } @@ -831,16 +841,102 @@ impl<'a> HtmlLexer<'a> { /// Peeks at the current character (handles escape sequences when escaped_string is true). fn peek(&self) -> char { - let ch = self.raw_peek(); - if self.escaped_string && ch == '\\' { - if let Some((ch, _)) = self.code_point_escape_at(self.index as usize) { - return ch; + self.cursor_char_at(self.index as usize) + } + + /// The character the cursor reads at byte `pos`: an escape is decoded, unless it starts right after a line + /// continuation. + fn cursor_char_at(&self, pos: usize) -> char { + let ch = self.input.get(pos..self.length as usize).and_then(|s| s.chars().next()); + let Some(ch) = ch else { return chars::EOF }; + if !self.escaped_string || ch != '\\' || self.reads_raw_at(pos) { + return ch; + } + if let Some((ch, _)) = self.code_point_escape_at(pos) { + return ch; + } + // Look ahead to see what character is being escaped + let next = self.input[(pos + 1)..].chars().next().unwrap_or(chars::EOF); + Self::unescape_char(next) + } + + /// Whether a line continuation (a backslash and a CR or LF) starts at byte `pos` of an escaped string. + fn is_line_continuation_at(&self, pos: usize) -> bool { + self.escaped_string + && pos + 1 < self.length as usize + && self.input.as_bytes()[pos] == b'\\' + && matches!(self.input.as_bytes()[pos + 1], b'\n' | b'\r') + } + + /// Whether the cursor reads the character at byte `pos` as is: it comes right after a line continuation. + fn reads_raw_at(&self, pos: usize) -> bool { + self.continuation_ends.binary_search(&pos).is_ok() + } + + /// The byte after the cursor character at `pos`: a whole escape, unless it is read as is. + fn cursor_char_end(&self, pos: usize) -> usize { + let ch = self.input[pos..].chars().next().unwrap_or(chars::EOF); + if !self.escaped_string || ch != '\\' || self.reads_raw_at(pos) { + return pos + ch.len_utf8(); + } + if let Some((_, len)) = self.code_point_escape_at(pos) { + return pos + len; + } + let escaped = self.input.get(pos + 1..self.length as usize).and_then(|s| s.chars().next()); + pos + 1 + escaped.map_or(0, char::len_utf8) + } + + /// The byte the cursor moves to from `pos`, past a line continuation it lands on, as Angular's + /// `EscapedCharacterCursor` skips one (a backslash and one CR or LF). + fn next_cursor_pos(&self, pos: usize) -> usize { + let next = self.cursor_char_end(pos); + if self.is_line_continuation_at(next) { next + 2 } else { next } + } + + /// Records where the line continuations the cursor skips end, walking the input as the cursor does. + fn find_line_continuations(&mut self) { + if !self.escaped_string { + return; + } + let mut pos = self.index as usize; + loop { + if self.is_line_continuation_at(pos) { + pos += 2; + self.continuation_ends.push(pos); + } + if pos >= self.length as usize { + break; + } + pos = self.cursor_char_end(pos); + } + } + + /// The byte after the first character the cursor reads as NUL in `start..end`, if any. + fn first_nul_end(&self, start: u32, end: u32) -> Option { + let mut pos = start as usize; + while pos < end as usize { + let escaped_nul = !self.reads_raw_at(pos) + && matches!(self.code_point_escape_value_at(pos), Some((Some(0), _))); + if escaped_nul || self.cursor_char_at(pos) == chars::EOF { + return Some(self.cursor_char_end(pos)); + } + pos = self.next_cursor_pos(pos); + } + None + } + + /// Skips a line continuation at the cursor, as Angular's cursor does when it lands on one. + fn skip_line_continuation(&mut self) { + let pos = self.index as usize; + if self.is_line_continuation_at(pos) { + self.index += 2; + // As Angular's cursor: the backslash is a column, an LF a new line, a CR neither + if self.input.as_bytes()[pos + 1] == b'\n' { + self.line += 1; + self.column = 0; + } else { + self.column += 1; } - // Look ahead to see what character is being escaped - let next = self.input[(self.index as usize + 1)..].chars().next().unwrap_or(chars::EOF); - Self::unescape_char(next) - } else { - ch } } @@ -907,7 +1003,7 @@ impl<'a> HtmlLexer<'a> { /// escaped string: Angular peeks EOF there too, but moving past it is the end of the input. fn at_nul(&self) -> bool { let pos = self.index as usize; - if self.escaped_string && self.raw_peek() == '\\' { + if self.escaped_string && self.raw_peek() == '\\' && !self.reads_raw_at(pos) { pos + 1 < self.length as usize && (self.peek() == chars::EOF || matches!(self.code_point_escape_value_at(pos), Some((Some(0), _)))) @@ -924,38 +1020,14 @@ impl<'a> HtmlLexer<'a> { return chars::EOF; } if self.escaped_string { - // Need to iterate through escape sequences properly let mut pos = self.index as usize; - let mut remaining = offset; - while remaining > 0 && pos < self.length as usize { - let ch = self.input[pos..].chars().next().unwrap_or(chars::EOF); - if let Some((_, len)) = self.code_point_escape_at(pos) { - pos += len; - } else if ch == '\\' { - // Skip past escape sequence - pos += 1; - if pos < self.length as usize { - let escaped = self.input[pos..].chars().next().unwrap_or(chars::EOF); - pos += escaped.len_utf8(); - } - } else { - pos += ch.len_utf8(); - } - remaining -= 1; - } - if pos >= self.length as usize { - chars::EOF - } else { - let ch = self.input[pos..].chars().next().unwrap_or(chars::EOF); - if let Some((ch, _)) = self.code_point_escape_at(pos) { - ch - } else if ch == '\\' { - let next = self.input[(pos + 1)..].chars().next().unwrap_or(chars::EOF); - Self::unescape_char(next) - } else { - ch + for _ in 0..offset { + if pos >= self.length as usize { + break; } + pos = self.next_cursor_pos(pos); } + self.cursor_char_at(pos) } else { self.input[self.index as usize..].chars().nth(offset as usize).unwrap_or(chars::EOF) } @@ -963,14 +1035,21 @@ impl<'a> HtmlLexer<'a> { /// Advances the index and returns the current character. fn advance(&mut self) -> char { + let ch = self.advance_char(); + self.skip_line_continuation(); + ch + } + + /// Moves past the current character, as `advance` but without skipping a line continuation after it. + fn advance_char(&mut self) -> char { if self.index >= self.length { return chars::EOF; } let raw_ch = self.raw_peek(); - // Handle escape sequences when escaped_string is true - if self.escaped_string && raw_ch == '\\' { + // Handle escape sequences when escaped_string is true (not right after a line continuation) + if self.escaped_string && raw_ch == '\\' && !self.reads_raw_at(self.index as usize) { let next_pos = self.index as usize + 1; if next_pos >= self.length as usize { // Backslash at end of input - just advance past it @@ -981,36 +1060,6 @@ impl<'a> HtmlLexer<'a> { let next = self.input[next_pos..].chars().next().unwrap_or(chars::EOF); - // Check for line continuation (backslash followed by newline) - if next == '\n' || next == '\r' { - // Skip the backslash - self.index += 1; - self.column += 1; - // Now handle the newline - if next == '\r' { - let after_pos = self.index as usize + 1; - let after = if after_pos < self.length as usize { - self.input[after_pos..].chars().next() - } else { - None - }; - if after == Some('\n') { - self.index += 2; // Skip CR and LF - } else { - self.index += 1; - } - } else { - self.index += 1; - } - self.line += 1; - self.column = 0; - // Line continuation - return the next actual character (or EOF if at end) - if self.index >= self.length { - return chars::EOF; - } - return self.advance(); - } - // A code-point escape is one character, as in Angular's cursor if let Some((ch, len)) = self.code_point_escape_at(self.index as usize) { self.index += len as u32; diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index bf99bc835..8d4b8cbbc 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -1907,6 +1907,77 @@ mod processing_instructions { assert_eq!(lex(r"z"), pi_end, len), (eof(), len, len)] + }; + assert_eq!(lex("z", true), (ended("x", 6, 10), vec![])); + assert_eq!(lex("z", true), (ended("x\n", 7, 11), vec![])); + assert_eq!( + lex("z", true), + (vec![(pi("x\\0y"), 0, 10), (text("z"), 10, 11), (eof(), 11, 11)], vec![]) + ); + // A quote after it starts a quoted part. + assert_eq!( + lex("'?>z", true), + (vec![(pi("a'?>'"), 0, 11), (text("z"), 11, 12), (eof(), 12, 12)], vec![]) + ); + assert_eq!( + lex("z", true), + (vec![(pi(""), 0, 6), (text("z"), 6, 7), (eof(), 7, 7)], vec![]) + ); + assert_eq!( + lex("z", true), + (vec![(pi("\n"), 0, 7), (text("z"), 7, 8), (eof(), 8, 8)], vec![]) + ); + // One right after the instruction is part of its span. + assert_eq!( + lex("\\\n{", true), + (vec![(pi(""), 0, 5), (text("{"), 5, 6), (eof(), 6, 6)], vec![]) + ); + assert_eq!(lex("\\\n", true), (vec![(pi(""), 0, 5), (eof(), 5, 5)], vec![])); + } +} + +mod escaped_line_continuations { + use super::*; + + type Lexed = (Vec<(HtmlTokenType, Vec, u32, u32)>, Vec<(String, u32)>); + + /// Tokens with their spans, and errors with their offsets, of an escaped string. + fn lex(input: &str) -> Lexed { + let result = HtmlLexer::new(input).with_escaped_string(true).tokenize(); + let tokens = + result.tokens.into_iter().map(|t| (t.token_type, t.parts, t.start, t.end)).collect(); + (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect()) + } + + fn text(value: &str, start: u32, end: u32) -> (HtmlTokenType, Vec, u32, u32) { + (HtmlTokenType::Text, vec![value.to_string()], start, end) + } + + fn eof(offset: u32) -> (HtmlTokenType, Vec, u32, u32) { + (HtmlTokenType::Eof, vec![], offset, offset) + } + + #[test] + fn should_read_the_character_after_it_as_is() { + // A NUL after it ends the text and the input. + assert_eq!(lex("a\\\n\0b"), (vec![text("a", 0, 3), eof(3)], vec![])); + // A backslash after it is a character, which starts no line continuation. + assert_eq!(lex("a\\\n\\\nb"), (vec![text("a\\\nb", 0, 6), eof(6)], vec![])); + } + + #[test] + fn should_report_nothing_after_an_escaped_nul_in_text() { + // Angular's text ends at the NUL, which ends the input: the open tag after it is not read. + assert_eq!(lex("\\0 Date: Fri, 4 Dec 2026 16:36:58 +0800 Subject: [PATCH 02/47] fix(parser): keep an escaped NUL inside quotes in a processing instruction Angular's cursor peeks a NUL as EOF, but its processing instruction scan does not check for EOF inside quotes: it moves past the NUL, keeps it in the content as U+0000, and lexing goes on after the instruction. In escaped-string mode our post-pass decoded escapes in every token part and cut the token list at the first escaped NUL, so all text after the instruction was lost. A NUL escape in a ProcessingInstruction part now decodes to '\0' and does not cut the tokens; other token kinds are unchanged. Example (escaped string 'z'): Angular: PI '"\u0000"' 0-8, Text 'z' 8-9, EOF before: PI '"' 0-8, EOF after: same as Angular (also \000, \x00, \u0000, \u{0}) Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 44 ++++++++++++------- .../tests/html_lexer_test.rs | 37 ++++++++++++++++ 2 files changed, 64 insertions(+), 17 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 5ee281a69..f2aaf2966 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -287,14 +287,28 @@ fn parse_int_prefix(digits: &str, radix: u32) -> Option { /// Processes escape sequences in text when in "escaped strings" mode. /// This is used when tokenize_expansion_forms is false (Angular's default for inline templates). /// Returns (processed_text, errors, encountered_null). -/// When a null character (\0) is encountered, everything after it is discarded (EOF behavior). -fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) { +/// When a null character (\0) is encountered, everything after it is discarded (EOF behavior), +/// unless `keep_nul` is set: then it decodes to `\0` and the text goes on. +fn process_escape_sequences(text: &str, keep_nul: bool) -> (String, Vec<(String, usize)>, bool) { let mut result = String::with_capacity(text.len()); let mut errors = Vec::new(); let chars: Vec = text.chars().collect(); let mut i = 0; let mut encountered_null = false; + // An escaped NUL that ends at `next`: kept as `\0` with `keep_nul`, else the end of the text. + macro_rules! nul { + ($next:expr) => {{ + if keep_nul { + result.push('\0'); + i = $next; + continue; + } + encountered_null = true; + break; + }}; + } + while i < chars.len() { if chars[i] == '\\' && i + 1 < chars.len() { let next = chars[i + 1]; @@ -346,19 +360,16 @@ fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) result.push(code as char); } else { // Result is null - treat as EOF - encountered_null = true; - break; + nul!(j); } } i = j; } else if i + 2 < chars.len() && chars[i + 2].is_ascii_digit() { // \0 followed by 8 or 9 - \0 is null (EOF), stop processing - encountered_null = true; - break; + nul!(i + 2); } else { // Just \0 - null character, treat as EOF - encountered_null = true; - break; + nul!(i + 2); } } '1'..='7' => { @@ -374,8 +385,7 @@ fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) result.push(code as char); } else { // Null character - treat as EOF - encountered_null = true; - break; + nul!(j); } } i = j; @@ -397,8 +407,7 @@ fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) result.push(code as char); } else { // Null character - treat as EOF - encountered_null = true; - break; + nul!(i + 4); } } i += 4; @@ -430,8 +439,7 @@ fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) if let Ok(code) = u32::from_str_radix(&hex, 16) { if code == 0 { // Null character - treat as EOF - encountered_null = true; - break; + nul!(j + 1); } if let Some(ch) = char::from_u32(code) { result.push(ch); @@ -459,8 +467,7 @@ fn process_escape_sequences(text: &str) -> (String, Vec<(String, usize)>, bool) if let Ok(code) = u32::from_str_radix(&hex, 16) { if code == 0 { // Null character - treat as EOF - encountered_null = true; - break; + nul!(i + 6); } if let Some(ch) = char::from_u32(code) { result.push(ch); @@ -776,9 +783,12 @@ impl<'a> HtmlLexer<'a> { break; } + // Angular's cursor peeks a NUL as EOF but can move past it. Its processing instruction scan reaches + // one only inside quotes, which it moves past, so the NUL stays in the content and lexing goes on. + let keep_nul = token.token_type == HtmlTokenType::ProcessingInstruction; // Process escape sequences in token parts for part in &mut token.parts { - let (processed, errs, has_null) = process_escape_sequences(part); + let (processed, errs, has_null) = process_escape_sequences(part, keep_nul); *part = processed; for (msg, offset) in errs { // The error offset is relative to the token start diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 8d4b8cbbc..68556ff80 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -1941,6 +1941,43 @@ mod processing_instructions { ); assert_eq!(lex("\\\n", true), (vec![(pi(""), 0, 5), (eof(), 5, 5)], vec![])); } + + #[test] + fn should_keep_an_escaped_nul_inside_quotes_like_angular() { + // Angular moves past a NUL inside quotes: it stays in the content and lexing goes on. + for (nul, len) in [(r"\0", 2), (r"\000", 4), (r"\x00", 4), (r"\u0000", 6), (r"\u{0}", 5)] { + let input = format!("z"); + let end = len + 6; + let tokens = + vec![(pi("\"\0\""), 0, end), (text("z"), end, end + 1), (eof(), end + 1, end + 1)]; + assert_eq!(lex(&input, true), (tokens, vec![]), "{input}"); + } + assert_eq!( + lex(r#"z"#, true), + (vec![(pi("x \"a\0b\""), 0, 12), (text("z"), 12, 13), (eof(), 13, 13)], vec![]) + ); + assert_eq!(lex(r#"z"#, true).0[0], (pi("\"a\u{0}8\""), 0, 10)); + let tag = |kind, name: &str| (kind, vec![String::new(), name.to_string()]); + assert_eq!( + lex(r#"c"#, true), + ( + vec![ + (pi("\"a\0b\""), 0, 10), + (text("c"), 10, 11), + (tag(HtmlTokenType::TagOpenStart, "i"), 11, 13), + ((HtmlTokenType::TagOpenEnd, vec![]), 13, 14), + (tag(HtmlTokenType::TagClose, "i"), 14, 18), + (eof(), 18, 18), + ], + vec![] + ) + ); + // After the quotes, a NUL ends the instruction again. + assert_eq!( + lex(r#"z"#, true), + (vec![(pi("\"a\0b\""), 0, 10), (text("?>z"), 10, 13), (eof(), 13, 13)], vec![]) + ); + } } mod escaped_line_continuations { From 34430a747cd423de80931fcf301cf622ad601700 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 16:46:56 +0800 Subject: [PATCH 03/47] fix(parser): drop a processing instruction at a bad escape after it like Angular Angular's EscapedCharacterCursor decodes the next escape as soon as it moves onto it. So when _consumeProcessingInstruction moves past the end of the instruction (`>`, the `?` of `?>`, or a NUL) onto a bad escape, the cursor throws before the token is emitted: the instruction is dropped and tokenize() records the error. For invalid digits the cursor still peeks the backslash, which is read as text before moving on from the escape's end; an escape cut short by the end of the input ends it. We kept the instruction and lexed the escape as text. Now, in escaped-string mode, the lexer checks for such an escape after each of those moves and recovers like Angular (not after an escaped NUL in text, where Angular's lexing has already ended). '\u{' Angular [EOF 13] err EOF @13 Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 107 ++++++++++++++++++ .../tests/html_lexer_test.rs | 63 +++++++++++ 2 files changed, 170 insertions(+) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index f2aaf2966..e31c38cb2 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -38,6 +38,24 @@ enum EntityError { Eof(u32, u32, u32), } +/// What Angular's `EscapedCharacterCursor` throws when it moves onto a bad escape (see `cursor_escape_error`). +#[derive(Debug, Clone, Copy)] +enum EscapeError { + /// The escape runs into the end of the input: `Unexpected character "EOF"`. + Eof, + /// `Invalid hexadecimal escape sequence` for the digits at byte `digits`. The escape ends at byte `end`; none + /// when the input ends on its last character, which the cursor then fails to move past. + InvalidHex { digits: u32, end: Option }, +} + +/// Whether JavaScript's `parseInt(digits, 16)` is NaN: no hex digit after leading whitespace, a sign and `0x`. +fn hex_is_nan(digits: &str) -> bool { + let digits = digits.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}'); + let digits = digits.strip_prefix(['+', '-']).unwrap_or(digits); + let digits = digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0X")).unwrap_or(digits); + !digits.starts_with(|c: char| c.is_ascii_hexdigit()) +} + /// Token types for HTML templates. /// Matches Angular's `TokenType` enum from `ml_parser/tokens.ts`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1022,6 +1040,88 @@ impl<'a> HtmlLexer<'a> { } } + /// The error Angular's `EscapedCharacterCursor` throws when it moves onto the escape at the cursor, if any. It + /// decodes the escape at once: `\u{` with no `}` after it, `\u` with fewer than 3 characters after it and `\x` + /// with none run into the end of the input, and digits `parseInt` reads as NaN are invalid. + fn cursor_escape_error(&self) -> Option { + if !self.escaped_string { + return None; + } + let pos = self.index as usize; + let rest = self.input.get(pos..)?.strip_prefix('\\')?; + let take_chars = |s: &str, n: usize| s.char_indices().nth(n).map_or(s.len(), |(i, _)| i); + // The digits, and the escape's end (none when cut short by the end of the input). + let (digits_start, digits, end) = if let Some(braced) = rest.strip_prefix("u{") { + let Some(close) = braced.find('}') else { return Some(EscapeError::Eof) }; + (pos + 3, &braced[..close], Some(pos + 4 + close)) + } else if let Some((fixed, width)) = rest + .strip_prefix('u') + .map(|s| (s, 4)) + .or_else(|| rest.strip_prefix('x').map(|s| (s, 2))) + { + // The cursor moves onto the last digit, so the input may end one character short. + let digits = &fixed[..take_chars(fixed, width)]; + let count = digits.chars().count(); + if count + 1 < width { + return Some(EscapeError::Eof); + } + (pos + 2, digits, (count == width).then_some(pos + 2 + digits.len())) + } else { + return None; + }; + if !hex_is_nan(digits) { + return None; + } + let digits = u32::try_from(digits_start).ok()?; + Some(EscapeError::InvalidHex { digits, end: end.and_then(|end| u32::try_from(end).ok()) }) + } + + /// Moves the cursor to byte `target`, counting lines and columns over the raw characters. + fn move_raw_to(&mut self, target: u32) { + let start = self.index as usize; + let mut chars = self.input[start..].char_indices().peekable(); + while let Some((_, ch)) = chars.next().filter(|&(i, _)| start + i < target as usize) { + if ch == '\n' || (ch == '\r' && chars.peek().is_none_or(|&(_, next)| next != '\n')) { + self.line += 1; + self.column = 0; + } else if ch != '\r' { + self.column += 1; + } + } + self.index = target; + } + + /// Angular's cursor decodes an escape as soon as it moves onto it, so a bad escape right after the last character + /// of a token throws before the token is emitted. Returns whether the cursor is at one, after recovering like + /// Angular's `tokenize`: it reports the error and, for invalid digits, reads the escape as a `\` of text (the + /// cursor still peeks the backslash, then moves on from the escape's end); otherwise, the input ends. + /// + /// Not after an escaped NUL in text: Angular's lexing ends there, and the tokens after it are dropped. + fn recover_at_bad_escape(&mut self) -> bool { + let Some(error) = self.cursor_escape_error() else { return false }; + let past_nul = self.tokens.iter().any(|t| { + t.token_type == HtmlTokenType::Text + && t.parts.iter().any(|p| process_escape_sequences(p, false).2) + }); + if past_nul { + return false; + } + let start = self.index; + if let EscapeError::InvalidHex { digits, end } = error { + self.move_raw_to(digits); + self.error("Invalid hexadecimal escape sequence"); + if let Some(end) = end { + self.move_raw_to(end); + // An escaped backslash, which the escape pass after tokenizing reads as `\`. + self.tokens.push(HtmlToken::with_part(HtmlTokenType::Text, "\\\\", start, end)); + return true; + } + } + self.move_raw_to(self.length); + self.error("Unexpected character \"EOF\""); + true + } + /// Peeks at a character at offset from current position. /// Note: offset is in characters, not bytes. /// When escaped_string is true, this accounts for escape sequences. @@ -3142,13 +3242,20 @@ impl<'a> HtmlLexer<'a> { return; } let content = self.input[content_start as usize..self.index as usize].to_string(); + // Angular drops the instruction when the cursor moves past its end onto a bad escape. let end_char = self.advance(); + if self.recover_at_bad_escape() { + return; + } if end_char == '?' { if self.peek() != '>' { self.error(&self.unexpected_character_message()); return; } self.advance(); + if self.recover_at_bad_escape() { + return; + } } self.tokens.push(HtmlToken::with_part( HtmlTokenType::ProcessingInstruction, diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 68556ff80..c69c81884 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -1978,6 +1978,69 @@ mod processing_instructions { (vec![(pi("\"a\0b\""), 0, 10), (text("?>z"), 10, 13), (eof(), 13, 13)], vec![]) ); } + + #[test] + fn should_drop_the_instruction_at_a_bad_escape_after_it_like_angular() { + // Angular's cursor decodes an escape as soon as it moves onto it, so moving past the end of the instruction + // onto a bad escape throws before the token is emitted. + let invalid = |offset| ("Invalid hexadecimal escape sequence".to_string(), offset); + // Cut short by the end of the input: the input ends there. + assert_eq!(lex(r"\u{", true), (vec![(eof(), 13, 13)], vec![eof_error(13)])); + // Invalid digits: the cursor still peeks the backslash, read as text, then moves on from the escape's end. + assert_eq!( + lex(r"\xZZab", true), + ( + vec![ + (text("\\ab"), 5, 11), + ((HtmlTokenType::TagOpenStart, vec![String::new(), "b".to_string()]), 11, 13), + ((HtmlTokenType::TagOpenEnd, vec![]), 13, 14), + (eof(), 14, 14), + ], + vec![invalid(7)] + ) + ); + assert_eq!( + lex(r"\u{zz}{{a}}", true), + ( + vec![ + (text("\\"), 4, 10), + ( + ( + HtmlTokenType::Interpolation, + vec!["{{".to_string(), "a".to_string(), "}}".to_string()] + ), + 10, + 15 + ), + (text(""), 15, 15), + (eof(), 15, 15), + ], + vec![invalid(7)] + ) + ); + // Moving past the `?` of `?>` too. + assert_eq!( + lex(r"", true), + (vec![(text("\\>"), 4, 9), (eof(), 9, 9)], vec![invalid(6)]) + ); + // Invalid digits that end the input: the cursor then fails to move past them. + assert_eq!( + lex(r"\uZZZ", true), + (vec![(eof(), 10, 10)], vec![invalid(7), eof_error(10)]) + ); + // A good escape keeps the instruction, and so does a bad one after an escaped NUL in text, which ends the + // input. + assert_eq!( + lex(r"\u{41}", true), + (vec![(pi("x"), 0, 5), (text("A"), 5, 11), (eof(), 11, 11)], vec![]) + ); + assert_eq!(lex(r"\u{0}\u{", true), (vec![(eof(), 0, 0)], vec![])); + } } mod escaped_line_continuations { From b5cacf84c594203bca78cecce2f6a63247f03a76 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 16:37:40 +0800 Subject: [PATCH 04/47] fix(parser): report an escaped NUL as EOF and stop the lexer there like Angular Angular's EscapedCharacterCursor peeks an escaped NUL (\0, \x00, \u0000, \u{0}) as $EOF. So an "Unexpected character" error at one says "EOF", and the tokenize loop stops at it, putting the EOF token at the NUL. Our peek() reads an escaped NUL as U+FFFD, so the error said "Unexpected character \"\u{fffd}\"", and the loop went on lexing the rest as text, which the NUL post-pass then cut, leaving the EOF token at 0-0. Now the tokenize loop also stops at at_nul(), and unexpected_character_message (also used for `z': Angular: [EOF 4-4], 'Unexpected character "EOF"' @4 before: [EOF 0-0], 'Unexpected character "\u{fffd}"' @4 Same for '' (@4). Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 21 ++++------ .../tests/html_lexer_test.rs | 41 +++++++++++++++++++ 2 files changed, 48 insertions(+), 14 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index e31c38cb2..3a6e7edeb 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -779,8 +779,8 @@ impl<'a> HtmlLexer<'a> { pub fn tokenize(mut self) -> HtmlTokenizeResult { self.find_line_continuations(); self.skip_line_continuation(); - // Like Angular's loop, stop at a NUL: its cursor peeks one as `$EOF`. - while self.index < self.length && self.peek() != chars::EOF { + // Like Angular's loop, stop at a NUL, raw or escaped: its cursor peeks one as `$EOF`. + while self.index < self.length && self.peek() != chars::EOF && !self.at_nul() { self.scan_token(); } @@ -1233,9 +1233,10 @@ impl<'a> HtmlLexer<'a> { self.input[self.index as usize..].starts_with(s) } - /// Angular's `_unexpectedCharacterErrorMsg` for the character at the cursor. + /// Angular's `_unexpectedCharacterErrorMsg` for the character at the cursor. A NUL, raw or escaped, is `EOF`, + /// as Angular's cursor peeks it. fn unexpected_character_message(&self) -> String { - if self.index >= self.length || self.peek() == chars::EOF { + if self.index >= self.length || self.peek() == chars::EOF || self.at_nul() { "Unexpected character \"EOF\"".to_string() } else { format!("Unexpected character \"{}\"", self.peek()) @@ -1947,19 +1948,11 @@ impl<'a> HtmlLexer<'a> { if self.peek() == '-' { // `\u{", true), (vec![(eof(), 0, 0)], vec![])); } + + #[test] + fn should_report_an_escaped_nul_after_a_question_mark_as_eof() { + // Angular's cursor peeks an escaped NUL as EOF, and the loop stops there: the EOF token is at the NUL. + for nul in [r"\0", r"\x00", r"\u0000", r"\u{0}"] { + let input = format!("z"); + assert_eq!(lex(&input, true), (vec![(eof(), 4, 4)], vec![eof_error(4)]), "{input}"); + } + assert_eq!(lex("z", false), (vec![(eof(), 4, 4)], vec![eof_error(4)])); + assert_eq!(lex(r", Vec<(String, u32)>); + + /// Token types with their spans, and errors with their offsets. + fn lex(input: &str) -> Lexed { + let result = HtmlLexer::new(input).with_escaped_string(true).tokenize(); + let tokens = result.tokens.into_iter().map(|t| (t.token_type, t.start, t.end)).collect(); + (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect()) + } + + fn eof_error(offset: u32) -> (String, u32) { + ("Unexpected character \"EOF\"".to_string(), offset) + } + + #[test] + fn should_report_an_escaped_nul_in_a_closing_tag_as_eof() { + assert_eq!(lex(r""), (vec![(HtmlTokenType::Eof, 4, 4)], vec![eof_error(4)])); + } + + #[test] + fn should_report_an_escaped_nul_after_an_incomplete_comment_or_cdata_start_as_eof() { + assert_eq!(lex(r" Date: Fri, 4 Dec 2026 16:50:54 +0800 Subject: [PATCH 05/47] fix(parser): read an escape after a line continuation as is when a processing instruction ends Angular's EscapedCharacterCursor skips a line continuation it lands on and then reads the next character raw, without decoding it. So when the advance past a processing instruction's end lands on a continuation followed by a bad escape, nothing throws: the instruction is kept and the escape is text. With the line continuation and bad-escape fixes together, the bad-escape check looked at the raw backslash after the continuation and dropped the instruction. It now skips positions the cursor reads raw (reads_raw_at). Example, escaped '\\xZZ': Angular: [PI 'x' 0-7, Text '\xZZ' 7-11, EOF] before: [Text '\' 7-11, EOF], 'Invalid hexadecimal escape sequence' @9 Co-Authored-By: Claude Opus 5.5 --- .../oxc_angular_compiler/src/parser/html/lexer.rs | 4 ++++ .../oxc_angular_compiler/tests/html_lexer_test.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 3a6e7edeb..79e9b276a 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -1048,6 +1048,10 @@ impl<'a> HtmlLexer<'a> { return None; } let pos = self.index as usize; + // Right after a line continuation, the cursor reads a backslash as is: no escape starts there. + if self.reads_raw_at(pos) { + return None; + } let rest = self.input.get(pos..)?.strip_prefix('\\')?; let take_chars = |s: &str, n: usize| s.char_indices().nth(n).map_or(s.len(), |(i, _)| i); // The digits, and the escape's end (none when cut short by the end of the input). diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 7c01b3ff5..ec381cb9d 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2042,6 +2042,19 @@ mod processing_instructions { assert_eq!(lex(r"\u{0}\u{", true), (vec![(eof(), 0, 0)], vec![])); } + #[test] + fn should_keep_the_instruction_at_an_escape_after_a_line_continuation_like_angular() { + // After a line continuation, Angular's cursor reads a backslash as is, so a bad escape there drops nothing. + assert_eq!( + lex("\\\n\\xZZ", true).0, + [(pi("x"), 0, 7), (text("\\xZZ"), 7, 11), (eof(), 11, 11)] + ); + assert_eq!( + lex("\\\n\\u{", true).0, + [(pi("x"), 0, 6), (text("\\u{"), 6, 9), (eof(), 9, 9)] + ); + } + #[test] fn should_report_an_escaped_nul_after_a_question_mark_as_eof() { // Angular's cursor peeks an escaped NUL as EOF, and the loop stops there: the EOF token is at the NUL. From 9afe52b3cd65f88989b8284f1fbb1a2e789081b3 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 17:32:04 +0800 Subject: [PATCH 06/47] fix(parser): skip only the CR of a CRLF line continuation in escaped token text Token text was normalized before the escape pass, so a backslash and CRLF looked like a backslash and LF: the LF was lost and the escape after it was read as is. Keep the CR after a backslash so the escape pass skips only the backslash and CR, like Angular's cursor. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 57 +++++++++++++------ .../tests/html_lexer_test.rs | 9 +++ 2 files changed, 49 insertions(+), 17 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 79e9b276a..f601675b7 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -896,6 +896,29 @@ impl<'a> HtmlLexer<'a> { && matches!(self.input.as_bytes()[pos + 1], b'\n' | b'\r') } + /// Normalizes the line endings of token text. In an escaped string, a CR right after a backslash stays: it ends + /// a line continuation, which the escape pass skips with the backslash, reading the LF of a CRLF after it as text + /// like Angular's cursor. + fn normalize_line_endings(&self, text: &str) -> String { + if !self.escaped_string { + return normalize_line_endings(text); + } + let mut result = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(ch) = chars.next() { + match ch { + '\\' => { + result.push(ch); + result.extend(chars.next()); + } + '\r' if chars.peek() == Some(&'\n') => {} + '\r' => result.push('\n'), + _ => result.push(ch), + } + } + result + } + /// Whether the cursor reads the character at byte `pos` as is: it comes right after a line continuation. fn reads_raw_at(&self, pos: usize) -> bool { self.continuation_ends.binary_search(&pos).is_ok() @@ -1824,7 +1847,7 @@ impl<'a> HtmlLexer<'a> { if self.is_tag_start() { // End interpolation token without the closing marker let expr = &self.input[expr_start as usize..self.index as usize]; - let normalized_expr = normalize_line_endings(expr); + let normalized_expr = self.normalize_line_endings(expr); let parts = vec![self.interpolation_start.to_string(), normalized_expr]; self.tokens.push(HtmlToken::new( HtmlTokenType::Interpolation, @@ -1895,7 +1918,7 @@ impl<'a> HtmlLexer<'a> { // Create interpolation token with parts: [startMarker, expression, endMarker] // Normalize line endings in the expression (CRLF -> LF, CR -> LF) - let normalized_expr = normalize_line_endings(expr); + let normalized_expr = self.normalize_line_endings(expr); let parts = if has_end { vec![ self.interpolation_start.to_string(), @@ -2132,7 +2155,7 @@ impl<'a> HtmlLexer<'a> { // For escapable raw text, Angular ALWAYS emits a text token, even if empty. // This ensures entities are surrounded by text tokens. let text = &self.input[text_start as usize..saved_index as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2143,7 +2166,7 @@ impl<'a> HtmlLexer<'a> { // For raw text, only emit if there is actual content if content_start < saved_index { let content = &self.input[content_start as usize..saved_index as usize]; - let normalized = normalize_line_endings(content); + let normalized = self.normalize_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2180,7 +2203,7 @@ impl<'a> HtmlLexer<'a> { if consume_entities { if text_start < self.index { let text = &self.input[text_start as usize..self.index as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2190,7 +2213,7 @@ impl<'a> HtmlLexer<'a> { } } else if content_start < self.index { let content = &self.input[content_start as usize..self.index as usize]; - let normalized = normalize_line_endings(content); + let normalized = self.normalize_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2208,7 +2231,7 @@ impl<'a> HtmlLexer<'a> { // We emit the text token first, then try to scan the entity. // If entity scanning fails, we pop the text token and treat & as regular text. let text = &self.input[text_start as usize..self.index as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2360,7 +2383,7 @@ impl<'a> HtmlLexer<'a> { if close_name.eq_ignore_ascii_case(&expected_close) && self.peek() == '>' { // Found the closing tag - emit content let content = &self.input[content_start as usize..saved_index as usize]; - let normalized = normalize_line_endings(content); + let normalized = self.normalize_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2385,7 +2408,7 @@ impl<'a> HtmlLexer<'a> { if self.index >= self.length { // EOF reached - emit whatever content we have let content = &self.input[content_start as usize..self.index as usize]; - let normalized = normalize_line_endings(content); + let normalized = self.normalize_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2971,7 +2994,7 @@ impl<'a> HtmlLexer<'a> { }; if entity_start > text_start { let text = &self.input[text_start as usize..entity_start as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, &normalized, @@ -3019,7 +3042,7 @@ impl<'a> HtmlLexer<'a> { if self.starts_with(self.interpolation_start) { // Emit any accumulated text first (or empty text token if at start of interpolation) let text = &self.input[text_start as usize..self.index as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, &normalized, @@ -3110,7 +3133,7 @@ impl<'a> HtmlLexer<'a> { if self.scan_entity() { // Entity was matched - emit any text before it (may be empty) let text = &self.input[text_start as usize..entity_start as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); // Insert before the entity token we just added // Safety: scan_entity() pushes a token when returning true if let Some(entity_token) = self.tokens.pop() { @@ -3144,7 +3167,7 @@ impl<'a> HtmlLexer<'a> { // Emit remaining text (only if there's actual content since we already emit empty tokens after interp/entity) if self.index > text_start { let text = &self.input[text_start as usize..self.index as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, &normalized, @@ -3169,7 +3192,7 @@ impl<'a> HtmlLexer<'a> { self.advance(); } let content = &self.input[content_start as usize..self.index as usize]; - let normalized_content = normalize_line_endings(content); + let normalized_content = self.normalize_line_endings(content); // Emit content as RAW_TEXT self.tokens.push(HtmlToken::with_part( @@ -3277,7 +3300,7 @@ impl<'a> HtmlLexer<'a> { self.advance(); } let content = &self.input[content_start as usize..self.index as usize]; - let normalized = normalize_line_endings(content); + let normalized = self.normalize_line_endings(content); // Emit content as RAW_TEXT self.tokens.push(HtmlToken::with_part( @@ -3559,7 +3582,7 @@ impl<'a> HtmlLexer<'a> { // Emit any text before entity if entity_start > text_start { let text = &self.input[text_start as usize..entity_start as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::Text, &normalized, @@ -3594,7 +3617,7 @@ impl<'a> HtmlLexer<'a> { // Emit remaining text if self.index > text_start { let text = &self.input[text_start as usize..self.index as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_line_endings(text); // Apply leading trivia calculation for source map accuracy let (adjusted_start, full_start) = self.calculate_start_with_trivia(text_start, self.index); diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index ec381cb9d..c8f207ce5 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2096,6 +2096,15 @@ mod escaped_line_continuations { assert_eq!(lex("a\\\n\\\nb"), (vec![text("a\\\nb", 0, 6), eof(6)], vec![])); } + #[test] + fn should_skip_only_the_cr_of_a_crlf() { + // The LF is read as is, and an escape after it is decoded. + assert_eq!(lex("a\\\r\nb"), (vec![text("a\nb", 0, 5), eof(5)], vec![])); + assert_eq!(lex("a\\\r\n\\x41"), (vec![text("a\nA", 0, 8), eof(8)], vec![])); + // An escaped NUL there ends the input: the bad escape after it is not read. + assert_eq!(lex("a\\\r\n\\x00\\xzz").1, []); + } + #[test] fn should_report_nothing_after_an_escaped_nul_in_text() { // Angular's text ends at the NUL, which ends the input: the open tag after it is not read. From ab95dbab7e4fb8aa64f6f99cf9e1138c10dced41 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 17:50:21 +0800 Subject: [PATCH 07/47] fix(parser): count escape digits in UTF-16 units like Angular's cursor Angular's cursor reads the digits of \x and \u by UTF-16 units, so an emoji is both digits of \x. Read every code-point escape in one helper, code_point_escape, which the cursor checks and the bad-escape check share, and drop hex_is_nan for parse_int_prefix, which now skips a sign too. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 133 ++++++++++-------- .../tests/html_lexer_test.rs | 18 +++ 2 files changed, 90 insertions(+), 61 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index f601675b7..feee0e666 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -48,12 +48,57 @@ enum EscapeError { InvalidHex { digits: u32, end: Option }, } -/// Whether JavaScript's `parseInt(digits, 16)` is NaN: no hex digit after leading whitespace, a sign and `0x`. -fn hex_is_nan(digits: &str) -> bool { - let digits = digits.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}'); - let digits = digits.strip_prefix(['+', '-']).unwrap_or(digits); - let digits = digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0X")).unwrap_or(digits); - !digits.starts_with(|c: char| c.is_ascii_hexdigit()) +/// A code-point escape as Angular's `EscapedCharacterCursor` reads it (see `code_point_escape`). +#[derive(Debug, Clone, Copy)] +struct CodePointEscape { + /// Byte offset of the digits, from the backslash. + digits: usize, + /// Length in bytes, up to the end of the text when the escape is cut short. + len: usize, + /// The code point `parseInt` reads from the digits; none when it is NaN or `eof` is set. + value: Option, + /// Whether the cursor can move past the escape: false when the text ends inside it. + complete: bool, + /// Whether the cursor runs into the end of the text before it reads the digits, and throws EOF. + eof: bool, +} + +/// The code-point escape at the start of `text` (a backslash), as Angular's `EscapedCharacterCursor` reads it: +/// `\u{...}` up to the next `}`, `\u` plus 4 UTF-16 units, `\x` plus 2, or up to three octal digits. None for any +/// other escape. +/// +/// The cursor moves onto the last digit of `\u` and `\x`, so the text may end one unit short: then the escape still +/// has a value, but is not complete. The value is not checked: it can be 0, a surrogate, or out of range. +fn code_point_escape(text: &str) -> Option { + let rest = text.strip_prefix('\\')?; + let escape = |digits: usize, len: usize, value: Option, complete: bool, eof: bool| { + Some(CodePointEscape { digits, len, value: value.filter(|_| !eof), complete, eof }) + }; + if let Some(braced) = rest.strip_prefix("u{") { + return match braced.find('}') { + Some(end) => escape(3, 4 + end, parse_int_prefix(&braced[..end], 16), true, false), + None => escape(3, text.len(), None, false, true), + }; + } + if let Some((fixed, width)) = + rest.strip_prefix('u').map(|s| (s, 4)).or_else(|| rest.strip_prefix('x').map(|s| (s, 2))) + { + // The first `width` UTF-16 units, as JavaScript's `slice` takes them (a split character is kept whole). + let mut units = 0; + let end = fixed + .char_indices() + .find(|&(_, ch)| { + let done = units >= width; + units += ch.len_utf16(); + done + }) + .map_or(fixed.len(), |(i, _)| i); + let units = fixed[..end].encode_utf16().count(); + let value = parse_int_prefix(&fixed[..end], 16); + return escape(2, 2 + end, value, units >= width, units + 1 < width); + } + let octal = rest.bytes().take(3).take_while(|b| (b'0'..=b'7').contains(b)).count(); + (octal > 0).then(|| escape(1, 1 + octal, parse_int_prefix(&rest[..octal], 8), true, false))? } /// Token types for HTML templates. @@ -273,9 +318,6 @@ fn offsets_to_positions(input: &str, offsets: &[u32]) -> Vec<(u32, u32)> { positions } -/// The value JavaScript's `parseInt(digits, radix)` gives, for the non-negative values a character can have: -/// leading whitespace and a `+` are skipped, a `0x` prefix is allowed in base 16, and the longest run of digits -/// counts. /// Splits an attribute name into its namespace prefix and local name, like /// Angular's `_consumePrefixAndName`: the prefix is the run of ASCII letters and /// digits at the start, and only counts when a `:` follows it. So `xlink:href` @@ -290,9 +332,12 @@ fn split_attr_ns_prefix(name: &str) -> (&str, &str) { } } +/// The value JavaScript's `parseInt(digits, radix)` gives, for the values a character can have: leading whitespace +/// and a sign are skipped (`-0` is 0, which the cursor reads as NUL too), a `0x` prefix is allowed in base 16, and +/// the longest run of digits counts. None when it is NaN. fn parse_int_prefix(digits: &str, radix: u32) -> Option { let digits = digits.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}'); - let digits = digits.strip_prefix('+').unwrap_or(digits); + let digits = digits.strip_prefix(['+', '-']).unwrap_or(digits); let digits = if radix == 16 { digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0X")).unwrap_or(digits) } else { @@ -1019,34 +1064,14 @@ impl<'a> HtmlLexer<'a> { Some((ch.unwrap_or(char::REPLACEMENT_CHARACTER), len)) } - /// A code-point escape at byte `pos` (a backslash), with the length Angular's `EscapedCharacterCursor` gives it: - /// `\u{...}` up to the next `}`, `\u` plus 4 characters, `\x` plus 2, or up to three octal digits. Returns the - /// code point (none when the escape has no digits or is cut short by the end of the input) and the escape's - /// length in bytes; none for any other escape. + /// A code-point escape at byte `pos` (a backslash), with the length Angular's `EscapedCharacterCursor` gives it + /// (see `code_point_escape`). Returns the code point (none when the digits are NaN or the escape is cut short by + /// the end of the input) and the escape's length in bytes; none for any other escape. /// - /// The digits are read like JavaScript's `parseInt`, so `\u{41zz}` is `A`. The code point is not checked: it - /// can be 0, a surrogate, or out of range. + /// The digits are read like JavaScript's `parseInt`, so `\u{41zz}` is `A`. fn code_point_escape_value_at(&self, pos: usize) -> Option<(Option, usize)> { - let rest = self.input.get(pos..)?.strip_prefix('\\')?; - let take_chars = |s: &str, n: usize| s.char_indices().nth(n).map_or(s.len(), |(i, _)| i); - let (digits, radix, len, complete) = if let Some(braced) = rest.strip_prefix("u{") { - let digits = braced.find('}').map_or(braced, |end| &braced[..end]); - let closed = digits.len() < braced.len(); - (digits, 16, 3 + digits.len() + usize::from(closed), closed) - } else if let Some(fixed) = rest.strip_prefix('u') { - let digits = &fixed[..take_chars(fixed, 4)]; - (digits, 16, 2 + digits.len(), digits.chars().count() == 4) - } else if let Some(fixed) = rest.strip_prefix('x') { - let digits = &fixed[..take_chars(fixed, 2)]; - (digits, 16, 2 + digits.len(), digits.chars().count() == 2) - } else { - let octal = rest.bytes().take(3).take_while(|b| (b'0'..=b'7').contains(b)).count(); - if octal == 0 { - return None; - } - (&rest[..octal], 8, 1 + octal, true) - }; - Some((parse_int_prefix(digits, radix).filter(|_| complete), len)) + let escape = code_point_escape(self.input.get(pos..)?)?; + Some((escape.value.filter(|_| escape.complete), escape.len)) } /// Whether the cursor is at a raw or escaped NUL, which Angular's cursor peeks as EOF but can move past. @@ -1064,7 +1089,7 @@ impl<'a> HtmlLexer<'a> { } /// The error Angular's `EscapedCharacterCursor` throws when it moves onto the escape at the cursor, if any. It - /// decodes the escape at once: `\u{` with no `}` after it, `\u` with fewer than 3 characters after it and `\x` + /// decodes the escape at once: `\u{` with no `}` after it, `\u` with fewer than 3 UTF-16 units after it and `\x` /// with none run into the end of the input, and digits `parseInt` reads as NaN are invalid. fn cursor_escape_error(&self) -> Option { if !self.escaped_string { @@ -1075,32 +1100,18 @@ impl<'a> HtmlLexer<'a> { if self.reads_raw_at(pos) { return None; } - let rest = self.input.get(pos..)?.strip_prefix('\\')?; - let take_chars = |s: &str, n: usize| s.char_indices().nth(n).map_or(s.len(), |(i, _)| i); - // The digits, and the escape's end (none when cut short by the end of the input). - let (digits_start, digits, end) = if let Some(braced) = rest.strip_prefix("u{") { - let Some(close) = braced.find('}') else { return Some(EscapeError::Eof) }; - (pos + 3, &braced[..close], Some(pos + 4 + close)) - } else if let Some((fixed, width)) = rest - .strip_prefix('u') - .map(|s| (s, 4)) - .or_else(|| rest.strip_prefix('x').map(|s| (s, 2))) - { - // The cursor moves onto the last digit, so the input may end one character short. - let digits = &fixed[..take_chars(fixed, width)]; - let count = digits.chars().count(); - if count + 1 < width { - return Some(EscapeError::Eof); - } - (pos + 2, digits, (count == width).then_some(pos + 2 + digits.len())) - } else { - return None; - }; - if !hex_is_nan(digits) { + let escape = code_point_escape(self.input.get(pos..)?)?; + if escape.eof { + return Some(EscapeError::Eof); + } + if escape.value.is_some() { return None; } - let digits = u32::try_from(digits_start).ok()?; - Some(EscapeError::InvalidHex { digits, end: end.and_then(|end| u32::try_from(end).ok()) }) + let at = |offset: usize| u32::try_from(pos + offset).ok(); + Some(EscapeError::InvalidHex { + digits: at(escape.digits)?, + end: if escape.complete { at(escape.len) } else { None }, + }) } /// Moves the cursor to byte `target`, counting lines and columns over the raw characters. diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index c8f207ce5..4974c3a10 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2042,6 +2042,24 @@ mod processing_instructions { assert_eq!(lex(r"\u{0}\u{", true), (vec![(eof(), 0, 0)], vec![])); } + #[test] + fn should_count_escape_digits_in_utf16_units_like_angular() { + // `\x` takes 2 UTF-16 units and `\u` 4, so an emoji is both digits of `\x`. Offsets are in bytes. + let invalid = |offset| ("Invalid hexadecimal escape sequence".to_string(), offset); + assert_eq!( + lex("\\xšŸ˜€", true), + (vec![(text("\\"), 5, 11), (eof(), 11, 11)], vec![invalid(7)]) + ); + assert_eq!( + lex("\\xšŸ˜€a", true), + (vec![(text("\\a"), 5, 12), (eof(), 12, 12)], vec![invalid(7)]) + ); + assert_eq!( + lex("\\uĆ©šŸ˜€a", true), + (vec![(text("\\"), 5, 14), (eof(), 14, 14)], vec![invalid(7)]) + ); + } + #[test] fn should_keep_the_instruction_at_an_escape_after_a_line_continuation_like_angular() { // After a line continuation, Angular's cursor reads a backslash as is, so a bad escape there drops nothing. From 87c5ad49e795691f0256eb0a38ab72085544cbb6 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 17:59:22 +0800 Subject: [PATCH 08/47] fix(parser): decode escapes in token text like Angular's cursor The pass that decodes escapes in token text after lexing now reads them as Angular's cursor does: - A token part that starts right after a line continuation reads its first character as is, so its escape is not decoded. - Code-point escapes use code_point_escape: parseInt digits (\x0\ is NUL), and invalid digits read as one backslash of text. - An escape cut short by the end of the input drops its token and reports one EOF error at the end, not a second one next to the lexer's. - Error offsets count from the part, so an interpolation's are right. The old decoder had a hidden nul! macro for its many NUL cases; the shared helper leaves one. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 334 ++++++------------ .../tests/html_lexer_test.rs | 78 ++++ 2 files changed, 191 insertions(+), 221 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index feee0e666..f95fe27a6 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -48,6 +48,9 @@ enum EscapeError { InvalidHex { digits: u32, end: Option }, } +/// The error Angular reports when its cursor moves past the end of the input. +const EOF_ERROR: &str = "Unexpected character \"EOF\""; + /// A code-point escape as Angular's `EscapedCharacterCursor` reads it (see `code_point_escape`). #[derive(Debug, Clone, Copy)] struct CodePointEscape { @@ -349,231 +352,84 @@ fn parse_int_prefix(digits: &str, radix: u32) -> Option { /// Processes escape sequences in text when in "escaped strings" mode. /// This is used when tokenize_expansion_forms is false (Angular's default for inline templates). -/// Returns (processed_text, errors, encountered_null). +/// Returns (processed_text, errors, encountered_null), with error offsets in bytes into `text`. /// When a null character (\0) is encountered, everything after it is discarded (EOF behavior), /// unless `keep_nul` is set: then it decodes to `\0` and the text goes on. -fn process_escape_sequences(text: &str, keep_nul: bool) -> (String, Vec<(String, usize)>, bool) { +/// Code-point escapes are read as Angular's cursor reads them (see `code_point_escape`): one cut short by the end of +/// the text is an EOF error there, unless it is NUL. +/// With `first_raw`, the first character is read as is, as Angular's cursor reads one after a line continuation. +fn process_escape_sequences( + text: &str, + keep_nul: bool, + first_raw: bool, +) -> (String, Vec<(String, usize)>, bool) { let mut result = String::with_capacity(text.len()); let mut errors = Vec::new(); - let chars: Vec = text.chars().collect(); let mut i = 0; - let mut encountered_null = false; - - // An escaped NUL that ends at `next`: kept as `\0` with `keep_nul`, else the end of the text. - macro_rules! nul { - ($next:expr) => {{ - if keep_nul { + if first_raw && let Some(ch) = text.chars().next() { + result.push(ch); + i = ch.len_utf8(); + } + while let Some(ch) = text[i..].chars().next() { + let next = text[i..].strip_prefix('\\').and_then(|rest| rest.chars().next()); + let Some(next) = next else { + result.push(ch); + i += ch.len_utf8(); + continue; + }; + if let Some(escape) = code_point_escape(&text[i..]) { + if escape.value == Some(0) { + // An escaped NUL: Angular's cursor peeks it as EOF + if !keep_nul { + return (result, errors, true); + } result.push('\0'); - i = $next; + i += escape.len; continue; } - encountered_null = true; - break; - }}; - } - - while i < chars.len() { - if chars[i] == '\\' && i + 1 < chars.len() { - let next = chars[i + 1]; - match next { - // Standard escape sequences - '\'' | '"' | '`' | '\\' => { - result.push(next); - i += 2; - } - 'n' => { - result.push('\n'); - i += 2; - } - 'r' => { - // \r gets normalized to \n - result.push('\n'); - i += 2; - } - 'v' => { - result.push('\x0B'); - i += 2; - } - 't' => { - result.push('\t'); - i += 2; - } - 'b' => { - result.push('\x08'); - i += 2; - } - 'f' => { - result.push('\x0C'); - i += 2; - } - '0' => { - // \0 is null character - treat as EOF (everything after is discarded) - // But if followed by more octal digits (1-7), it might produce a non-null value - if i + 2 < chars.len() && ('0'..='7').contains(&chars[i + 2]) { - // Could be octal like \001, \007, \077 - let mut octal = String::new(); - let mut j = i + 1; // Start from the first '0' - while j < chars.len() && octal.len() < 3 && ('0'..='7').contains(&chars[j]) - { - octal.push(chars[j]); - j += 1; - } - if let Ok(code) = u8::from_str_radix(&octal, 8) { - if code > 0 { - result.push(code as char); - } else { - // Result is null - treat as EOF - nul!(j); - } - } - i = j; - } else if i + 2 < chars.len() && chars[i + 2].is_ascii_digit() { - // \0 followed by 8 or 9 - \0 is null (EOF), stop processing - nul!(i + 2); - } else { - // Just \0 - null character, treat as EOF - nul!(i + 2); - } - } - '1'..='7' => { - // Octal escape sequence - let mut octal = String::new(); - let mut j = i + 1; - while j < chars.len() && octal.len() < 3 && ('0'..='7').contains(&chars[j]) { - octal.push(chars[j]); - j += 1; - } - if let Ok(code) = u8::from_str_radix(&octal, 8) { - if code > 0 { - result.push(code as char); - } else { - // Null character - treat as EOF - nul!(j); - } - } - i = j; - } - '8' | '9' => { - // Invalid octal - treat as literal - result.push(next); - i += 2; - } - 'x' => { - // Hex escape sequence: \xNN - if i + 3 < chars.len() - && chars[i + 2].is_ascii_hexdigit() - && chars[i + 3].is_ascii_hexdigit() - { - let hex: String = chars[i + 2..i + 4].iter().collect(); - if let Ok(code) = u8::from_str_radix(&hex, 16) { - if code > 0 { - result.push(code as char); - } else { - // Null character - treat as EOF - nul!(i + 4); - } - } - i += 4; - } else if i + 2 >= chars.len() { - // Hit EOF after \x - errors.push(("Unexpected character \"EOF\"".to_string(), i + 2)); - result.push('\\'); - result.push('x'); - i += 2; - } else { - // Invalid hex characters after \x - errors.push(("Invalid hexadecimal escape sequence".to_string(), i + 2)); - result.push('\\'); - result.push('x'); - i += 2; - } - } - 'u' => { - // Unicode escape sequence: \uNNNN or \u{N...} - if i + 2 < chars.len() && chars[i + 2] == '{' { - // Variable length Unicode: \u{N...} - let mut j = i + 3; - let mut hex = String::new(); - while j < chars.len() && chars[j] != '}' && chars[j].is_ascii_hexdigit() { - hex.push(chars[j]); - j += 1; - } - if j < chars.len() && chars[j] == '}' && !hex.is_empty() { - if let Ok(code) = u32::from_str_radix(&hex, 16) { - if code == 0 { - // Null character - treat as EOF - nul!(j + 1); - } - if let Some(ch) = char::from_u32(code) { - result.push(ch); - } - } - i = j + 1; - } else if j >= chars.len() { - // Hit EOF - errors.push(("Unexpected character \"EOF\"".to_string(), i + 3)); - result.push('\\'); - result.push('u'); - i += 2; - } else { - // Invalid characters (like \u{GG}) - errors.push(("Invalid hexadecimal escape sequence".to_string(), i + 3)); - result.push('\\'); - result.push('u'); - i += 2; - } - } else if i + 5 < chars.len() { - // Fixed length Unicode: \uNNNN - let valid = chars[i + 2..i + 6].iter().all(|c| c.is_ascii_hexdigit()); - if valid { - let hex: String = chars[i + 2..i + 6].iter().collect(); - if let Ok(code) = u32::from_str_radix(&hex, 16) { - if code == 0 { - // Null character - treat as EOF - nul!(i + 6); - } - if let Some(ch) = char::from_u32(code) { - result.push(ch); - } - } - i += 6; - } else { - // Invalid characters (like \uGGGG) - errors.push(("Invalid hexadecimal escape sequence".to_string(), i + 2)); - result.push('\\'); - result.push('u'); - i += 2; - } - } else { - // Incomplete sequence (hit EOF) - errors.push(("Unexpected character \"EOF\"".to_string(), i + 2)); - result.push('\\'); - result.push('u'); - i += 2; - } - } - '\n' | '\r' => { - // A line continuation: as Angular's cursor, skip the backslash and one CR or LF (so a CRLF - // leaves its LF), and read the character after it as is. - i += 2; - if let Some(&ch) = chars.get(i) { - result.push(ch); - i += 1; - } + match escape.value { + Some(value) if escape.complete => result.extend(char::from_u32(value)), + // Invalid digits: Angular reads the escape as a `\` of text + None if !escape.eof => { + errors.push(( + "Invalid hexadecimal escape sequence".to_string(), + i + escape.digits, + )); + result.push('\\'); } + // The text ends inside the escape _ => { - // Unknown escape - just use the character after backslash + errors.push((EOF_ERROR.to_string(), text.len())); + result.push('\\'); result.push(next); i += 2; + continue; + } + } + i += escape.len; + continue; + } + i += 1 + next.len_utf8(); + match next { + 'n' | 'r' => result.push('\n'), // \r gets normalized to \n + 'v' => result.push('\x0B'), + 't' => result.push('\t'), + 'b' => result.push('\x08'), + 'f' => result.push('\x0C'), + '\n' | '\r' => { + // A line continuation: as Angular's cursor, skip the backslash and one CR or LF (so a CRLF + // leaves its LF), and read the character after it as is. + if let Some(ch) = text[i..].chars().next() { + result.push(ch); + i += ch.len_utf8(); } } - } else { - result.push(chars[i]); - i += 1; + // Any other escaped character, quotes and backslashes too, is itself + _ => result.push(next), } } - (result, errors, encountered_null) + (result, errors, false) } /// Merges adjacent text tokens and adjacent attribute value text tokens. @@ -840,6 +696,7 @@ impl<'a> HtmlLexer<'a> { let mut errors_to_add: Vec<(String, u32)> = Vec::new(); let mut null_encountered = false; let mut null_token_idx = None; + let mut cut_short_token = None; for (token_idx, token) in tokens.iter_mut().enumerate() { if null_encountered { @@ -849,13 +706,45 @@ impl<'a> HtmlLexer<'a> { // Angular's cursor peeks a NUL as EOF but can move past it. Its processing instruction scan reaches // one only inside quotes, which it moves past, so the NUL stays in the content and lexing goes on. let keep_nul = token.token_type == HtmlTokenType::ProcessingInstruction; + // Where each part starts: at the token start, but the content of an interpolation, a processing + // instruction or a doctype after its start marker and a line continuation there. Angular's cursor + // reads the character after one as is. + let start = token.effective_full_start() as usize; + let (content_idx, marker_len) = match token.token_type { + HtmlTokenType::Interpolation | HtmlTokenType::AttrValueInterpolation => { + (1, token.parts.first().map_or(0, String::len)) + } + HtmlTokenType::ProcessingInstruction | HtmlTokenType::DocType => (0, 2), + _ => (0, 0), + }; + let marker_end = start + marker_len; + let after_continuation = marker_len > 0 && self.is_line_continuation_at(marker_end); + let content_start = marker_end + if after_continuation { 2 } else { 0 }; // Process escape sequences in token parts - for part in &mut token.parts { - let (processed, errs, has_null) = process_escape_sequences(part, keep_nul); + for (part_idx, part) in token.parts.iter_mut().enumerate() { + let part_start = if part_idx == content_idx { content_start } else { start }; + let first_raw = part.starts_with('\\') && self.reads_raw_at(part_start); + let (processed, errs, has_null) = + process_escape_sequences(part, keep_nul, first_raw); *part = processed; + // An escape cut short by the end of the input throws an EOF error there in Angular, which may be + // the one the lexer reports: the token is lost, and the input ends. + let mut cut_short = false; for (msg, offset) in errs { - // The error offset is relative to the token start - errors_to_add.push((msg, token.start + offset as u32)); + let offset = if msg == EOF_ERROR { + cut_short = true; + token.end + } else { + part_start as u32 + offset as u32 + }; + if !self.errors.iter().any(|e| e.offset == offset && e.msg == msg) { + errors_to_add.push((msg, offset)); + } + } + if cut_short { + cut_short_token = Some((token_idx, token.end)); + null_encountered = true; + break; } if has_null { null_encountered = true; @@ -871,6 +760,10 @@ impl<'a> HtmlLexer<'a> { } } + if let Some((idx, end)) = cut_short_token { + tokens.truncate(idx); + tokens.push(HtmlToken::empty(HtmlTokenType::Eof, end, end)); + } // If null was encountered, truncate tokens after that point and ensure EOF is present if let Some(idx) = null_token_idx { // Keep tokens up to and including the null token @@ -1139,7 +1032,7 @@ impl<'a> HtmlLexer<'a> { let Some(error) = self.cursor_escape_error() else { return false }; let past_nul = self.tokens.iter().any(|t| { t.token_type == HtmlTokenType::Text - && t.parts.iter().any(|p| process_escape_sequences(p, false).2) + && t.parts.iter().any(|p| process_escape_sequences(p, false, false).2) }); if past_nul { return false; @@ -3879,15 +3772,16 @@ mod tests { 0, ), ("\\u{zz}", &[Text, Eof][..], 1), - ("\\x7}", &[Text, Eof][..], 1), + // `parseInt("7}", 16)` is 7. + ("\\x7}", &[Text, Eof][..], 0), ("\\u{7b}{a}}", &[Text, Interpolation, Text, Eof][..], 0), ("{{ \\u{7d}}", &[Text, Interpolation, Text, Eof][..], 0), ("&\\x3b", &[Text, EncodedEntity, Text, Eof][..], 0), ("\\x26amp;", &[Text, EncodedEntity, Text, Eof][..], 0), ("\\x3c\\x21-- x -->", &[CommentStart, RawText, CommentEnd, Eof][..], 0), ("a \\x3c\\ud83d\\ude00 b", &[Text, Eof][..], 0), - // Cut short by the end of the input, as Angular's cursor reports it. - ("a\\u{7d", &[Text, Eof][..], 1), + // Cut short by the end of the input, as Angular's cursor reports it: the text is lost. + ("a\\u{7d", &[Eof][..], 1), ] { let result = HtmlLexer::new(input).with_escaped_string(true).tokenize(); let found: Vec<_> = result.tokens.iter().map(|t| t.token_type).collect(); @@ -3946,11 +3840,9 @@ mod tests { [ ("Invalid hexadecimal escape sequence", (0, 14), 14), ("Invalid hexadecimal escape sequence", (0, 19), 19), - ("Invalid hexadecimal escape sequence", (0, 26), 26), - ("Invalid hexadecimal escape sequence", (1, 4), 33), - ("Invalid hexadecimal escape sequence", (3, 0), 39), - ("Invalid hexadecimal escape sequence", (3, 4), 43), - ("Invalid hexadecimal escape sequence", (4, 1), 55), + ("Invalid hexadecimal escape sequence", (1, 5), 34), + ("Invalid hexadecimal escape sequence", (3, 1), 40), + ("Unexpected character \"EOF\"", (5, 0), 58), ] ); } diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 4974c3a10..764dfbcd6 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2114,6 +2114,34 @@ mod escaped_line_continuations { assert_eq!(lex("a\\\n\\\nb"), (vec![text("a\\\nb", 0, 6), eof(6)], vec![])); } + #[test] + fn should_read_a_backslash_starting_a_token_after_it_as_is() { + // The token starts after the line continuation, and its escape is not decoded. + assert_eq!(lex("\\\n\\x41"), (vec![text("\\x41", 2, 6), eof(6)], vec![])); + let block_close = (HtmlTokenType::BlockClose, vec![], 6, 7); + assert_eq!(lex("\\\n\\u{0}"), (vec![text("\\u{0", 2, 6), block_close, eof(7)], vec![])); + let parts = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + assert_eq!( + lex("").0[3], + (HtmlTokenType::AttrValueText, parts(&["\\x41"]), 8, 12) + ); + assert_eq!( + lex("").0[1], + (HtmlTokenType::RawText, parts(&["\\x41"]), 6, 10) + ); + // After a start marker too. + let interpolation = (HtmlTokenType::Interpolation, parts(&["{{", "\\u{", "}}"]), 0, 9); + assert_eq!( + lex("{{\\\n\\u{}}"), + (vec![text("", 0, 0), interpolation, text("", 9, 9), eof(9)], vec![]) + ); + let pi = (HtmlTokenType::ProcessingInstruction, parts(&["\\x0--"]), 0, 10); + assert_eq!(lex(""), (vec![pi, eof(10)], vec![])); + // And after a processing instruction that ends in error. + let unexpected = ("Unexpected character \"\\\"".to_string(), 6); + assert_eq!(lex(""), (vec![text("\\xZZ>", 6, 11), eof(11)], vec![unexpected])); + } + #[test] fn should_skip_only_the_cr_of_a_crlf() { // The LF is read as is, and an escape after it is decoded. @@ -2131,6 +2159,56 @@ mod escaped_line_continuations { } } +/// Code-point escapes (`\x`, `\u`, `\u{...}`) in the text of tokens, read as Angular's cursor reads them. Expected +/// values are from Angular 22.3.0. +mod escaped_code_points { + use super::*; + + type Token = (HtmlTokenType, Vec, u32, u32); + type Lexed = (Vec, Vec<(String, u32)>); + + /// Tokens with their spans, and errors with their offsets, of an escaped string. + fn lex(input: &str) -> Lexed { + let result = HtmlLexer::new(input).with_escaped_string(true).tokenize(); + let tokens = + result.tokens.into_iter().map(|t| (t.token_type, t.parts, t.start, t.end)).collect(); + (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect()) + } + + fn text(value: &str, start: u32, end: u32) -> Token { + (HtmlTokenType::Text, vec![value.to_string()], start, end) + } + + fn eof(offset: u32) -> Token { + (HtmlTokenType::Eof, vec![], offset, offset) + } + + fn eof_error(offset: u32) -> (String, u32) { + ("Unexpected character \"EOF\"".to_string(), offset) + } + + #[test] + fn should_read_the_digits_like_parse_int() { + // `parseInt("0\\", 16)` is 0: an escaped NUL, which ends the text. + let (tokens, errors) = lex(r"a\x0\b"); + assert_eq!((&tokens[0].1, errors), (&vec!["a".to_string()], vec![])); + } + + #[test] + fn should_read_invalid_digits_as_a_backslash() { + let invalid = ("Invalid hexadecimal escape sequence".to_string(), 2); + assert_eq!(lex(r"\xzzb"), (vec![text("\\b", 0, 5), eof(5)], vec![invalid])); + } + + #[test] + fn should_drop_the_token_at_an_escape_cut_short_by_the_end_of_the_input() { + // Angular's cursor throws inside the token: it is lost, and the error is the one at the end of the input. + assert_eq!(lex(r"a\u{12"), (vec![eof(6)], vec![eof_error(6)])); + assert_eq!(lex(r"{{a\u{"), (vec![text("", 0, 0), eof(6)], vec![eof_error(6)])); + assert_eq!(lex(r#" Date: Fri, 4 Dec 2026 18:11:44 +0800 Subject: [PATCH 09/47] fix(parser): peek an escaped NUL as EOF like Angular's cursor The cursor read an escaped NUL as U+FFFD, so every scan went on past it and the escape pass cut the tokens later, leaving the lexer's errors from after the NUL. Angular's cursor peeks it as EOF: read it as chars::EOF, as a raw NUL is, so each scan stops there where Angular's does and the lexer stops after it. A bad escape after {{\0}}, @if (\0), @let a = \0, or a tag name with \0 is then not read, and text ends at the NUL. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 30 +++++++++---------- .../tests/html_lexer_test.rs | 30 +++++++++++++++++-- 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index f95fe27a6..95b6bd39a 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -681,7 +681,7 @@ impl<'a> HtmlLexer<'a> { self.find_line_continuations(); self.skip_line_continuation(); // Like Angular's loop, stop at a NUL, raw or escaped: its cursor peeks one as `$EOF`. - while self.index < self.length && self.peek() != chars::EOF && !self.at_nul() { + while self.index < self.length && self.peek() != chars::EOF { self.scan_token(); } @@ -948,12 +948,13 @@ impl<'a> HtmlLexer<'a> { /// A code-point escape at byte `pos` (a backslash), read as one character by `code_point_escape_value_at`. /// Returns the character and the escape's length in bytes; none for any other escape. /// - /// An escape with no digits, one cut short by the end of the input, a surrogate, or NUL (the cursor's end of - /// input) reads as U+FFFD, which is no structural character: the escape stays inside its token, whose text - /// `process_escape_sequences` decodes, reporting the invalid ones and ending the text at NUL. + /// NUL reads as `chars::EOF`, as Angular's cursor peeks it, so a scan stops there where Angular's does. An escape + /// with no digits, one cut short by the end of the input, or a surrogate reads as U+FFFD, which is no structural + /// character: the escape stays inside its token, whose text `process_escape_sequences` decodes, reporting the + /// invalid ones. fn code_point_escape_at(&self, pos: usize) -> Option<(char, usize)> { let (value, len) = self.code_point_escape_value_at(pos)?; - let ch = value.and_then(char::from_u32).filter(|&ch| ch != '\0'); + let ch = value.and_then(char::from_u32); Some((ch.unwrap_or(char::REPLACEMENT_CHARACTER), len)) } @@ -968,17 +969,14 @@ impl<'a> HtmlLexer<'a> { } /// Whether the cursor is at a raw or escaped NUL, which Angular's cursor peeks as EOF but can move past. - /// `peek` reads an escaped NUL as U+FFFD. False at the end of the input, and at a backslash that ends an - /// escaped string: Angular peeks EOF there too, but moving past it is the end of the input. + /// False at the end of the input, and at a backslash that ends an escaped string: Angular peeks EOF there too, + /// but moving past it is the end of the input. fn at_nul(&self) -> bool { - let pos = self.index as usize; - if self.escaped_string && self.raw_peek() == '\\' && !self.reads_raw_at(pos) { - pos + 1 < self.length as usize - && (self.peek() == chars::EOF - || matches!(self.code_point_escape_value_at(pos), Some((Some(0), _)))) - } else { - self.index < self.length && self.peek() == chars::EOF - } + let trailing_backslash = self.escaped_string + && self.index + 1 == self.length + && self.raw_peek() == '\\' + && !self.reads_raw_at(self.index as usize); + self.index < self.length && self.peek() == chars::EOF && !trailing_backslash } /// The error Angular's `EscapedCharacterCursor` throws when it moves onto the escape at the cursor, if any. It @@ -1167,7 +1165,7 @@ impl<'a> HtmlLexer<'a> { /// Angular's `_unexpectedCharacterErrorMsg` for the character at the cursor. A NUL, raw or escaped, is `EOF`, /// as Angular's cursor peeks it. fn unexpected_character_message(&self) -> String { - if self.index >= self.length || self.peek() == chars::EOF || self.at_nul() { + if self.index >= self.length || self.peek() == chars::EOF { "Unexpected character \"EOF\"".to_string() } else { format!("Unexpected character \"{}\"", self.peek()) diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 764dfbcd6..6fc162182 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2033,13 +2033,11 @@ mod processing_instructions { lex(r"\uZZZ", true), (vec![(eof(), 10, 10)], vec![invalid(7), eof_error(10)]) ); - // A good escape keeps the instruction, and so does a bad one after an escaped NUL in text, which ends the - // input. + // A good escape keeps the instruction. assert_eq!( lex(r"\u{41}", true), (vec![(pi("x"), 0, 5), (text("A"), 5, 11), (eof(), 11, 11)], vec![]) ); - assert_eq!(lex(r"\u{0}\u{", true), (vec![(eof(), 0, 0)], vec![])); } #[test] @@ -2154,6 +2152,7 @@ mod escaped_line_continuations { #[test] fn should_report_nothing_after_an_escaped_nul_in_text() { // Angular's text ends at the NUL, which ends the input: the open tag after it is not read. + assert_eq!(lex("a\\0\xZZ"), + (vec![(Text, 0, 0), (Interpolation, 0, 2), (Text, 2, 2), (Eof, 2, 2)], vec![]) + ); + assert_eq!(lex(r"{{\0}}\u{").1, []); + assert_eq!( + lex(r"@if (\0) {}\xZZ"), + (vec![(IncompleteBlockOpen, 0, 4), (Eof, 5, 5)], vec![]) + ); + assert_eq!( + lex(r"@let a = \0;\xZZ"), + (vec![(IncompleteLet, 0, 9), (LetValue, 9, 9), (Eof, 9, 9)], vec![]) + ); + assert_eq!(lex(r"\xZZ"), (vec![(IncompleteTagOpen, 0, 2), (Eof, 3, 3)], vec![])); + assert_eq!(lex(r"\xZZ"), (vec![(IncompleteTagOpen, 0, 2), (Eof, 2, 2)], vec![])); + // An attribute value reads the NUL as text and goes on, so the error is reported. + let invalid = ("Invalid hexadecimal escape sequence".to_string(), 17); + assert_eq!(lex(r#"\xZZ"#).1, [invalid]); + } } // ============================================================================ From 43ddbf24292bdcf2620404ff1d63985c6821640e Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 18:14:50 +0800 Subject: [PATCH 10/47] refactor(parser): drop the escaped NUL guards the lexer no longer needs Now that the lexer stops at an escaped NUL like Angular, nothing after it is read: the guard in recover_at_bad_escape and the pruning of errors after a NUL in text never change a result (same on the whole corpus). Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 29 ------------------- 1 file changed, 29 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 95b6bd39a..932985ab8 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -749,12 +749,6 @@ impl<'a> HtmlLexer<'a> { if has_null { null_encountered = true; null_token_idx = Some(token_idx); - // Angular's text ends at the NUL, which ends the input: nothing after it is read - if token.token_type == HtmlTokenType::Text - && let Some(nul_end) = self.first_nul_end(token.start, token.end) - { - self.errors.retain(|error| error.offset as usize <= nul_end); - } break; } } @@ -900,20 +894,6 @@ impl<'a> HtmlLexer<'a> { } } - /// The byte after the first character the cursor reads as NUL in `start..end`, if any. - fn first_nul_end(&self, start: u32, end: u32) -> Option { - let mut pos = start as usize; - while pos < end as usize { - let escaped_nul = !self.reads_raw_at(pos) - && matches!(self.code_point_escape_value_at(pos), Some((Some(0), _))); - if escaped_nul || self.cursor_char_at(pos) == chars::EOF { - return Some(self.cursor_char_end(pos)); - } - pos = self.next_cursor_pos(pos); - } - None - } - /// Skips a line continuation at the cursor, as Angular's cursor does when it lands on one. fn skip_line_continuation(&mut self) { let pos = self.index as usize; @@ -1024,17 +1004,8 @@ impl<'a> HtmlLexer<'a> { /// of a token throws before the token is emitted. Returns whether the cursor is at one, after recovering like /// Angular's `tokenize`: it reports the error and, for invalid digits, reads the escape as a `\` of text (the /// cursor still peeks the backslash, then moves on from the escape's end); otherwise, the input ends. - /// - /// Not after an escaped NUL in text: Angular's lexing ends there, and the tokens after it are dropped. fn recover_at_bad_escape(&mut self) -> bool { let Some(error) = self.cursor_escape_error() else { return false }; - let past_nul = self.tokens.iter().any(|t| { - t.token_type == HtmlTokenType::Text - && t.parts.iter().any(|p| process_escape_sequences(p, false, false).2) - }); - if past_nul { - return false; - } let start = self.index; if let EscapeError::InvalidHex { digits, end } = error { self.move_raw_to(digits); From 5c65a82c88a8d8a1edd9e14b57238ab064a799da Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:00:19 +0800 Subject: [PATCH 11/47] fix(parser): read nothing after an escape cut short by the end of the input Angular's cursor throws at the end of the input there, so a bad escape after it is never reported. Co-Authored-By: Claude Opus 5.5 --- crates/oxc_angular_compiler/src/parser/html/lexer.rs | 8 +++----- crates/oxc_angular_compiler/tests/html_lexer_test.rs | 8 ++++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 932985ab8..e8062e847 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -397,13 +397,11 @@ fn process_escape_sequences( )); result.push('\\'); } - // The text ends inside the escape + // The text ends inside the escape: Angular's cursor throws there, at the end of the input, and + // reads nothing more. _ => { errors.push((EOF_ERROR.to_string(), text.len())); - result.push('\\'); - result.push(next); - i += 2; - continue; + return (result, errors, false); } } i += escape.len; diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 6fc162182..c99daa469 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2206,6 +2206,14 @@ mod escaped_code_points { assert_eq!(lex(r"{{a\u{"), (vec![text("", 0, 0), eof(6)], vec![eof_error(6)])); assert_eq!(lex(r#" Date: Fri, 4 Dec 2026 20:01:27 +0800 Subject: [PATCH 12/47] fix(parser): keep an escaped NUL in tokens like Angular's cursor The lexer already ends a token where Angular's cursor peeks a NUL as EOF, so the escape pass now keeps any NUL left in a token: quoted attribute values, comments, CDATA, raw text, doctypes and ICU raw text go on past it. A NUL escape cut short by the end of the input (`\x0`) peeks as EOF too, and a processing instruction ending there is dropped. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 95 +++++++------------ .../tests/html_lexer_test.rs | 59 ++++++++++++ 2 files changed, 92 insertions(+), 62 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index e8062e847..e9c2c4942 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -351,18 +351,13 @@ fn parse_int_prefix(digits: &str, radix: u32) -> Option { } /// Processes escape sequences in text when in "escaped strings" mode. -/// This is used when tokenize_expansion_forms is false (Angular's default for inline templates). -/// Returns (processed_text, errors, encountered_null), with error offsets in bytes into `text`. -/// When a null character (\0) is encountered, everything after it is discarded (EOF behavior), -/// unless `keep_nul` is set: then it decodes to `\0` and the text goes on. +/// Returns (processed_text, errors), with error offsets in bytes into `text`. +/// An escaped NUL decodes to `\0`: the lexer already ended the token where Angular's cursor peeks one as EOF, so any +/// NUL left in a token is one Angular's cursor moved past. /// Code-point escapes are read as Angular's cursor reads them (see `code_point_escape`): one cut short by the end of /// the text is an EOF error there, unless it is NUL. /// With `first_raw`, the first character is read as is, as Angular's cursor reads one after a line continuation. -fn process_escape_sequences( - text: &str, - keep_nul: bool, - first_raw: bool, -) -> (String, Vec<(String, usize)>, bool) { +fn process_escape_sequences(text: &str, first_raw: bool) -> (String, Vec<(String, usize)>) { let mut result = String::with_capacity(text.len()); let mut errors = Vec::new(); let mut i = 0; @@ -379,10 +374,6 @@ fn process_escape_sequences( }; if let Some(escape) = code_point_escape(&text[i..]) { if escape.value == Some(0) { - // An escaped NUL: Angular's cursor peeks it as EOF - if !keep_nul { - return (result, errors, true); - } result.push('\0'); i += escape.len; continue; @@ -401,7 +392,7 @@ fn process_escape_sequences( // reads nothing more. _ => { errors.push((EOF_ERROR.to_string(), text.len())); - return (result, errors, false); + return (result, errors); } } i += escape.len; @@ -427,7 +418,7 @@ fn process_escape_sequences( } } - (result, errors, false) + (result, errors) } /// Merges adjacent text tokens and adjacent attribute value text tokens. @@ -692,18 +683,9 @@ impl<'a> HtmlLexer<'a> { if self.escaped_string { // (message, offset): positions are worked out once all are known, in one pass. let mut errors_to_add: Vec<(String, u32)> = Vec::new(); - let mut null_encountered = false; - let mut null_token_idx = None; let mut cut_short_token = None; - for (token_idx, token) in tokens.iter_mut().enumerate() { - if null_encountered { - break; - } - - // Angular's cursor peeks a NUL as EOF but can move past it. Its processing instruction scan reaches - // one only inside quotes, which it moves past, so the NUL stays in the content and lexing goes on. - let keep_nul = token.token_type == HtmlTokenType::ProcessingInstruction; + 'tokens: for (token_idx, token) in tokens.iter_mut().enumerate() { // Where each part starts: at the token start, but the content of an interpolation, a processing // instruction or a doctype after its start marker and a line continuation there. Angular's cursor // reads the character after one as is. @@ -722,8 +704,7 @@ impl<'a> HtmlLexer<'a> { for (part_idx, part) in token.parts.iter_mut().enumerate() { let part_start = if part_idx == content_idx { content_start } else { start }; let first_raw = part.starts_with('\\') && self.reads_raw_at(part_start); - let (processed, errs, has_null) = - process_escape_sequences(part, keep_nul, first_raw); + let (processed, errs) = process_escape_sequences(part, first_raw); *part = processed; // An escape cut short by the end of the input throws an EOF error there in Angular, which may be // the one the lexer reports: the token is lost, and the input ends. @@ -741,13 +722,7 @@ impl<'a> HtmlLexer<'a> { } if cut_short { cut_short_token = Some((token_idx, token.end)); - null_encountered = true; - break; - } - if has_null { - null_encountered = true; - null_token_idx = Some(token_idx); - break; + break 'tokens; } } } @@ -756,28 +731,6 @@ impl<'a> HtmlLexer<'a> { tokens.truncate(idx); tokens.push(HtmlToken::empty(HtmlTokenType::Eof, end, end)); } - // If null was encountered, truncate tokens after that point and ensure EOF is present - if let Some(idx) = null_token_idx { - // Keep tokens up to and including the null token - tokens.truncate(idx + 1); - - // If the last token has empty parts after null processing, and it's a TEXT token, - // we might need to remove it - if let Some(last) = tokens.last() { - if last.token_type == HtmlTokenType::Text - && last.parts.iter().all(|p| p.is_empty()) - { - tokens.pop(); - } - } - - // Add EOF if not already present - if tokens.last().is_none_or(|t| t.token_type != HtmlTokenType::Eof) { - let eof_start = tokens.last().map(|t| t.end).unwrap_or(0); - tokens.push(HtmlToken::empty(HtmlTokenType::Eof, eof_start, eof_start)); - } - } - let offsets: Vec = errors_to_add.iter().map(|&(_, offset)| offset).collect(); let positions = offsets_to_positions(self.input, &offsets); self.errors.extend(errors_to_add.into_iter().zip(positions).map( @@ -926,10 +879,10 @@ impl<'a> HtmlLexer<'a> { /// A code-point escape at byte `pos` (a backslash), read as one character by `code_point_escape_value_at`. /// Returns the character and the escape's length in bytes; none for any other escape. /// - /// NUL reads as `chars::EOF`, as Angular's cursor peeks it, so a scan stops there where Angular's does. An escape - /// with no digits, one cut short by the end of the input, or a surrogate reads as U+FFFD, which is no structural - /// character: the escape stays inside its token, whose text `process_escape_sequences` decodes, reporting the - /// invalid ones. + /// NUL reads as `chars::EOF`, as Angular's cursor peeks it, so a scan stops there where Angular's does, even when + /// the end of the input cuts it short. An escape with no digits, any other one cut short, or a surrogate reads as + /// U+FFFD, which is no structural character: the escape stays inside its token, whose text + /// `process_escape_sequences` decodes, reporting the invalid ones. fn code_point_escape_at(&self, pos: usize) -> Option<(char, usize)> { let (value, len) = self.code_point_escape_value_at(pos)?; let ch = value.and_then(char::from_u32); @@ -938,12 +891,13 @@ impl<'a> HtmlLexer<'a> { /// A code-point escape at byte `pos` (a backslash), with the length Angular's `EscapedCharacterCursor` gives it /// (see `code_point_escape`). Returns the code point (none when the digits are NaN or the escape is cut short by - /// the end of the input) and the escape's length in bytes; none for any other escape. + /// the end of the input, but NUL, which Angular's cursor peeks there too) and the escape's length in bytes; none + /// for any other escape. /// /// The digits are read like JavaScript's `parseInt`, so `\u{41zz}` is `A`. fn code_point_escape_value_at(&self, pos: usize) -> Option<(Option, usize)> { let escape = code_point_escape(self.input.get(pos..)?)?; - Some((escape.value.filter(|_| escape.complete), escape.len)) + Some((escape.value.filter(|&v| escape.complete || v == 0), escape.len)) } /// Whether the cursor is at a raw or escaped NUL, which Angular's cursor peeks as EOF but can move past. @@ -983,6 +937,17 @@ impl<'a> HtmlLexer<'a> { }) } + /// Whether the cursor is at a code-point escape that the end of the input cuts short, which it cannot move past. + fn at_escape_cut_short(&self) -> bool { + self.escaped_string + && !self.reads_raw_at(self.index as usize) + && self + .input + .get(self.index as usize..) + .and_then(code_point_escape) + .is_some_and(|escape| !escape.complete) + } + /// Moves the cursor to byte `target`, counting lines and columns over the raw characters. fn move_raw_to(&mut self, target: u32) { let start = self.index as usize; @@ -3132,6 +3097,12 @@ impl<'a> HtmlLexer<'a> { self.error("Unexpected character \"EOF\""); return; } + // At a NUL escape cut short by the end of the input (`\x0`), the cursor cannot move past the end. + if self.at_escape_cut_short() { + self.move_raw_to(self.length); + self.error(EOF_ERROR); + return; + } let content = self.input[content_start as usize..self.index as usize].to_string(); // Angular drops the instruction when the cursor moves past its end onto a bad escape. let end_char = self.advance(); diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index c99daa469..9183c8d7a 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2269,6 +2269,65 @@ mod escaped_nul_errors { let invalid = ("Invalid hexadecimal escape sequence".to_string(), 17); assert_eq!(lex(r#"\xZZ"#).1, [invalid]); } + + #[test] + fn should_keep_an_escaped_nul_where_angular_moves_past_it() { + // Scans that do not stop at EOF read the NUL as a character and go on: quoted attribute values, comments, + // CDATA, raw text, doctypes and ICU raw text. + let lexed = |input: &str| { + let result = HtmlLexer::new(input) + .with_escaped_string(true) + .with_expansion_forms(true) + .tokenize(); + let tokens: Vec<_> = result + .tokens + .into_iter() + .map(|t| (t.token_type, t.parts, t.start, t.end)) + .collect(); + (tokens, result.errors.len()) + }; + let nul_text = |input: &str, token: usize| { + let (tokens, errors) = lexed(input); + assert_eq!(errors, 0, "{input}"); + let (ty, parts, start, end) = tokens[token].clone(); + (ty, parts[0].clone(), start, end, tokens.last().map(|t| t.0)) + }; + use HtmlTokenType::*; + let s = |v: &str| v.to_string(); + assert_eq!( + nul_text(r#"c"#, 3), + (AttrValueText, s("x\0y"), 6, 10, Some(Eof)) + ); + assert_eq!(nul_text(r#""#, 3), (AttrValueText, s("x\0y"), 6, 12, Some(Eof))); + assert_eq!(nul_text(r"z", 1), (RawText, s("x\0y"), 4, 8, Some(Eof))); + assert_eq!(nul_text(r"z", 1), (RawText, s("x\0y"), 9, 13, Some(Eof))); + assert_eq!(nul_text(r"z", 2), (RawText, s("x\0y"), 8, 12, Some(Eof))); + assert_eq!( + nul_text(r"z", 2), + (EscapableRawText, s("x\0y"), 10, 14, Some(Eof)) + ); + assert_eq!( + nul_text(r"z", 0), + (DocType, s("DOCTYPE x\0y"), 0, 15, Some(Eof)) + ); + assert_eq!(nul_text(r"{a\0b, select, c\0 {d}}", 1), (RawText, s("a\0b"), 1, 5, Some(Eof))); + assert_eq!( + nul_text(r"{a\0b, select, c\0 {d}}", 3), + (ExpansionCaseValue, s("c\0"), 15, 19, Some(Eof)) + ); + // The token after it is read too. + assert_eq!(lexed(r"z").0[3], (Text, vec![s("z")], 11, 12)); + assert_eq!(lexed(r"z").0[1], (Text, vec![s("z")], 15, 16)); + } + + #[test] + fn should_peek_a_nul_escape_cut_short_by_the_end_of_the_input_as_eof() { + use HtmlTokenType::*; + // `parseInt("0", 16)` is 0 although `\x` wants 2 digits: the cursor peeks EOF there, but cannot move past. + assert_eq!(lex(r"\x0"), (vec![(Eof, 0, 0)], vec![])); + assert_eq!(lex(r"a\x0"), (vec![(Text, 0, 1), (Eof, 1, 1)], vec![])); + assert_eq!(lex(r" Date: Fri, 4 Dec 2026 20:06:44 +0800 Subject: [PATCH 13/47] fix(parser): normalize line endings after decoding escapes like Angular Angular's _processCarriageReturns runs on the characters its cursor reads, so a CR before a line continuation and the LF after it are one line ending, and an escaped CR is a CR. Doctypes, processing instructions and an ICU's switch value and type keep their CRs, as in Angular. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 58 +++++++++++-------- .../tests/html_lexer_test.rs | 33 +++++++++++ 2 files changed, 68 insertions(+), 23 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index e9c2c4942..569a5acbe 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -400,7 +400,8 @@ fn process_escape_sequences(text: &str, first_raw: bool) -> (String, Vec<(String } i += 1 + next.len_utf8(); match next { - 'n' | 'r' => result.push('\n'), // \r gets normalized to \n + 'n' => result.push('\n'), + 'r' => result.push('\r'), 'v' => result.push('\x0B'), 't' => result.push('\t'), 'b' => result.push('\x08'), @@ -684,6 +685,29 @@ impl<'a> HtmlLexer<'a> { // (message, offset): positions are worked out once all are known, in one pass. let mut errors_to_add: Vec<(String, u32)> = Vec::new(); let mut cut_short_token = None; + // Angular's `_processCarriageReturns` runs on the decoded text of text, attribute values, raw text and + // interpolation expressions; not on an ICU's switch value and type, which are raw text too. + let processes_crs: Vec = tokens + .iter() + .enumerate() + .map(|(i, token)| { + let before = |n: usize| i.checked_sub(n).map(|j| tokens[j].token_type); + match token.token_type { + HtmlTokenType::Text + | HtmlTokenType::AttrValueText + | HtmlTokenType::EscapableRawText + | HtmlTokenType::Interpolation + | HtmlTokenType::AttrValueInterpolation => true, + HtmlTokenType::RawText => { + let icu_switch = before(1) == Some(HtmlTokenType::ExpansionFormStart); + let icu_type = before(1) == Some(HtmlTokenType::RawText) + && before(2) == Some(HtmlTokenType::ExpansionFormStart); + !icu_switch && !icu_type + } + _ => false, + } + }) + .collect(); 'tokens: for (token_idx, token) in tokens.iter_mut().enumerate() { // Where each part starts: at the token start, but the content of an interpolation, a processing @@ -705,7 +729,11 @@ impl<'a> HtmlLexer<'a> { let part_start = if part_idx == content_idx { content_start } else { start }; let first_raw = part.starts_with('\\') && self.reads_raw_at(part_start); let (processed, errs) = process_escape_sequences(part, first_raw); - *part = processed; + *part = if processes_crs[token_idx] && part_idx == content_idx { + normalize_line_endings(&processed) + } else { + processed + }; // An escape cut short by the end of the input throws an EOF error there in Angular, which may be // the one the lexer reports: the token is lost, and the input ends. let mut cut_short = false; @@ -779,27 +807,10 @@ impl<'a> HtmlLexer<'a> { && matches!(self.input.as_bytes()[pos + 1], b'\n' | b'\r') } - /// Normalizes the line endings of token text. In an escaped string, a CR right after a backslash stays: it ends - /// a line continuation, which the escape pass skips with the backslash, reading the LF of a CRLF after it as text - /// like Angular's cursor. + /// Normalizes the line endings of token text. In an escaped string, the escape pass does it once the escapes are + /// decoded, as Angular's `_processCarriageReturns` runs on the characters its cursor reads. fn normalize_line_endings(&self, text: &str) -> String { - if !self.escaped_string { - return normalize_line_endings(text); - } - let mut result = String::with_capacity(text.len()); - let mut chars = text.chars().peekable(); - while let Some(ch) = chars.next() { - match ch { - '\\' => { - result.push(ch); - result.extend(chars.next()); - } - '\r' if chars.peek() == Some(&'\n') => {} - '\r' => result.push('\n'), - _ => result.push(ch), - } - } - result + if self.escaped_string { text.to_string() } else { normalize_line_endings(text) } } /// Whether the cursor reads the character at byte `pos` as is: it comes right after a line continuation. @@ -3779,7 +3790,8 @@ mod tests { ("Invalid hexadecimal escape sequence", (0, 14), 14), ("Invalid hexadecimal escape sequence", (0, 19), 19), ("Invalid hexadecimal escape sequence", (1, 5), 34), - ("Invalid hexadecimal escape sequence", (3, 1), 40), + // Angular's UTF-16 offset 40: the CR of the CRLF before it counts. + ("Invalid hexadecimal escape sequence", (3, 2), 41), ("Unexpected character \"EOF\"", (5, 0), 58), ] ); diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 9183c8d7a..c0258a45a 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2149,6 +2149,39 @@ mod escaped_line_continuations { assert_eq!(lex("a\\\r\n\\x00\\xzz").1, []); } + #[test] + fn should_normalize_line_endings_after_decoding_escapes() { + // Angular's `_processCarriageReturns` runs on the characters the cursor reads: a CR before a line + // continuation and the LF after it are one line ending. + assert_eq!(lex("a\r\\\r\nb"), (vec![text("a\nb", 0, 6), eof(6)], vec![])); + assert_eq!(lex("a\\\n\\\r\nb"), (vec![text("a\\\nb", 0, 7), eof(7)], vec![])); + let parts = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + let interpolation = (HtmlTokenType::Interpolation, parts(&["{{", "a"]), 4, 7); + assert_eq!( + lex("\\\r\\\r{{a"), + (vec![text("\\\n", 2, 4), interpolation, text("", 7, 7), eof(7)], vec![]) + ); + let part = |input: &str, token: usize| lex(input).0[token].1[0].clone(); + assert_eq!(part("", 3), "x\ny"); + assert_eq!(part("", 1), "x\ny"); + assert_eq!(part("", 1), "x\ny"); + assert_eq!(part("", 2), "x\ny"); + assert_eq!(part("", 2), "x\ny"); + assert_eq!(lex("{{x\r\\\r\ny}}").0[1].1[1], "x\ny"); + // An escaped CR is a CR too. + assert_eq!(lex(r"a\r").0[0].1[0], "a\n"); + assert_eq!(lex("a\\r\nb"), (vec![text("a\nb", 0, 5), eof(5)], vec![])); + // A doctype and a processing instruction keep their CRs. + assert_eq!(part(r"", 0), "DOCTYPE a\rb"); + assert_eq!(part("z", 0), "x\r\n"); + // So does an ICU's switch value. + let icu = HtmlLexer::new("{a\r\n\\r, select, c {d}}") + .with_escaped_string(true) + .with_expansion_forms(true) + .tokenize(); + assert_eq!(icu.tokens[1].parts, ["a\r\n\r"]); + } + #[test] fn should_report_nothing_after_an_escaped_nul_in_text() { // Angular's text ends at the NUL, which ends the input: the open tag after it is not read. From 6e002c8f9693d35f2b83ead95adc9d677189b59b Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:12:02 +0800 Subject: [PATCH 14/47] fix(parser): find where the prefix and name of a tag or attribute start The check for a backslash read as is after a line continuation used the token start for every part. A name after a prefix starts after its `:`, and the name of a closing tag after the ` --- .../src/parser/html/lexer.rs | 43 ++++++++++++++++++- .../tests/html_lexer_test.rs | 16 +++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 569a5acbe..ffe6eae0c 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -724,10 +724,35 @@ impl<'a> HtmlLexer<'a> { let marker_end = start + marker_len; let after_continuation = marker_len > 0 && self.is_line_continuation_at(marker_end); let content_start = marker_end + if after_continuation { 2 } else { 0 }; + // The prefix of a tag or attribute name starts where the cursor starts the name: at the start of an + // attribute name, after the `<` of an open tag, after the ` Some(start), + HtmlTokenType::TagOpenStart | HtmlTokenType::IncompleteTagOpen + if start < self.length as usize => + { + Some(self.next_cursor_pos(start)) + } + HtmlTokenType::TagClose => Some(self.tag_close_name_start(start)), + _ => None, + }; + let prefix_len = token.parts.first().map_or(0, String::len); // Process escape sequences in token parts for (part_idx, part) in token.parts.iter_mut().enumerate() { - let part_start = if part_idx == content_idx { content_start } else { start }; - let first_raw = part.starts_with('\\') && self.reads_raw_at(part_start); + let part_start = match name_start { + Some(at) if part_idx == 1 && prefix_len > 0 => at + prefix_len + 1, + Some(at) => at, + None if part_idx == content_idx => content_start, + None => start, + }; + // (The closing tag of raw text has the name of its open tag, which may not be there.) + let first_raw = part.starts_with('\\') + && self.reads_raw_at(part_start) + && self + .input + .get(part_start..) + .is_some_and(|rest| rest.starts_with(part.as_str())); let (processed, errs) = process_escape_sequences(part, first_raw); *part = if processes_crs[token_idx] && part_idx == content_idx { normalize_line_endings(&processed) @@ -813,6 +838,20 @@ impl<'a> HtmlLexer<'a> { if self.escaped_string { text.to_string() } else { normalize_line_endings(text) } } + /// Where the cursor starts the name of the closing tag at byte `start`: past the ` usize { + let mut pos = start; + for _ in 0..2 { + if pos < self.length as usize { + pos = self.next_cursor_pos(pos); + } + } + while pos < self.length as usize && chars::is_whitespace(self.cursor_char_at(pos)) { + pos = self.next_cursor_pos(pos); + } + pos + } + /// Whether the cursor reads the character at byte `pos` as is: it comes right after a line continuation. fn reads_raw_at(&self, pos: usize) -> bool { self.continuation_ends.binary_search(&pos).is_ok() diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index c0258a45a..56db9626c 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2140,6 +2140,22 @@ mod escaped_line_continuations { assert_eq!(lex(""), (vec![text("\\xZZ>", 6, 11), eof(11)], vec![unexpected])); } + #[test] + fn should_read_a_backslash_starting_a_name_after_it_as_is() { + use HtmlTokenType::*; + let tag = |ty, prefix: &str, name: &str, start, end| { + (ty, vec![prefix.to_string(), name.to_string()], start, end) + }; + // Where the cursor starts the name: after the `").0[0], tag(TagClose, "", "\\x41", 0, 9)); + assert_eq!(lex("").0[0], tag(TagClose, "", "\\x41", 0, 10)); + // Not after a prefix, nor at a tag starting there. + assert_eq!(lex("").0[1], tag(AttrName, "x", "A", 5, 11)); + assert_eq!(lex("\\\n<\\x41>").0[0], tag(TagOpenStart, "", "A", 2, 7)); + assert_eq!(lex("\\\n").0[0], tag(TagOpenStart, "a", "b", 2, 9)); + assert_eq!(lex("\\\n").0[0], tag(TagClose, "", "A", 2, 9)); + } + #[test] fn should_skip_only_the_cr_of_a_crlf() { // The LF is read as is, and an escape after it is decoded. From 86ccd534e03995851e393dca45cd84db07d00507 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:17:56 +0800 Subject: [PATCH 15/47] fix(parser): drop the text an unterminated attribute value ends in Angular's cursor throws at the end of the input before it ends the text token it is in, so that token is lost, with the empty one after an interpolation or entity. This holds in plain templates too. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 13 +++++ .../tests/html_lexer_test.rs | 50 +++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index ffe6eae0c..1361b0803 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -3050,6 +3050,19 @@ impl<'a> HtmlLexer<'a> { } } + if self.index >= self.length { + // No closing quote: Angular's cursor throws at the end of the input before it ends the text token it is + // in, so that token is lost, with the empty one emitted after an interpolation or entity. + if self.tokens.last().is_some_and(|t| { + t.token_type == HtmlTokenType::AttrValueText + && t.start == text_start + && t.end == text_start + }) { + self.tokens.pop(); + } + return; + } + // Emit remaining text (only if there's actual content since we already emit empty tokens after interp/entity) if self.index > text_start { let text = &self.input[text_start as usize..self.index as usize]; diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 56db9626c..f7856118a 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -531,6 +531,56 @@ mod attributes { let result = tokenize(r#" = result + .tokens + .into_iter() + .map(|t| (t.token_type, t.parts, t.start, t.end)) + .collect(); + (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect::>()) + }; + let parts = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + let start = || { + vec![ + (TagOpenStart, parts(&["", "a"]), 0, 2), + (AttrName, parts(&["", "b"]), 3, 4), + (AttrQuote, parts(&["\""]), 5, 6), + ] + }; + let eof_error = |offset| vec![("Unexpected character \"EOF\"".to_string(), offset)]; + let mut tokens = start(); + tokens.push((Eof, vec![], 9, 9)); + assert_eq!(lex(r#" Date: Fri, 4 Dec 2026 20:24:10 +0800 Subject: [PATCH 16/47] fix(parser): drop the characters of a bad entity in text like Angular Angular's _consumeEntity throws out of the text: the text before the entity is a token, the characters the entity read are lost, and lexing goes on where its cursor stopped, past an escaped NUL too. The message has the characters the cursor read. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 57 ++++++++++++++----- .../tests/html_lexer_test.rs | 52 +++++++++++++++++ 2 files changed, 95 insertions(+), 14 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 1361b0803..52da8a04a 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -852,6 +852,20 @@ impl<'a> HtmlLexer<'a> { pos } + /// The characters the cursor reads from byte `start` to `end`, as Angular's `getChars`. + fn cursor_text(&self, start: u32, end: u32) -> String { + if !self.escaped_string { + return self.input[start as usize..end as usize].to_string(); + } + let mut text = String::new(); + let mut pos = start as usize; + while pos < end as usize { + text.push(self.cursor_char_at(pos)); + pos = self.next_cursor_pos(pos); + } + text + } + /// Whether the cursor reads the character at byte `pos` as is: it comes right after a line continuation. fn reads_raw_at(&self, pos: usize) -> bool { self.continuation_ends.binary_search(&pos).is_ok() @@ -3512,6 +3526,17 @@ impl<'a> HtmlLexer<'a> { continue; } } + if let Some(error) = self.entity_error.take() { + // Angular's `_consumeEntity` throws out of the text: the text before the entity is a token (maybe + // empty), the characters the entity read are lost, and lexing goes on where its cursor stopped. + self.push_text(text_start, entity_start); + let (EntityError::At(index, line, column) + | EntityError::Eof(index, line, column)) = error; + self.index = index; + self.line = line; + self.column = column; + return; + } // If entity parsing failed, scan_entity reverted the index // so just advance past the & and treat it as regular text } @@ -3521,21 +3546,25 @@ impl<'a> HtmlLexer<'a> { // Emit remaining text if self.index > text_start { - let text = &self.input[text_start as usize..self.index as usize]; - let normalized = self.normalize_line_endings(text); - // Apply leading trivia calculation for source map accuracy - let (adjusted_start, full_start) = - self.calculate_start_with_trivia(text_start, self.index); - self.tokens.push(HtmlToken::new_with_full_start( - HtmlTokenType::Text, - vec![normalized], - adjusted_start, - self.index, - full_start, - )); + self.push_text(text_start, self.index); } } + /// Emits the text from byte `start` to `end` as a text token. + fn push_text(&mut self, start: u32, end: u32) { + let text = &self.input[start as usize..end as usize]; + let normalized = self.normalize_line_endings(text); + // Apply leading trivia calculation for source map accuracy + let (adjusted_start, full_start) = self.calculate_start_with_trivia(start, end); + self.tokens.push(HtmlToken::new_with_full_start( + HtmlTokenType::Text, + vec![normalized], + adjusted_start, + end, + full_start, + )); + } + /// Scans an HTML entity (numeric or named). /// Returns true if an entity was successfully parsed and a token was emitted. /// Returns false if no valid entity was found (caller should treat `&` as regular text). @@ -3577,7 +3606,7 @@ impl<'a> HtmlLexer<'a> { // Angular's `String.fromCodePoint` throws for no digits or a value past // U+10FFFF: an unknown entity, reported after the `;`. if code_point.is_none_or(|code_point| code_point > 0x0010_FFFF) { - let entity_str = &self.input[start as usize..self.index as usize]; + let entity_str = self.cursor_text(start, self.index); let msg = format!( "Unknown entity \"{entity_str}\" - use the \"&#;\" or \"&#x;\" syntax" ); @@ -3621,7 +3650,7 @@ impl<'a> HtmlLexer<'a> { self.entity_error = Some(EntityError::Eof(self.index, self.line, self.column)); } else { self.advance(); - let entity_str = &self.input[start as usize..self.index as usize]; + let entity_str = self.cursor_text(start, self.index); let entity_type = if is_hex { "hexadecimal" } else { "decimal" }; self.push_error(format!( "Unable to parse entity \"{entity_str}\" - {entity_type} character reference entities must end with \";\"" diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index f7856118a..9e1709aa7 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -3382,6 +3382,58 @@ mod expansion_forms { mod entities_extended { use super::*; + type Lexed = (Vec<(HtmlTokenType, Vec, u32, u32)>, Vec<(String, u32)>); + + fn lex(input: &str, escaped: bool) -> Lexed { + let result = HtmlLexer::new(input).with_escaped_string(escaped).tokenize(); + let tokens = + result.tokens.into_iter().map(|t| (t.token_type, t.parts, t.start, t.end)).collect(); + (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect()) + } + + #[test] + fn should_drop_the_characters_of_a_bad_entity_in_text() { + // Angular's `_consumeEntity` throws out of the text: the characters it read are lost, and lexing goes on + // where its cursor stopped. Expected values are from Angular 22.3.0. + let text = + |value: &str, start, end| (HtmlTokenType::Text, vec![value.to_string()], start, end); + let eof = |offset| (HtmlTokenType::Eof, vec![], offset, offset); + let unparsable = |entity: &str, kind: &str, offset| { + let msg = format!( + "Unable to parse entity \"{entity}\" - {kind} character reference entities must end with \";\"" + ); + vec![(msg, offset)] + }; + let unknown = |entity: &str, offset| { + let msg = format!( + "Unknown entity \"{entity}\" - use the \"&#;\" or \"&#x;\" syntax" + ); + vec![(msg, offset)] + }; + assert_eq!( + lex("q;z", false), + (vec![text(";z", 0, 7), eof(7)], unparsable("q", "hexadecimal", 5)) + ); + assert_eq!( + lex("aAz", false), + (vec![text("a", 0, 1), eof(6)], unparsable("Az", "decimal", 6)) + ); + assert_eq!(lex("a&#;b", false), (vec![text("ab", 0, 5), eof(5)], unknown("&#;", 4))); + assert_eq!(lex("a&foo;b", false), (vec![text("ab", 0, 7), eof(7)], unknown("foo", 1))); + let eof_error = vec![("Unexpected character \"EOF\"".to_string(), 5)]; + assert_eq!(lex("aA", false), (vec![text("a", 0, 1), eof(5)], eof_error)); + // In an escaped string, the cursor moves past a NUL before it throws, and the message has the characters it + // read. + assert_eq!( + lex(r"\x00;z", true), + (vec![text(";z", 0, 10), eof(10)], unparsable("\0", "hexadecimal", 8)) + ); + assert_eq!( + lex("\\\n\\x41;z", true), + (vec![text("x41;z", 0, 12), eof(12)], unparsable("\\", "hexadecimal", 7)) + ); + } + #[test] fn should_parse_entities_with_more_than_4_hex_digits() { // TS: it("should parse entities with more than 4 hex digits", ...) From 77ae704ea197c9ed979329d89875e07c13e7236c Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:39:02 +0800 Subject: [PATCH 17/47] fix(parser): drop an instruction, end tag or comment text at a bad escape Angular's cursor decodes an escape as soon as it moves onto it and throws for invalid digits: a processing instruction or comment text it is in is lost, and so is an end tag whose `>` it moves past onto one. The backslash it still peeks starts a text. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 28 +++++++++++++++++-- .../tests/html_lexer_test.rs | 20 +++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 52da8a04a..2e17b0c6c 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -2421,6 +2421,10 @@ impl<'a> HtmlLexer<'a> { return; } self.advance(); + // Angular drops the end tag when its cursor moves past the `>` onto a bad escape. + if self.recover_at_bad_escape() { + return; + } self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::TagClose, @@ -3101,7 +3105,11 @@ impl<'a> HtmlLexer<'a> { self.tokens.push(HtmlToken::empty(HtmlTokenType::CommentStart, start, self.index)); let content_start = self.index; + // Angular drops the comment's text when its cursor moves onto a bad escape inside it. while !self.starts_with("-->") && self.index < self.length { + if self.recover_at_bad_escape() { + return; + } self.advance(); } let content = &self.input[content_start as usize..self.index as usize]; @@ -3153,13 +3161,29 @@ impl<'a> HtmlLexer<'a> { /// `_consumeProcessingInstruction`: up to a `?` or `>` outside quotes, then `>`. fn scan_processing_instruction(&mut self, start: u32) { let content_start = self.index; - while self.index < self.length && !matches!(self.peek(), '?' | '>') && !self.at_nul() { + // Angular drops the instruction when its cursor moves onto a bad escape inside it. + loop { + if self.recover_at_bad_escape() { + return; + } + if self.index >= self.length || matches!(self.peek(), '?' | '>') || self.at_nul() { + break; + } let ch = self.peek(); self.advance(); if ch == '"' || ch == '\'' || ch == '`' { - while self.index < self.length && self.peek() != ch { + loop { + if self.recover_at_bad_escape() { + return; + } + if self.index >= self.length || self.peek() == ch { + break; + } if self.peek() == '\\' { self.advance(); + if self.recover_at_bad_escape() { + return; + } } if self.index < self.length { self.advance(); diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 9e1709aa7..4ed0d66ce 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2306,6 +2306,26 @@ mod escaped_code_points { assert_eq!(lex(r#"e"), + (vec![text("\\cd?>e", 4, 13), eof(13)], vec![invalid(6)]) + ); + assert_eq!(lex(r"e"), (vec![text("\\'?>e", 3, 11), eof(11)], vec![invalid(5)])); + assert_eq!(lex(r"x\xzz"), (vec![text("x\\", 0, 9), eof(9)], vec![invalid(7)])); + let comment_start = (HtmlTokenType::CommentStart, vec![], 0, 4); + assert_eq!( + lex(r"c"), + (vec![comment_start, text("\\b-->c", 5, 14), eof(14)], vec![invalid(7)]) + ); + } + #[test] fn should_read_nothing_after_an_escape_cut_short_by_the_end_of_the_input() { // Angular's cursor throws at the end of the input: the bad escape after it is never read. From f73e3583dd66f9c9f298dad358e9f83fd501d331 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:41:44 +0800 Subject: [PATCH 18/47] fix(parser): report escape errors in input order like Angular The bad escapes found while lexing and those found when the escapes of token text are decoded afterwards now come in the order Angular's cursor meets them. Co-Authored-By: Claude Opus 5.5 --- crates/oxc_angular_compiler/src/parser/html/lexer.rs | 2 ++ crates/oxc_angular_compiler/tests/html_lexer_test.rs | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 2e17b0c6c..41c42e5a6 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -789,6 +789,8 @@ impl<'a> HtmlLexer<'a> { self.errors.extend(errors_to_add.into_iter().zip(positions).map( |((msg, offset), position)| HtmlTokenError { msg, position, offset, end: offset }, )); + // In the order Angular's cursor meets them. + self.errors.sort_by_key(|error| error.offset); } HtmlTokenizeResult { tokens, errors: self.errors } diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 4ed0d66ce..efbcf6578 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2326,6 +2326,15 @@ mod escaped_code_points { ); } + #[test] + fn should_report_the_bad_escapes_in_input_order() { + let invalid = |offset| ("Invalid hexadecimal escape sequence".to_string(), offset); + assert_eq!( + lex(r"\xzz\xzz"), + (vec![text("\\\\", 0, 13), eof(13)], vec![invalid(2), invalid(11)]) + ); + } + #[test] fn should_read_nothing_after_an_escape_cut_short_by_the_end_of_the_input() { // Angular's cursor throws at the end of the input: the bad escape after it is never read. From a01819f7b8d2bf48a34b2d9a492376909375628b Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:44:14 +0800 Subject: [PATCH 19/47] fix(parser): report EOF after invalid escape digits that end the input Angular's cursor reports the invalid digits, then fails to move past them: the token is lost, and the input ends. Co-Authored-By: Claude Opus 5.5 --- crates/oxc_angular_compiler/src/parser/html/lexer.rs | 5 +++++ crates/oxc_angular_compiler/tests/html_lexer_test.rs | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 41c42e5a6..4a7d13efc 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -386,6 +386,11 @@ fn process_escape_sequences(text: &str, first_raw: bool) -> (String, Vec<(String "Invalid hexadecimal escape sequence".to_string(), i + escape.digits, )); + // Digits that end the input: the cursor then fails to move past them. + if !escape.complete { + errors.push((EOF_ERROR.to_string(), text.len())); + return (result, errors); + } result.push('\\'); } // The text ends inside the escape: Angular's cursor throws there, at the end of the input, and diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index efbcf6578..cf9fd21f6 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2335,6 +2335,16 @@ mod escaped_code_points { ); } + #[test] + fn should_report_eof_after_invalid_digits_that_end_the_input() { + // The cursor fails to move past them: the token is lost, and the input ends. + let invalid = |offset| ("Invalid hexadecimal escape sequence".to_string(), offset); + assert_eq!(lex(r"\xz"), (vec![eof(3)], vec![invalid(2), eof_error(3)])); + assert_eq!(lex(r"a\xz"), (vec![eof(4)], vec![invalid(3), eof_error(4)])); + assert_eq!(lex(r"a\uZZZ"), (vec![eof(6)], vec![invalid(3), eof_error(6)])); + assert_eq!(lex(r"{{a\xz"), (vec![text("", 0, 0), eof(6)], vec![invalid(5), eof_error(6)])); + } + #[test] fn should_read_nothing_after_an_escape_cut_short_by_the_end_of_the_input() { // Angular's cursor throws at the end of the input: the bad escape after it is never read. From d86c5d23554f2d249e34c09f886c8e7d646a96de Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:46:49 +0800 Subject: [PATCH 20/47] fix(parser): report the bad escapes in a dropped attribute value text The text an unterminated attribute value ends in is lost, but Angular's cursor still reports the bad escapes it read in it. Co-Authored-By: Claude Opus 5.5 --- .../oxc_angular_compiler/src/parser/html/lexer.rs | 14 +++++++++++++- .../oxc_angular_compiler/tests/html_lexer_test.rs | 3 +++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 4a7d13efc..82df7e1be 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -3077,7 +3077,19 @@ impl<'a> HtmlLexer<'a> { if self.index >= self.length { // No closing quote: Angular's cursor throws at the end of the input before it ends the text token it is - // in, so that token is lost, with the empty one emitted after an interpolation or entity. + // in, so that token is lost, with the empty one emitted after an interpolation or entity. The bad escapes + // its cursor read in it are still reported. + if self.escaped_string { + let text = &self.input[text_start as usize..self.index as usize]; + let first_raw = self.reads_raw_at(text_start as usize); + for (msg, offset) in process_escape_sequences(text, first_raw).1 { + if msg != EOF_ERROR { + let offset = text_start + offset as u32; + let position = offsets_to_positions(self.input, &[offset])[0]; + self.push_error(msg, position, offset, offset); + } + } + } if self.tokens.last().is_some_and(|t| { t.token_type == HtmlTokenType::AttrValueText && t.start == text_start diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index cf9fd21f6..1661dec08 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -580,6 +580,9 @@ mod attributes { tokens.push((AttrValueInterpolation, parts(&["{{", ""]), 6, 8)); tokens.push((Eof, vec![], 15, 15)); assert_eq!(lex(r#" Date: Fri, 4 Dec 2026 20:49:40 +0800 Subject: [PATCH 21/47] fix(parser): decode the escapes of text tokens before merging them An escape cut short by the end of the input loses only the text it ends, as in Angular: the text before an instruction dropped at a bad escape stays, while an empty text after an entity and the backslash read after an earlier bad escape go with it. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 23 ++++++++++++++++--- .../tests/html_lexer_test.rs | 15 ++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 82df7e1be..41e821bcb 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -536,6 +536,8 @@ pub struct HtmlLexer<'a> { /// In an escaped string, the byte offsets right after each line continuation the cursor skips, in order. /// Angular's cursor reads the character there as is: an escape starting there is not decoded. continuation_ends: Vec, + /// Where the texts `recover_at_bad_escape` emitted start. + recovered_texts: Vec, /// Line offset for range mode. range_line_offset: u32, /// Column offset for range mode. @@ -569,6 +571,7 @@ impl<'a> HtmlLexer<'a> { range_start_pos: 0, range_end_pos: length, continuation_ends: Vec::new(), + recovered_texts: Vec::new(), range_line_offset: 0, range_col_offset: 0, } @@ -682,8 +685,7 @@ impl<'a> HtmlLexer<'a> { self.tokens.push(HtmlToken::empty(HtmlTokenType::Eof, self.index, self.index)); - // Merge adjacent text tokens (Angular does this to combine empty text tokens with adjacent text) - let mut tokens = merge_text_tokens(std::mem::take(&mut self.tokens)); + let mut tokens = std::mem::take(&mut self.tokens); // Process escape sequences if enabled if self.escaped_string { @@ -786,7 +788,20 @@ impl<'a> HtmlLexer<'a> { } if let Some((idx, end)) = cut_short_token { + let cut = &tokens[idx]; + let (cut_text, cut_start) = (cut.token_type == HtmlTokenType::Text, cut.start); tokens.truncate(idx); + // The text Angular lost began earlier: after an entity or interpolation, or at the backslash its cursor + // peeked after an earlier bad escape. + if cut_text + && tokens.last().is_some_and(|t| { + t.token_type == HtmlTokenType::Text + && t.end == cut_start + && (t.start == t.end || self.recovered_texts.contains(&t.start)) + }) + { + tokens.pop(); + } tokens.push(HtmlToken::empty(HtmlTokenType::Eof, end, end)); } let offsets: Vec = errors_to_add.iter().map(|&(_, offset)| offset).collect(); @@ -798,7 +813,8 @@ impl<'a> HtmlLexer<'a> { self.errors.sort_by_key(|error| error.offset); } - HtmlTokenizeResult { tokens, errors: self.errors } + // Merge adjacent text tokens (Angular does this to combine empty text tokens with adjacent text) + HtmlTokenizeResult { tokens: merge_text_tokens(tokens), errors: self.errors } } /// Peeks at the raw current character (no escape processing). @@ -1048,6 +1064,7 @@ impl<'a> HtmlLexer<'a> { self.move_raw_to(end); // An escaped backslash, which the escape pass after tokenizing reads as `\`. self.tokens.push(HtmlToken::with_part(HtmlTokenType::Text, "\\\\", start, end)); + self.recovered_texts.push(start); return true; } } diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 1661dec08..170440af5 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2329,6 +2329,21 @@ mod escaped_code_points { ); } + #[test] + fn should_drop_only_the_text_an_escape_cut_short_ends() { + // The text before an instruction dropped at a bad escape is its own token, which Angular keeps; the text + // after it begins at the backslash, and is lost with it. Offsets are in bytes. + let invalid = ("Invalid hexadecimal escape sequence".to_string(), 6); + assert_eq!( + lex(r"Ć© Date: Fri, 4 Dec 2026 20:50:04 +0800 Subject: [PATCH 22/47] refactor(parser): say what parse_int_prefix does with a sign Co-Authored-By: Claude Opus 5.5 --- crates/oxc_angular_compiler/src/parser/html/lexer.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 41e821bcb..770309da3 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -336,8 +336,9 @@ fn split_attr_ns_prefix(name: &str) -> (&str, &str) { } /// The value JavaScript's `parseInt(digits, radix)` gives, for the values a character can have: leading whitespace -/// and a sign are skipped (`-0` is 0, which the cursor reads as NUL too), a `0x` prefix is allowed in base 16, and -/// the longest run of digits counts. None when it is NaN. +/// is skipped, a `0x` prefix is allowed in base 16, and the longest run of digits counts. None when it is NaN. +/// A sign is skipped too, so a negative value reads as its absolute value: right for `-0`, which the cursor reads as +/// NUL too, while for `\x-5` Angular's `String.fromCodePoint` throws a `RangeError` and this reads U+0005. fn parse_int_prefix(digits: &str, radix: u32) -> Option { let digits = digits.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}'); let digits = digits.strip_prefix(['+', '-']).unwrap_or(digits); From 0ac5a26db29b4ac61420de87398cf4f2adfaeefb Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 20:56:27 +0800 Subject: [PATCH 23/47] refactor(parser): avoid casts and closures clippy warns about Co-Authored-By: Claude Opus 5.5 --- crates/oxc_angular_compiler/src/parser/html/lexer.rs | 6 +++--- crates/oxc_angular_compiler/tests/html_lexer_test.rs | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 770309da3..72cd8bb36 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -775,7 +775,7 @@ impl<'a> HtmlLexer<'a> { cut_short = true; token.end } else { - part_start as u32 + offset as u32 + u32::try_from(part_start + offset).unwrap_or(token.end) }; if !self.errors.iter().any(|e| e.offset == offset && e.msg == msg) { errors_to_add.push((msg, offset)); @@ -3101,8 +3101,8 @@ impl<'a> HtmlLexer<'a> { let text = &self.input[text_start as usize..self.index as usize]; let first_raw = self.reads_raw_at(text_start as usize); for (msg, offset) in process_escape_sequences(text, first_raw).1 { - if msg != EOF_ERROR { - let offset = text_start + offset as u32; + if let (false, Ok(offset)) = (msg == EOF_ERROR, u32::try_from(offset)) { + let offset = text_start + offset; let position = offsets_to_positions(self.input, &[offset])[0]; self.push_error(msg, position, offset, offset); } diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 170440af5..19c0c649b 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -546,7 +546,7 @@ mod attributes { .collect(); (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect::>()) }; - let parts = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + let parts = |parts: &[&str]| parts.iter().map(ToString::to_string).collect::>(); let start = || { vec![ (TagOpenStart, parts(&["", "a"]), 0, 2), @@ -2171,7 +2171,7 @@ mod escaped_line_continuations { assert_eq!(lex("\\\n\\x41"), (vec![text("\\x41", 2, 6), eof(6)], vec![])); let block_close = (HtmlTokenType::BlockClose, vec![], 6, 7); assert_eq!(lex("\\\n\\u{0}"), (vec![text("\\u{0", 2, 6), block_close, eof(7)], vec![])); - let parts = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + let parts = |parts: &[&str]| parts.iter().map(ToString::to_string).collect::>(); assert_eq!( lex("").0[3], (HtmlTokenType::AttrValueText, parts(&["\\x41"]), 8, 12) @@ -2224,7 +2224,7 @@ mod escaped_line_continuations { // continuation and the LF after it are one line ending. assert_eq!(lex("a\r\\\r\nb"), (vec![text("a\nb", 0, 6), eof(6)], vec![])); assert_eq!(lex("a\\\n\\\r\nb"), (vec![text("a\\\nb", 0, 7), eof(7)], vec![])); - let parts = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + let parts = |parts: &[&str]| parts.iter().map(ToString::to_string).collect::>(); let interpolation = (HtmlTokenType::Interpolation, parts(&["{{", "a"]), 4, 7); assert_eq!( lex("\\\r\\\r{{a"), @@ -2428,6 +2428,7 @@ mod escaped_nul_errors { #[test] fn should_keep_an_escaped_nul_where_angular_moves_past_it() { + use HtmlTokenType::*; // Scans that do not stop at EOF read the NUL as a character and go on: quoted attribute values, comments, // CDATA, raw text, doctypes and ICU raw text. let lexed = |input: &str| { @@ -2448,7 +2449,6 @@ mod escaped_nul_errors { let (ty, parts, start, end) = tokens[token].clone(); (ty, parts[0].clone(), start, end, tokens.last().map(|t| t.0)) }; - use HtmlTokenType::*; let s = |v: &str| v.to_string(); assert_eq!( nul_text(r#"c"#, 3), From 2309ba27e3b041efd2937278a819b82e1807b8fe Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 21:44:44 +0800 Subject: [PATCH 24/47] fix(parser): keep the text up to an ampersand in an unterminated attribute value Angular emits an `&` that starts no entity as a text token of its own, so only the text after the last `&`, entity or interpolation is lost when the quote is missing. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 27 +++++++-- .../tests/html_lexer_test.rs | 58 +++++++++++++++++++ 2 files changed, 79 insertions(+), 6 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 72cd8bb36..061794b0d 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -2965,6 +2965,9 @@ impl<'a> HtmlLexer<'a> { } let mut text_start = self.index; + // Where the text Angular has ended a token for stops: after an `&` that starts no entity, which it emits as + // a text token of its own. + let mut kept_end = text_start; // Only the quote ends the value: like Angular, read a NUL as text (an interpolation still stops there). while self.peek() != quote && self.index < self.length { @@ -3050,6 +3053,7 @@ impl<'a> HtmlLexer<'a> { // Emit empty text token after interpolation text_start = self.index; + kept_end = text_start; self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, "", @@ -3075,6 +3079,7 @@ impl<'a> HtmlLexer<'a> { self.tokens.push(entity_token); // Emit empty text token after entity text_start = self.index; + kept_end = text_start; self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, "", @@ -3087,6 +3092,7 @@ impl<'a> HtmlLexer<'a> { } else { // scan_entity reverted, so & is just regular text - advance past it self.advance(); + kept_end = self.index; } } else { self.advance(); @@ -3095,20 +3101,29 @@ impl<'a> HtmlLexer<'a> { if self.index >= self.length { // No closing quote: Angular's cursor throws at the end of the input before it ends the text token it is - // in, so that token is lost, with the empty one emitted after an interpolation or entity. The bad escapes - // its cursor read in it are still reported. + // in, so the text after the last interpolation, entity or `&` is lost, with the empty token emitted after + // an interpolation or entity. The bad escapes its cursor read in it are still reported. if self.escaped_string { - let text = &self.input[text_start as usize..self.index as usize]; - let first_raw = self.reads_raw_at(text_start as usize); + let text = &self.input[kept_end as usize..self.index as usize]; + let first_raw = self.reads_raw_at(kept_end as usize); for (msg, offset) in process_escape_sequences(text, first_raw).1 { if let (false, Ok(offset)) = (msg == EOF_ERROR, u32::try_from(offset)) { - let offset = text_start + offset; + let offset = kept_end + offset; let position = offsets_to_positions(self.input, &[offset])[0]; self.push_error(msg, position, offset, offset); } } } - if self.tokens.last().is_some_and(|t| { + if kept_end > text_start { + let text = &self.input[text_start as usize..kept_end as usize]; + let normalized = self.normalize_line_endings(text); + self.tokens.push(HtmlToken::with_part( + HtmlTokenType::AttrValueText, + &normalized, + text_start, + kept_end, + )); + } else if self.tokens.last().is_some_and(|t| { t.token_type == HtmlTokenType::AttrValueText && t.start == text_start && t.end == text_start diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 19c0c649b..6cf58d19d 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -584,6 +584,64 @@ mod attributes { let invalid = ("Invalid hexadecimal escape sequence".to_string(), 8); assert_eq!(lex(r#" = result + .tokens + .into_iter() + .skip(3) + .map(|t| (t.token_type, t.parts, t.start, t.end)) + .collect(); + (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect::>()) + }; + let value = |text: &str, start, end| (AttrValueText, vec![text.to_string()], start, end); + let eof = |offset| { + ((Eof, vec![], offset, offset), ("Unexpected character \"EOF\"".to_string(), offset)) + }; + for escaped in [false, true] { + let (eof_token, eof_error) = eof(8); + assert_eq!( + lex(r#" Date: Fri, 4 Dec 2026 21:47:20 +0800 Subject: [PATCH 25/47] fix(parser): read escapes across name and case value splits like Angular The escape pass took any part that ended inside `\x` or `\u` for the end of the input. But the raw `:` split of a tag name and the trim of an ICU case value can cut an escape. Now the digits are read from the input, so only a real end of the input cuts an escape short. Names split at the first `:` the cursor reads, so the `:` in `\x4:` is a digit, and an ICU case value is trimmed after its escapes are decoded. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 120 +++++++++++------- .../tests/html_lexer_test.rs | 57 +++++++++ 2 files changed, 133 insertions(+), 44 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 061794b0d..7d6440970 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -321,20 +321,6 @@ fn offsets_to_positions(input: &str, offsets: &[u32]) -> Vec<(u32, u32)> { positions } -/// Splits an attribute name into its namespace prefix and local name, like -/// Angular's `_consumePrefixAndName`: the prefix is the run of ASCII letters and -/// digits at the start, and only counts when a `:` follows it. So `xlink:href` -/// has the prefix `xlink`, while `(window:click)`, `on-window:click` and -/// `[attr.x:y]` have none. -/// Reference: lexer.ts (`_consumePrefixAndName`, `isPrefixEnd`) -fn split_attr_ns_prefix(name: &str) -> (&str, &str) { - let end = name.find(|c: char| !c.is_ascii_alphanumeric()).unwrap_or(name.len()); - match name[end..].strip_prefix(':') { - Some(local_name) if end > 0 => (&name[..end], local_name), - _ => ("", name), - } -} - /// The value JavaScript's `parseInt(digits, radix)` gives, for the values a character can have: leading whitespace /// is skipped, a `0x` prefix is allowed in base 16, and the longest run of digits counts. None when it is NaN. /// A sign is skipped too, so a negative value reads as its absolute value: right for `-0`, which the cursor reads as @@ -355,18 +341,24 @@ fn parse_int_prefix(digits: &str, radix: u32) -> Option { /// Returns (processed_text, errors), with error offsets in bytes into `text`. /// An escaped NUL decodes to `\0`: the lexer already ended the token where Angular's cursor peeks one as EOF, so any /// NUL left in a token is one Angular's cursor moved past. -/// Code-point escapes are read as Angular's cursor reads them (see `code_point_escape`): one cut short by the end of -/// the text is an EOF error there, unless it is NUL. +/// Only the first `len` bytes of `text` are decoded, but an escape starting there reads its digits from the rest of +/// `text`, as Angular's cursor reads them from the input: `text` runs to the end of the input when the token text is +/// a slice of it. Code-point escapes are read as Angular's cursor reads them (see `code_point_escape`): one cut short +/// by the end of `text` is an EOF error there, unless it is NUL. /// With `first_raw`, the first character is read as is, as Angular's cursor reads one after a line continuation. -fn process_escape_sequences(text: &str, first_raw: bool) -> (String, Vec<(String, usize)>) { - let mut result = String::with_capacity(text.len()); +fn process_escape_sequences( + text: &str, + len: usize, + first_raw: bool, +) -> (String, Vec<(String, usize)>) { + let mut result = String::with_capacity(len); let mut errors = Vec::new(); let mut i = 0; - if first_raw && let Some(ch) = text.chars().next() { + if first_raw && let Some(ch) = text[..len].chars().next() { result.push(ch); i = ch.len_utf8(); } - while let Some(ch) = text[i..].chars().next() { + while let Some(ch) = text.get(i..len).and_then(|rest| rest.chars().next()) { let next = text[i..].strip_prefix('\\').and_then(|rest| rest.chars().next()); let Some(next) = next else { result.push(ch); @@ -415,7 +407,7 @@ fn process_escape_sequences(text: &str, first_raw: bool) -> (String, Vec<(String '\n' | '\r' => { // A line continuation: as Angular's cursor, skip the backslash and one CR or LF (so a CRLF // leaves its LF), and read the character after it as is. - if let Some(ch) = text[i..].chars().next() { + if let Some(ch) = text.get(i..len).and_then(|rest| rest.chars().next()) { result.push(ch); i += ch.len_utf8(); } @@ -734,7 +726,7 @@ impl<'a> HtmlLexer<'a> { let content_start = marker_end + if after_continuation { 2 } else { 0 }; // The prefix of a tag or attribute name starts where the cursor starts the name: at the start of an // attribute name, after the `<` of an open tag, after the ` Some(start), HtmlTokenType::TagOpenStart | HtmlTokenType::IncompleteTagOpen @@ -749,21 +741,32 @@ impl<'a> HtmlLexer<'a> { // Process escape sequences in token parts for (part_idx, part) in token.parts.iter_mut().enumerate() { let part_start = match name_start { - Some(at) if part_idx == 1 && prefix_len > 0 => at + prefix_len + 1, + Some(at) + if part_idx == 1 + && prefix_len > 0 + && at + prefix_len < self.length as usize => + { + self.next_cursor_pos(at + prefix_len) + } Some(at) => at, None if part_idx == content_idx => content_start, None => start, }; - // (The closing tag of raw text has the name of its open tag, which may not be there.) - let first_raw = part.starts_with('\\') - && self.reads_raw_at(part_start) - && self - .input - .get(part_start..) - .is_some_and(|rest| rest.starts_with(part.as_str())); - let (processed, errs) = process_escape_sequences(part, first_raw); + // The input from the part on, when the part is a slice of it. (The closing tag of raw text has the + // name of its open tag, which may not be there.) + let rest = self + .input + .get(part_start..self.length as usize) + .filter(|rest| rest.starts_with(part.as_str())); + let first_raw = + part.starts_with('\\') && self.reads_raw_at(part_start) && rest.is_some(); + let (processed, errs) = + process_escape_sequences(rest.unwrap_or(part), part.len(), first_raw); *part = if processes_crs[token_idx] && part_idx == content_idx { normalize_line_endings(&processed) + } else if token.token_type == HtmlTokenType::ExpansionCaseValue { + // Angular trims the characters its cursor read. + processed.trim().to_string() } else { processed }; @@ -2460,6 +2463,42 @@ impl<'a> HtmlLexer<'a> { )); } + /// Splits the name from byte `start` to `end` into its prefix and name, at the first `:` the cursor reads + /// after characters that all pass `in_prefix`, as Angular's `_consumePrefixAndName` reads it: an escaped `:` + /// counts, a `:` inside an escape (the digits of `\x4:`) does not. Both are slices of the input, the name + /// starting where the cursor moves to past the `:`. + fn split_prefix( + &self, + start: u32, + end: u32, + in_prefix: fn(char) -> bool, + ) -> (&'a str, &'a str) { + let (start, end) = (start as usize, end as usize); + let mut pos = start; + while pos < end { + let ch = self.cursor_char_at(pos); + if ch == ':' && pos > start { + return ( + &self.input[start..pos], + &self.input[self.next_cursor_pos(pos).min(end)..end], + ); + } + if !in_prefix(ch) { + break; + } + pos = self.next_cursor_pos(pos); + } + ("", &self.input[start..end]) + } + + /// Splits an attribute name into its namespace prefix and local name, like Angular's `_consumePrefixAndName`: + /// the prefix is the run of ASCII letters and digits at the start, and only counts when a `:` follows it. So + /// `xlink:href` has the prefix `xlink`, while `(window:click)`, `on-window:click` and `[attr.x:y]` have none. + /// Reference: lexer.ts (`_consumePrefixAndName`, `isPrefixEnd`) + fn split_attr_ns_prefix(&self, start: u32, end: u32) -> (&'a str, &'a str) { + self.split_prefix(start, end, |ch| ch.is_ascii_alphanumeric()) + } + /// Scans a tag name (with optional namespace prefix). fn scan_tag_name(&mut self) -> (String, String) { self.skip_whitespace(); @@ -2474,16 +2513,9 @@ impl<'a> HtmlLexer<'a> { self.advance(); } - let full_name = &self.input[name_start as usize..self.index as usize]; - - // Split on colon for namespace prefix - if let Some(colon_pos) = full_name.find(':') { - let prefix = &full_name[..colon_pos]; - let name = &full_name[colon_pos + 1..]; - (prefix.to_string(), name.to_string()) - } else { - (String::new(), full_name.to_string()) - } + // Split on the first colon for namespace prefix + let (prefix, name) = self.split_prefix(name_start, self.index, |_| true); + (prefix.to_string(), name.to_string()) } /// Scans a selectorless directive: @DirectiveName or @DirectiveName(attrs) @@ -2592,7 +2624,7 @@ impl<'a> HtmlLexer<'a> { break; } - let (prefix, name) = split_attr_ns_prefix(attr_name); + let (prefix, name) = self.split_attr_ns_prefix(attr_start, self.index); self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::AttrName, @@ -2738,7 +2770,7 @@ impl<'a> HtmlLexer<'a> { } } - let (prefix, name) = split_attr_ns_prefix(attr_full_name); + let (prefix, name) = self.split_attr_ns_prefix(attr_start, self.index); self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::AttrName, @@ -3106,7 +3138,7 @@ impl<'a> HtmlLexer<'a> { if self.escaped_string { let text = &self.input[kept_end as usize..self.index as usize]; let first_raw = self.reads_raw_at(kept_end as usize); - for (msg, offset) in process_escape_sequences(text, first_raw).1 { + for (msg, offset) in process_escape_sequences(text, text.len(), first_raw).1 { if let (false, Ok(offset)) = (msg == EOF_ERROR, u32::try_from(offset)) { let offset = kept_end + offset; let position = offsets_to_positions(self.input, &[offset])[0]; diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 6cf58d19d..3a3908457 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2428,6 +2428,63 @@ mod escaped_code_points { assert_eq!(lex(r"").0[1], + lex_escaped("").0[1], (HtmlTokenType::RawText, parts(&["\\x41"]), 6, 10) ); // After a start marker too. let interpolation = (HtmlTokenType::Interpolation, parts(&["{{", "\\u{", "}}"]), 0, 9); assert_eq!( - lex("{{\\\n\\u{}}"), + lex_escaped("{{\\\n\\u{}}"), (vec![text("", 0, 0), interpolation, text("", 9, 9), eof(9)], vec![]) ); let pi = (HtmlTokenType::ProcessingInstruction, parts(&["\\x0--"]), 0, 10); - assert_eq!(lex(""), (vec![pi, eof(10)], vec![])); + assert_eq!(lex_escaped(""), (vec![pi, eof(10)], vec![])); // And after a processing instruction that ends in error. let unexpected = ("Unexpected character \"\\\"".to_string(), 6); - assert_eq!(lex(""), (vec![text("\\xZZ>", 6, 11), eof(11)], vec![unexpected])); + assert_eq!( + lex_escaped(""), + (vec![text("\\xZZ>", 6, 11), eof(11)], vec![unexpected]) + ); } #[test] @@ -2258,46 +2276,46 @@ mod escaped_line_continuations { (ty, vec![prefix.to_string(), name.to_string()], start, end) }; // Where the cursor starts the name: after the `").0[0], tag(TagClose, "", "\\x41", 0, 9)); - assert_eq!(lex("").0[0], tag(TagClose, "", "\\x41", 0, 10)); + assert_eq!(lex_escaped("").0[0], tag(TagClose, "", "\\x41", 0, 9)); + assert_eq!(lex_escaped("").0[0], tag(TagClose, "", "\\x41", 0, 10)); // Not after a prefix, nor at a tag starting there. - assert_eq!(lex("").0[1], tag(AttrName, "x", "A", 5, 11)); - assert_eq!(lex("\\\n<\\x41>").0[0], tag(TagOpenStart, "", "A", 2, 7)); - assert_eq!(lex("\\\n").0[0], tag(TagOpenStart, "a", "b", 2, 9)); - assert_eq!(lex("\\\n").0[0], tag(TagClose, "", "A", 2, 9)); + assert_eq!(lex_escaped("").0[1], tag(AttrName, "x", "A", 5, 11)); + assert_eq!(lex_escaped("\\\n<\\x41>").0[0], tag(TagOpenStart, "", "A", 2, 7)); + assert_eq!(lex_escaped("\\\n").0[0], tag(TagOpenStart, "a", "b", 2, 9)); + assert_eq!(lex_escaped("\\\n").0[0], tag(TagClose, "", "A", 2, 9)); } #[test] fn should_skip_only_the_cr_of_a_crlf() { // The LF is read as is, and an escape after it is decoded. - assert_eq!(lex("a\\\r\nb"), (vec![text("a\nb", 0, 5), eof(5)], vec![])); - assert_eq!(lex("a\\\r\n\\x41"), (vec![text("a\nA", 0, 8), eof(8)], vec![])); + assert_eq!(lex_escaped("a\\\r\nb"), (vec![text("a\nb", 0, 5), eof(5)], vec![])); + assert_eq!(lex_escaped("a\\\r\n\\x41"), (vec![text("a\nA", 0, 8), eof(8)], vec![])); // An escaped NUL there ends the input: the bad escape after it is not read. - assert_eq!(lex("a\\\r\n\\x00\\xzz").1, []); + assert_eq!(lex_escaped("a\\\r\n\\x00\\xzz").1, []); } #[test] fn should_normalize_line_endings_after_decoding_escapes() { // Angular's `_processCarriageReturns` runs on the characters the cursor reads: a CR before a line // continuation and the LF after it are one line ending. - assert_eq!(lex("a\r\\\r\nb"), (vec![text("a\nb", 0, 6), eof(6)], vec![])); - assert_eq!(lex("a\\\n\\\r\nb"), (vec![text("a\\\nb", 0, 7), eof(7)], vec![])); + assert_eq!(lex_escaped("a\r\\\r\nb"), (vec![text("a\nb", 0, 6), eof(6)], vec![])); + assert_eq!(lex_escaped("a\\\n\\\r\nb"), (vec![text("a\\\nb", 0, 7), eof(7)], vec![])); let parts = |parts: &[&str]| parts.iter().map(ToString::to_string).collect::>(); let interpolation = (HtmlTokenType::Interpolation, parts(&["{{", "a"]), 4, 7); assert_eq!( - lex("\\\r\\\r{{a"), + lex_escaped("\\\r\\\r{{a"), (vec![text("\\\n", 2, 4), interpolation, text("", 7, 7), eof(7)], vec![]) ); - let part = |input: &str, token: usize| lex(input).0[token].1[0].clone(); + let part = |input: &str, token: usize| lex_escaped(input).0[token].1[0].clone(); assert_eq!(part("", 3), "x\ny"); assert_eq!(part("", 1), "x\ny"); assert_eq!(part("", 1), "x\ny"); assert_eq!(part("", 2), "x\ny"); assert_eq!(part("", 2), "x\ny"); - assert_eq!(lex("{{x\r\\\r\ny}}").0[1].1[1], "x\ny"); + assert_eq!(lex_escaped("{{x\r\\\r\ny}}").0[1].1[1], "x\ny"); // An escaped CR is a CR too. - assert_eq!(lex(r"a\r").0[0].1[0], "a\n"); - assert_eq!(lex("a\\r\nb"), (vec![text("a\nb", 0, 5), eof(5)], vec![])); + assert_eq!(lex_escaped(r"a\r").0[0].1[0], "a\n"); + assert_eq!(lex_escaped("a\\r\nb"), (vec![text("a\nb", 0, 5), eof(5)], vec![])); // A doctype and a processing instruction keep their CRs. assert_eq!(part(r"", 0), "DOCTYPE a\rb"); assert_eq!(part("z", 0), "x\r\n"); @@ -2312,9 +2330,9 @@ mod escaped_line_continuations { #[test] fn should_report_nothing_after_an_escaped_nul_in_text() { // Angular's text ends at the NUL, which ends the input: the open tag after it is not read. - assert_eq!(lex("a\\0, u32, u32); - type Lexed = (Vec, Vec<(String, u32)>); - - /// Tokens with their spans, and errors with their offsets, of an escaped string. - fn lex(input: &str) -> Lexed { - let result = HtmlLexer::new(input).with_escaped_string(true).tokenize(); - let tokens = - result.tokens.into_iter().map(|t| (t.token_type, t.parts, t.start, t.end)).collect(); - (tokens, result.errors.into_iter().map(|e| (e.msg, e.offset)).collect()) - } - - fn text(value: &str, start: u32, end: u32) -> Token { - (HtmlTokenType::Text, vec![value.to_string()], start, end) - } - - fn eof(offset: u32) -> Token { - (HtmlTokenType::Eof, vec![], offset, offset) - } - - fn eof_error(offset: u32) -> (String, u32) { - ("Unexpected character \"EOF\"".to_string(), offset) - } - #[test] fn should_read_the_digits_like_parse_int() { // `parseInt("0\\", 16)` is 0: an escaped NUL, which ends the text. - let (tokens, errors) = lex(r"a\x0\b"); + let (tokens, errors) = lex_escaped(r"a\x0\b"); assert_eq!((&tokens[0].1, errors), (&vec!["a".to_string()], vec![])); } #[test] fn should_read_invalid_digits_as_a_backslash() { let invalid = ("Invalid hexadecimal escape sequence".to_string(), 2); - assert_eq!(lex(r"\xzzb"), (vec![text("\\b", 0, 5), eof(5)], vec![invalid])); + assert_eq!(lex_escaped(r"\xzzb"), (vec![text("\\b", 0, 5), eof(5)], vec![invalid])); } #[test] fn should_drop_the_token_at_an_escape_cut_short_by_the_end_of_the_input() { // Angular's cursor throws inside the token: it is lost, and the error is the one at the end of the input. - assert_eq!(lex(r"a\u{12"), (vec![eof(6)], vec![eof_error(6)])); - assert_eq!(lex(r"{{a\u{"), (vec![text("", 0, 0), eof(6)], vec![eof_error(6)])); - assert_eq!(lex(r#"e"), + lex_escaped(r"e"), (vec![text("\\cd?>e", 4, 13), eof(13)], vec![invalid(6)]) ); - assert_eq!(lex(r"e"), (vec![text("\\'?>e", 3, 11), eof(11)], vec![invalid(5)])); - assert_eq!(lex(r"x\xzz"), (vec![text("x\\", 0, 9), eof(9)], vec![invalid(7)])); + assert_eq!( + lex_escaped(r"e"), + (vec![text("\\'?>e", 3, 11), eof(11)], vec![invalid(5)]) + ); + assert_eq!(lex_escaped(r"x\xzz"), (vec![text("x\\", 0, 9), eof(9)], vec![invalid(7)])); let comment_start = (HtmlTokenType::CommentStart, vec![], 0, 4); assert_eq!( - lex(r"c"), + lex_escaped(r"c"), (vec![comment_start, text("\\b-->c", 5, 14), eof(14)], vec![invalid(7)]) ); } @@ -2393,20 +2391,23 @@ mod escaped_code_points { // after it begins at the backslash, and is lost with it. Offsets are in bytes. let invalid = ("Invalid hexadecimal escape sequence".to_string(), 6); assert_eq!( - lex(r"Ć©\xzz"), + lex_escaped(r"\xzz\xzz"), (vec![text("\\\\", 0, 13), eof(13)], vec![invalid(2), invalid(11)]) ); } @@ -2415,18 +2416,21 @@ mod escaped_code_points { fn should_report_eof_after_invalid_digits_that_end_the_input() { // The cursor fails to move past them: the token is lost, and the input ends. let invalid = |offset| ("Invalid hexadecimal escape sequence".to_string(), offset); - assert_eq!(lex(r"\xz"), (vec![eof(3)], vec![invalid(2), eof_error(3)])); - assert_eq!(lex(r"a\xz"), (vec![eof(4)], vec![invalid(3), eof_error(4)])); - assert_eq!(lex(r"a\uZZZ"), (vec![eof(6)], vec![invalid(3), eof_error(6)])); - assert_eq!(lex(r"{{a\xz"), (vec![text("", 0, 0), eof(6)], vec![invalid(5), eof_error(6)])); + assert_eq!(lex_escaped(r"\xz"), (vec![eof(3)], vec![invalid(2), eof_error(3)])); + assert_eq!(lex_escaped(r"a\xz"), (vec![eof(4)], vec![invalid(3), eof_error(4)])); + assert_eq!(lex_escaped(r"a\uZZZ"), (vec![eof(6)], vec![invalid(3), eof_error(6)])); + assert_eq!( + lex_escaped(r"{{a\xz"), + (vec![text("", 0, 0), eof(6)], vec![invalid(5), eof_error(6)]) + ); } #[test] fn should_read_nothing_after_an_escape_cut_short_by_the_end_of_the_input() { // Angular's cursor throws at the end of the input: the bad escape after it is never read. - assert_eq!(lex(r"a\u{\xzz"), (vec![eof(8)], vec![eof_error(8)])); - assert_eq!(lex(r"z").0[3], (Text, vec![s("z")], 11, 12)); - assert_eq!(lexed(r"z").0[1], (Text, vec![s("z")], 15, 16)); + assert_eq!(lex_icu(r"z").0[3], (Text, vec![s("z")], 11, 12)); + assert_eq!(lex_icu(r"z").0[1], (Text, vec![s("z")], 15, 16)); } #[test] From 6d5f88f2abd7fccbed1296367ea4021d72b0904a Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:51:15 +0800 Subject: [PATCH 37/47] test(parser): drop the test that pins a signed escape Angular throws a RangeError for `\x-5`, so the lexer's U+0005 is not an Angular value to hold; the doc of parse_int_prefix keeps the note. Co-Authored-By: Claude Opus 5.5 --- crates/oxc_angular_compiler/tests/html_lexer_test.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index affa26a84..44b74b21c 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2265,13 +2265,6 @@ mod escaped_code_points { assert_eq!((&tokens[0].1, errors), (&vec!["a".to_string()], vec![])); } - #[test] - fn should_read_a_signed_escape_as_its_absolute_value() { - // `parseInt("-5", 16)` is -5, for which Angular's `String.fromCodePoint` throws a `RangeError` out of the - // lexer. This pins what the lexer reads instead: U+0005. - assert_eq!(lex_escaped(r"a\x-5b"), (vec![text("a\u{5}b", 0, 6), eof(6)], vec![])); - } - #[test] fn should_read_invalid_digits_as_a_backslash() { let invalid = ("Invalid hexadecimal escape sequence".to_string(), 2); From a3897887acc169f1e6bb1e5bce076bb80bb327ff Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:51:55 +0800 Subject: [PATCH 38/47] fix(parser): read a tag prefix of letters and digits only like Angular Angular's `_consumePrefixAndName` uses `isPrefixEnd` for tag names too, so `` and `` have no prefix: a `:` after any other character is part of the name. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 35 ++++++----------- .../tests/html_lexer_test.rs | 38 +++++++++++++++++++ 2 files changed, 50 insertions(+), 23 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index b325de941..c0909852b 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -2475,16 +2475,13 @@ impl<'a> HtmlLexer<'a> { )); } - /// Splits the name from byte `start` to `end` into its prefix and name, at the first `:` the cursor reads - /// after characters that all pass `in_prefix`, as Angular's `_consumePrefixAndName` reads it: an escaped `:` - /// counts, a `:` inside an escape (the digits of `\x4:`) does not. Both are slices of the input, the name - /// starting where the cursor moves to past the `:`. - fn split_prefix( - &self, - start: u32, - end: u32, - in_prefix: fn(char) -> bool, - ) -> (&'a str, &'a str) { + /// Splits the tag or attribute name from byte `start` to `end` into its namespace prefix and name, as Angular's + /// `_consumePrefixAndName` (with `isPrefixEnd`) reads it: the prefix is the run of ASCII letters and digits the + /// cursor reads at the start, and only counts when a `:` follows it. So `xlink:href` has the prefix `xlink`, while + /// `a-b:c`, `(window:click)`, `on-window:click` and `[attr.x:y]` have none. An escaped `:` or letter counts, a `:` + /// inside an escape (the digits of `\x4:`) does not. Both are slices of the input, the name starting where the + /// cursor moves to past the `:`. + fn split_prefix(&self, start: u32, end: u32) -> (&'a str, &'a str) { let (start, end) = (start as usize, end as usize); let mut pos = start; while pos < end { @@ -2495,7 +2492,7 @@ impl<'a> HtmlLexer<'a> { &self.input[self.next_cursor_pos(pos).min(end)..end], ); } - if !in_prefix(ch) { + if !ch.is_ascii_alphanumeric() { break; } pos = self.next_cursor_pos(pos); @@ -2503,14 +2500,6 @@ impl<'a> HtmlLexer<'a> { ("", &self.input[start..end]) } - /// Splits an attribute name into its namespace prefix and local name, like Angular's `_consumePrefixAndName`: - /// the prefix is the run of ASCII letters and digits at the start, and only counts when a `:` follows it. So - /// `xlink:href` has the prefix `xlink`, while `(window:click)`, `on-window:click` and `[attr.x:y]` have none. - /// Reference: lexer.ts (`_consumePrefixAndName`, `isPrefixEnd`) - fn split_attr_ns_prefix(&self, start: u32, end: u32) -> (&'a str, &'a str) { - self.split_prefix(start, end, |ch| ch.is_ascii_alphanumeric()) - } - /// Scans a tag name (with optional namespace prefix). fn scan_tag_name(&mut self) -> (String, String) { self.skip_whitespace(); @@ -2525,8 +2514,8 @@ impl<'a> HtmlLexer<'a> { self.advance(); } - // Split on the first `:` the cursor reads for namespace prefix - let (prefix, name) = self.split_prefix(name_start, self.index, |_| true); + // Split off the namespace prefix + let (prefix, name) = self.split_prefix(name_start, self.index); (prefix.to_string(), name.to_string()) } @@ -2636,7 +2625,7 @@ impl<'a> HtmlLexer<'a> { break; } - let (prefix, name) = self.split_attr_ns_prefix(attr_start, self.index); + let (prefix, name) = self.split_prefix(attr_start, self.index); self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::AttrName, @@ -2782,7 +2771,7 @@ impl<'a> HtmlLexer<'a> { } } - let (prefix, name) = self.split_attr_ns_prefix(attr_start, self.index); + let (prefix, name) = self.split_prefix(attr_start, self.index); self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::AttrName, diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 44b74b21c..97ae05a0b 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -271,6 +271,44 @@ mod basic_tags { tag_open.parts ); } + + #[test] + fn should_read_a_tag_prefix_of_letters_and_digits_only() { + // As Angular's `_consumePrefixAndName` (`isPrefixEnd`): a `:` after any other character is part of the name. + // Expected values are from Angular 22.3.0. + use HtmlTokenType::*; + assert_eq!( + lex("", false), + ( + vec![ + token(TagOpenStart, &["", "a-b:c"], 0, 6), + token(TagOpenEnd, &[], 6, 7), + eof(7) + ], + vec![] + ) + ); + assert_eq!( + lex("", false), + (vec![token(TagClose, &["", "a-b:c"], 0, 8), eof(8)], vec![]) + ); + // An escaped `:` too. + assert_eq!( + lex_escaped(r""), + ( + vec![ + token(TagOpenStart, &["", "a;:b"], 0, 8), + token(TagOpenEnd, &[], 8, 9), + eof(9) + ], + vec![] + ) + ); + assert_eq!( + lex_escaped(r""), + (vec![token(TagClose, &["", "a;:b"], 0, 10), eof(10)], vec![]) + ); + } } // ============================================================================ From f633027b431883fb82ebb7bea3cfec90bb6c519a Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:52:03 +0800 Subject: [PATCH 39/47] fix(parser): trim an expansion case value like JavaScript Angular trims the case value with `String.prototype.trim`, which keeps U+0085 and removes U+FEFF; `parseInt` skips the same whitespace. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 19 ++++++++--- .../tests/html_lexer_test.rs | 32 +++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index c0909852b..d63b85ca7 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -346,12 +346,23 @@ fn offsets_to_positions(input: &str, offsets: &[u32]) -> Vec<(u32, u32)> { positions } +/// Whether JavaScript's `String.prototype.trim` and `parseInt` skip `ch` as whitespace: Rust's whitespace but +/// U+0085, which JavaScript does not count, and U+FEFF, which it does. +fn is_js_whitespace(ch: char) -> bool { + (ch.is_whitespace() && ch != '\u{85}') || ch == '\u{feff}' +} + +/// `text` without the whitespace JavaScript's `String.prototype.trim` removes at its ends. +fn js_trim(text: &str) -> &str { + text.trim_matches(is_js_whitespace) +} + /// The value JavaScript's `parseInt(digits, radix)` gives, for the values a character can have: leading whitespace /// is skipped, a `0x` prefix is allowed in base 16, and the longest run of digits counts. None when it is NaN. /// A sign is skipped too, so a negative value reads as its absolute value: right for `-0`, which the cursor reads as /// NUL too, while for `\x-5` Angular's `String.fromCodePoint` throws a `RangeError` and this reads U+0005. fn parse_int_prefix(digits: &str, radix: u32) -> Option { - let digits = digits.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}'); + let digits = digits.trim_start_matches(is_js_whitespace); let digits = digits.strip_prefix(['+', '-']).unwrap_or(digits); let digits = if radix == 16 { digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0X")).unwrap_or(digits) @@ -799,8 +810,8 @@ impl<'a> HtmlLexer<'a> { *part = if processes_crs[token_idx] && part_idx == content_idx { normalize_line_endings(&processed) } else if token.token_type == HtmlTokenType::ExpansionCaseValue { - // Angular trims the characters its cursor read. - processed.trim().to_string() + // Angular trims the characters its cursor read, with JavaScript's `trim`. + js_trim(&processed).to_string() } else { processed }; @@ -3474,7 +3485,7 @@ impl<'a> HtmlLexer<'a> { fn scan_expansion_case_start(&mut self) { // Read case value (until '{') let value_start = self.index; - let value = self.read_until('{').trim().to_string(); + let value = js_trim(&self.read_until('{')).to_string(); if self.index >= self.length { // As Angular's `_readUntil`: the case value token is dropped. self.error("Unexpected character \"EOF\""); diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 97ae05a0b..34c76cde9 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2491,6 +2491,14 @@ mod escaped_code_points { ]); assert_eq!(lex_icu(r"{a, select, b {c}}\xzz {d}}"), (tokens, vec![invalid(ICU_HINT, 20)])); } + + #[test] + fn should_skip_only_javascript_whitespace_before_the_digits() { + // `parseInt` skips the whitespace `String.prototype.trim` removes, which U+0085 is not. Expected values are + // from Angular 22.3.0. + let invalid = ("Invalid hexadecimal escape sequence".to_string(), 3); + assert_eq!(lex_escaped("\\u{\u{85} 41}"), (vec![text("\\", 0, 9), eof(9)], vec![invalid])); + } } /// An escaped NUL where a character is required, which Angular reports as EOF. Expected values are from @@ -3538,6 +3546,30 @@ mod expansion_forms { ] ); } + + #[test] + fn should_trim_a_case_value_like_javascript() { + // `String.prototype.trim` keeps U+0085. Expected values are from Angular 22.3.0. + let case_value = |input: &str, escaped| { + let result = HtmlLexer::new(input) + .with_escaped_string(escaped) + .with_expansion_forms(true) + .tokenize(); + result + .tokens + .into_iter() + .find(|t| t.token_type == HtmlTokenType::ExpansionCaseValue) + .map(|t| (t.parts, t.start, t.end)) + }; + assert_eq!( + case_value("{a, select, b\u{85} {c}}", false), + Some((vec!["b\u{85}".to_string()], 12, 16)) + ); + assert_eq!( + case_value(r"{a, select, b\x85 {c}}", true), + Some((vec!["b\u{85}".to_string()], 12, 18)) + ); + } } // ============================================================================ From 6b045cc53a62af0af33f607071aa7a124cb44fa4 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:52:12 +0800 Subject: [PATCH 40/47] fix(parser): find the content after an escaped start marker like Angular The content of an interpolation, a processing instruction or a doctype starts where the cursor moves to past the marker's characters, any of which may be an escape, and a line continuation after it. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 16 +++++--- .../tests/html_lexer_test.rs | 40 +++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index d63b85ca7..41b97daf5 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -756,19 +756,23 @@ impl<'a> HtmlLexer<'a> { 'tokens: for (token_idx, token) in tokens.iter_mut().enumerate() { // Where each part starts: at the token start, but the content of an interpolation, a processing - // instruction or a doctype after its start marker and a line continuation there. Angular's cursor - // reads the character after one as is. + // instruction or a doctype after its start marker and a line continuation there, where the cursor + // moves to past the marker's characters (any of them may be an escape). Angular's cursor reads the + // character after a line continuation as is. let start = token.effective_full_start() as usize; - let (content_idx, marker_len) = match token.token_type { + let (content_idx, marker_chars) = match token.token_type { HtmlTokenType::Interpolation | HtmlTokenType::AttrValueInterpolation => { (1, token.parts.first().map_or(0, String::len)) } HtmlTokenType::ProcessingInstruction | HtmlTokenType::DocType => (0, 2), _ => (0, 0), }; - let marker_end = start + marker_len; - let after_continuation = marker_len > 0 && self.is_line_continuation_at(marker_end); - let content_start = marker_end + if after_continuation { 2 } else { 0 }; + let mut content_start = start; + for _ in 0..marker_chars { + if content_start < self.length as usize { + content_start = self.next_cursor_pos(content_start); + } + } // The prefix of a tag or attribute name starts where the cursor starts the name: at the start of an // attribute name, after the `<` of an open tag, after the `"), + ( + vec![ + token(TagOpenStart, &["", "a"], 0, 2), + token(AttrName, &["", "b"], 3, 4), + token(AttrQuote, &["\""], 5, 6), + token(AttrValueText, &[""], 6, 6), + token(AttrValueInterpolation, &["{{", "\\xzz", "}}"], 6, 19), + token(AttrValueText, &[""], 19, 19), + token(AttrQuote, &["\""], 19, 20), + token(TagOpenEnd, &[], 20, 21), + eof(21), + ], + vec![] + ) + ); + assert_eq!( + lex_escaped("\\x3c?\\\n\\xzz?>"), + (vec![token(ProcessingInstruction, &["\\xzz"], 0, 13), eof(13)], vec![]) + ); + } } /// Code-point escapes (`\x`, `\u`, `\u{...}`) in the text of tokens, read as Angular's cursor reads them. Expected From 376f36720e72d22766dcc514f6d96eae19aeefee Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:52:20 +0800 Subject: [PATCH 41/47] fix(parser): keep an empty unquoted attribute value before a NUL Angular's value text ends at the NUL, raw or escaped, which its cursor peeks as EOF, and the empty token stays. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 4 +++- .../tests/html_lexer_test.rs | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 41b97daf5..3e0d28188 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -2947,7 +2947,9 @@ impl<'a> HtmlLexer<'a> { } } let value = &self.input[text_start as usize..self.index as usize]; - if !value.is_empty() { + // Angular's text token is there even when the value is empty; this keeps the empty one before a NUL, + // raw or escaped, where the input ends for Angular's cursor. + if !value.is_empty() || self.at_nul() { self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, value, diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 507f472fc..e125b6ee0 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -698,6 +698,23 @@ mod attributes { (vec![value("&", 6, 10), eof(10)], vec![eof_error(10)]) ); } + + #[test] + fn should_keep_an_empty_unquoted_value_before_a_nul() { + // Angular's value text ends at the NUL, which its cursor peeks as EOF. Expected values are from Angular 22.3.0. + use HtmlTokenType::*; + let tokens = |value_at| { + vec![ + token(IncompleteTagOpen, &["", "a"], 0, 2), + token(AttrName, &["", "x"], 3, 4), + token(AttrValueText, &[""], value_at, value_at), + eof(value_at), + ] + }; + assert_eq!(lex_escaped(r" Date: Fri, 4 Dec 2026 22:52:28 +0800 Subject: [PATCH 42/47] fix(parser): drop an end tag at a bad escape inside it like Angular Angular's cursor throws when it moves onto a bad escape anywhere in the end tag, in its name or the whitespace around it, not only after its `>`. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 36 ++++++++++++++++--- .../tests/html_lexer_test.rs | 11 ++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 3e0d28188..b1d20a921 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -1758,6 +1758,22 @@ impl<'a> HtmlLexer<'a> { } } + /// Advances while `pred` holds for the character the cursor peeks (never past a NUL or the end of the input). + /// Returns whether the cursor stopped at a bad escape instead, which Angular's cursor throws for: the token being + /// read is dropped, and the lexer recovers as Angular's `tokenize` does (see `recover_at_bad_escape`). + fn advance_while_no_bad_escape(&mut self, pred: impl Fn(char) -> bool) -> bool { + loop { + if self.recover_at_bad_escape() { + return true; + } + let ch = self.peek(); + if ch == chars::EOF || !pred(ch) { + return false; + } + self.advance(); + } + } + /// Skips whitespace characters. fn skip_whitespace(&mut self) { while chars::is_whitespace(self.peek()) { @@ -2462,12 +2478,24 @@ impl<'a> HtmlLexer<'a> { return; } - // Scan tag name - let (prefix, name) = self.scan_tag_name(); + // As Angular's `_consumeTagClose`: whitespace, the name and whitespace. Its cursor throws when it moves onto + // a bad escape anywhere in the end tag, which drops it. + if self.advance_while_no_bad_escape(chars::is_whitespace) { + return; + } + let name_start = self.index; + if self.advance_while_no_bad_escape(|ch| { + !chars::is_whitespace(ch) && !matches!(ch, '>' | '/' | '<') + }) { + return; + } + let (prefix, name) = self.split_prefix(name_start, self.index); + let (prefix, name) = (prefix.to_string(), name.to_string()); // An empty name is allowed (``), as in Angular's `_consumeTagClose`. - // Skip whitespace - self.skip_whitespace(); + if self.advance_while_no_bad_escape(chars::is_whitespace) { + return; + } // A missing `>` is an error at the character found instead, and the end tag // is dropped, as Angular's `_requireCharCode` throws out of `_consumeTagClose`. diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index e125b6ee0..5f49dade9 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -4099,6 +4099,17 @@ mod closing_tags { let result = tokenize(""), (vec![eof(10)], vec![eof_error(10)])); + assert_eq!(lex_escaped(r""), (vec![eof(8)], vec![eof_error(8)])); + assert_eq!(lex_escaped(r""), (vec![eof(8)], vec![eof_error(8)])); + let invalid = ("Invalid hexadecimal escape sequence".to_string(), 6); + assert_eq!(lex_escaped(r"b"), (vec![text("\\>b", 4, 10), eof(10)], vec![invalid])); + } } // ============================================================================ From 032b4b01dbbb01083d8abfd6e4a8f9ce2bf10f6c Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:52:36 +0800 Subject: [PATCH 43/47] fix(parser): end an end tag name at a quote or `=` like Angular Angular's `_consumeTagClose` reads the name up to `isNameEnd`, so the missing `>` is an error at the quote or `=`, and the rest is text. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 16 ++++++++----- .../tests/html_lexer_test.rs | 23 +++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index b1d20a921..d8256be37 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -2478,15 +2478,13 @@ impl<'a> HtmlLexer<'a> { return; } - // As Angular's `_consumeTagClose`: whitespace, the name and whitespace. Its cursor throws when it moves onto - // a bad escape anywhere in the end tag, which drops it. + // As Angular's `_consumeTagClose`: whitespace, the name up to `isNameEnd` (so `=` and quotes end it too) and + // whitespace. Its cursor throws when it moves onto a bad escape anywhere in the end tag, which drops it. if self.advance_while_no_bad_escape(chars::is_whitespace) { return; } let name_start = self.index; - if self.advance_while_no_bad_escape(|ch| { - !chars::is_whitespace(ch) && !matches!(ch, '>' | '/' | '<') - }) { + if self.advance_while_no_bad_escape(|ch| !Self::is_name_end(ch)) { return; } let (prefix, name) = self.split_prefix(name_start, self.index); @@ -2543,7 +2541,13 @@ impl<'a> HtmlLexer<'a> { ("", &self.input[start..end]) } - /// Scans a tag name (with optional namespace prefix). + /// Whether `ch` ends a tag or attribute name, as Angular's `isNameEnd`. + fn is_name_end(ch: char) -> bool { + chars::is_whitespace(ch) || matches!(ch, '>' | '<' | '/' | '\'' | '"' | '=' | chars::EOF) + } + + /// Scans the name (with optional namespace prefix) of an open tag. Unlike Angular's `isNameEnd`, a quote or `=` + /// does not end it. fn scan_tag_name(&mut self) -> (String, String) { self.skip_whitespace(); diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 5f49dade9..f7604b8a5 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -4100,6 +4100,29 @@ mod closing_tags { assert!(!result.errors.is_empty()); } + #[test] + fn should_end_a_closing_tag_name_like_angular() { + // As Angular's `isNameEnd`, a quote or `=` ends the name too: the missing `>` is an error there, and the rest + // is text. Expected values are from Angular 22.3.0. + let unexpected = |ch: &str, offset| (format!("Unexpected character \"{ch}\""), offset); + assert_eq!( + lex("", false), + (vec![text("'b>", 3, 6), eof(6)], vec![unexpected("'", 3)]) + ); + assert_eq!( + lex_escaped(" Date: Fri, 4 Dec 2026 22:52:45 +0800 Subject: [PATCH 44/47] fix(parser): check the character the cursor reads after `@let` The whitespace Angular requires after `@let` is the character its cursor reads, so an escaped `@` or whitespace counts. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 10 +++------- .../tests/html_lexer_test.rs | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index d8256be37..cc991bfbd 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -1277,13 +1277,9 @@ impl<'a> HtmlLexer<'a> { // Check for @let declarations (only if tokenize_let is enabled) if self.tokenize_let && self.peek() == '@' && self.starts_with("@let") { // Angular requires at least one whitespace after `@let`. Any other - // following character (including EOF) produces INCOMPLETE_LET. - let next_char = self - .input - .get(self.index as usize + 4..) - .and_then(|s| s.chars().next()) - .unwrap_or(chars::EOF); - if chars::is_whitespace(next_char) { + // following character (including EOF) produces INCOMPLETE_LET. It is the one the cursor reads after + // `@let`, any of which may be an escape. + if chars::is_whitespace(self.peek_at(4)) { self.scan_let_start(start); } else { // Consume "@let" diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index f7604b8a5..b8953feff 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -1937,6 +1937,26 @@ mod let_declarations { ] ); } + + #[test] + fn should_read_the_character_after_an_escaped_let_through_the_cursor() { + // Angular checks the character its cursor reads after `@let`. Expected values are from Angular 22.3.0. + use HtmlTokenType::*; + let declaration = |start, offset: u32| { + vec![ + token(LetStart, &["x"], start, offset + 9), + token(LetValue, &["y"], offset + 12, offset + 13), + token(LetEnd, &[], offset + 13, offset + 14), + eof(offset + 14), + ] + }; + assert_eq!(lex_escaped(r"\x40let x = y;"), (declaration(0, 0), vec![])); + assert_eq!(lex_escaped(r"@let\x20x = y;"), (declaration(0, 0), vec![])); + // `\\` after a line continuation is read as is: a `\`, then `\@`. + let mut tokens = vec![text("\\", 2, 3)]; + tokens.extend(declaration(3, 1)); + assert_eq!(lex_escaped("\\\n\\\\@let x = y;"), (tokens, vec![])); + } } // ============================================================================ From 6ac9cee4de7ad4e7adf0f24374d58cf9f2079562 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:52:53 +0800 Subject: [PATCH 45/47] fix(parser): read a `{` before a bad escape as text with expansion forms Angular's `isExpansionFormStart` tries `{{`, so its cursor moves onto the escape after the `{` and throws there, as it does in a text. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 17 ++++++++++++++++- .../tests/html_lexer_test.rs | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index cc991bfbd..7fa8ad2e7 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -1056,10 +1056,15 @@ impl<'a> HtmlLexer<'a> { /// decodes the escape at once: `\u{` with no `}` after it, `\u` with fewer than 3 UTF-16 units after it and `\x` /// with none run into the end of the input, and digits `parseInt` reads as NaN are invalid. fn cursor_escape_error(&self) -> Option { + self.escape_error_at(self.index as usize) + } + + /// The error Angular's `EscapedCharacterCursor` throws when it moves onto the escape at byte `pos`, if any (see + /// `cursor_escape_error`). + fn escape_error_at(&self, pos: usize) -> Option { if !self.escaped_string { return None; } - let pos = self.index as usize; // Right after a line continuation, the cursor reads a backslash as is: no escape starts there. if self.reads_raw_at(pos) { return None; @@ -3434,6 +3439,16 @@ impl<'a> HtmlLexer<'a> { if self.peek() != '{' { return false; } + // Angular's `isExpansionFormStart` tries the interpolation start with `_attemptStr`, which moves the cursor + // past the `{`: at a bad escape after it, the cursor throws, as it does when a text moves past a `{` there. + // So outside an expansion form, the `{` is read as text, which ends the same way. + if self.interpolation_start.len() > 1 + && self.interpolation_start.starts_with('{') + && !self.is_in_expansion_form() + && self.escape_error_at(self.next_cursor_pos(self.index as usize)).is_some() + { + return false; + } // Check it's not an interpolation start !self.starts_with(self.interpolation_start) } diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index b8953feff..c5d739039 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2576,6 +2576,22 @@ mod escaped_code_points { let invalid = ("Invalid hexadecimal escape sequence".to_string(), 3); assert_eq!(lex_escaped("\\u{\u{85} 41}"), (vec![text("\\", 0, 9), eof(9)], vec![invalid])); } + + #[test] + fn should_read_a_brace_before_a_bad_escape_as_text_with_expansion_forms() { + // Angular's `isExpansionFormStart` tries `{{`, so its cursor moves onto the escape and throws, as in a text. + // Expected values are from Angular 22.3.0. + let invalid = |offset| ("Invalid hexadecimal escape sequence".to_string(), offset); + assert_eq!(lex_icu(r"{\xz"), (vec![eof(4)], vec![invalid(3), eof_error(4)])); + assert_eq!( + lex_icu(r"\xzz{\xz"), + (vec![eof(8)], vec![invalid(2), invalid(7), eof_error(8)]) + ); + assert_eq!( + lex_icu(r" Date: Fri, 4 Dec 2026 22:53:01 +0800 Subject: [PATCH 46/47] fix(parser): end the text of a bad entity at an interpolation after it Angular starts an empty text after the entity error, which ends at the `{{` and is merged into the text before the entity. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 14 +++----- .../tests/html_lexer_test.rs | 34 +++++++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 7fa8ad2e7..331991a03 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -1310,17 +1310,13 @@ impl<'a> HtmlLexer<'a> { // Check for interpolation if self.starts_with(self.interpolation_start) { - // Emit empty Text token before interpolation if the previous token is NOT Text + // Emit empty Text token before interpolation, as Angular's `_consumeWithInterpolation` starts one // This ensures interpolations are always surrounded by Text tokens for proper parsing // (Angular's lexer behavior - empty tokens get filtered at parser level) - let needs_text_before = match self.tokens.last() { - Some(t) => { - t.token_type != HtmlTokenType::Text - && t.token_type != HtmlTokenType::RawText - && t.token_type != HtmlTokenType::EscapableRawText - } - None => true, - }; + // After a text it is merged into it, which then ends here: past a bad entity that ended the text. + let needs_text_before = !self.tokens.last().is_some_and(|t| { + matches!(t.token_type, HtmlTokenType::RawText | HtmlTokenType::EscapableRawText) + }); if needs_text_before { self.tokens.push(HtmlToken::with_part(HtmlTokenType::Text, "", start, start)); } diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index c5d739039..183c7ed6c 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -3786,6 +3786,40 @@ mod entities_extended { ] ); } + + #[test] + fn should_end_the_text_of_a_bad_entity_at_an_interpolation_after_it() { + // Angular starts a text after the entity error, which ends at once at the `{{` and is merged into the text + // before the entity. Expected values are from Angular 22.3.0. + use HtmlTokenType::*; + let hex_error = |entity: &str, offset| { + ( + format!( + "Unable to parse entity \"{entity}\" - hexadecimal character reference entities must end with \";\"" + ), + offset, + ) + }; + let after = |text_token, offset: u32| { + vec![ + text_token, + token(Interpolation, &["{{", "c", "}}"], offset, offset + 5), + text("", offset + 5, offset + 5), + eof(offset + 5), + ] + }; + assert_eq!(lex("&#x {{c}}", false), (after(text("", 0, 4), 4), vec![hex_error("&#x ", 4)])); + assert_eq!( + lex("a&#x {{c}}", false), + (after(text("a", 0, 5), 5), vec![hex_error("&#x ", 5)]) + ); + let unknown = ( + "Unknown entity \"&#x;\" - use the \"&#;\" or \"&#x;\" syntax" + .to_string(), + 4, + ); + assert_eq!(lex_escaped("&#x;{{c}}"), (after(text("", 0, 4), 4), vec![unknown])); + } } // ============================================================================ From 4cfec8ef909e6210c1a89c3034108cde3d0514f7 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Fri, 4 Dec 2026 22:53:09 +0800 Subject: [PATCH 47/47] fix(parser): move one UTF-16 unit past a bad numeric entity Angular's cursor moves past the CR of a CRLF only. In a character outside the BMP it moves into it; no str starts at its second half, so the lexer keeps the whole character there and reads the first half as U+FFFD in the message. Co-Authored-By: Claude Opus 5.5 --- .../src/parser/html/lexer.rs | 16 ++++++++++-- .../tests/html_lexer_test.rs | 26 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index 331991a03..284300c92 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -3852,8 +3852,20 @@ impl<'a> HtmlLexer<'a> { ); self.entity_error = Some(EntityError::Eof(self.index, self.line, self.column)); } else { - advance!(); - let entity_str = self.cursor_text(start, self.index); + // Angular's cursor moves one UTF-16 unit here. That is the CR of a CRLF, which `advance` would move + // past with its LF. In a character outside the BMP, it is the first half, which Angular's message + // holds (it reads as U+FFFD): the lexer goes on at the whole character, as no `str` starts at its + // second half. + let raw = self.raw_peek(); + let mut split_char = ""; + if raw.len_utf16() == 2 { + split_char = "\u{fffd}"; + } else if raw == '\r' && self.input[self.index as usize..].starts_with("\r\n") { + self.move_raw_to(self.index + 1); + } else { + advance!(); + } + let entity_str = self.cursor_text(start, self.index) + split_char; let entity_type = if is_hex { "hexadecimal" } else { "decimal" }; self.push_error(format!( "Unable to parse entity \"{entity_str}\" - {entity_type} character reference entities must end with \";\"" diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index 183c7ed6c..b6dbcca9d 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -3820,6 +3820,32 @@ mod entities_extended { ); assert_eq!(lex_escaped("&#x;{{c}}"), (after(text("", 0, 4), 4), vec![unknown])); } + + #[test] + fn should_move_one_utf16_unit_past_a_bad_numeric_entity() { + // Angular's cursor moves past one UTF-16 unit there: the CR of a CRLF. Expected values are from Angular 22.3.0. + let error = |entity: &str, kind: &str, offset| { + ( + format!( + "Unable to parse entity \"{entity}\" - {kind} character reference entities must end with \";\"" + ), + offset, + ) + }; + for escaped in [false, true] { + assert_eq!( + lex("a&#x\r\nb", escaped), + (vec![text("a\nb", 0, 7), eof(7)], vec![error("&#x\r", "hexadecimal", 5)]) + ); + } + // Angular splits a character outside the BMP: its text holds the second half, its message the first, at + // UTF-16 offset 3. No `str` holds half a character: the text keeps the whole one and the message reads the + // first half as U+FFFD, at the character's start. The span of the text is Angular's. + assert_eq!( + lex("&#šŸ˜€", false), + (vec![text("šŸ˜€", 0, 6), eof(6)], vec![error("&#\u{fffd}", "decimal", 2)]) + ); + } } // ============================================================================