diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index e01260611..284300c92 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -36,6 +36,97 @@ enum EntityError { At(u32, u32, u32), /// The input ended inside the entity, a `CursorError`. Eof(u32, u32, u32), + /// The cursor moved onto a bad escape inside the entity, which it throws for (see `recover_at_bad_escape`). + BadEscape(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 }, +} + +/// The error Angular reports when its cursor moves past the end of the input. +const EOF_ERROR: &str = "Unexpected character \"EOF\""; + +/// What Angular's `_createError` adds to an error between the cases of an expansion form. +pub const ICU_HINT: &str = + " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)"; + +/// How far Angular's `EscapedCharacterCursor` gets through a code-point escape. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum EscapeEnd { + /// The cursor can move past the escape. + Complete, + /// The text ends on the escape's last digit: the cursor reads it, but cannot move past it. + CutShort, + /// The cursor runs into the end of the text before it reads the digits, and throws EOF. + Eof, +} + +/// 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 the escape ends in `Eof`. + value: Option, + /// How far the cursor gets through it. + end: EscapeEnd, +} + +/// 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 cut short. 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, end: EscapeEnd| { + Some(CodePointEscape { digits, len, value: value.filter(|_| end != EscapeEnd::Eof), end }) + }; + if let Some(braced) = rest.strip_prefix("u{") { + return match braced.find('}') { + Some(end) => { + escape(3, 4 + end, parse_int_prefix(&braced[..end], 16), EscapeEnd::Complete) + } + None => escape(3, text.len(), None, EscapeEnd::Eof), + }; + } + 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); + let escape_end = if units >= width { + EscapeEnd::Complete + } else if units + 1 == width { + EscapeEnd::CutShort + } else { + EscapeEnd::Eof + }; + return escape(2, 2 + end, value, escape_end); + } + 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), EscapeEnd::Complete))? } /// Token types for HTML templates. @@ -255,26 +346,24 @@ 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` -/// 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), - } +/// 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.strip_prefix('+').unwrap_or(digits); + 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) } else { @@ -285,227 +374,88 @@ 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) { - let mut result = String::with_capacity(text.len()); +/// 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. +/// 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, + len: usize, + first_raw: bool, +) -> (String, Vec<(String, usize)>) { + let mut result = String::with_capacity(len); let mut errors = Vec::new(); - let chars: Vec = text.chars().collect(); let mut i = 0; - let mut encountered_null = false; - - 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 - encountered_null = true; - break; - } - } - 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; - } else { - // Just \0 - null character, treat as EOF - encountered_null = true; - break; - } - } - '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 - encountered_null = true; - break; - } - } - 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 - encountered_null = true; - break; - } - } - 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 - encountered_null = true; - break; - } - 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 - encountered_null = true; - break; - } - 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' => { - // Line continuation - skip both backslash and newline - i += 2; + if first_raw && let Some(ch) = text[..len].chars().next() { + result.push(ch); + i = ch.len_utf8(); + } + 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); + i += ch.len_utf8(); + continue; + }; + if let Some(escape) = code_point_escape(&text[i..]) { + if escape.value == Some(0) { + result.push('\0'); + i += escape.len; + continue; + } + match escape.value { + Some(value) if escape.end == EscapeEnd::Complete => { + result.extend(char::from_u32(value)); } - '\r' => { - // Line continuation with CR or CRLF - i += 2; - if i < chars.len() && chars[i] == '\n' { - i += 1; + // Invalid digits: Angular reads the escape as a `\` of text + None if escape.end != EscapeEnd::Eof => { + errors.push(( + "Invalid hexadecimal escape sequence".to_string(), + i + escape.digits, + )); + // Digits that end the input: the cursor then fails to move past them. + if escape.end == EscapeEnd::CutShort { + 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 + // reads nothing more. _ => { - // Unknown escape - just use the character after backslash - result.push(next); - i += 2; + errors.push((EOF_ERROR.to_string(), text.len())); + return (result, errors); } } - } else { - result.push(chars[i]); - i += 1; + i += escape.len; + continue; + } + i += 1 + next.len_utf8(); + match next { + 'n' => result.push('\n'), + 'r' => result.push('\r'), + '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.get(i..len).and_then(|rest| rest.chars().next()) { + result.push(ch); + i += ch.len_utf8(); + } + } + // Any other escaped character, quotes and backslashes too, is itself + _ => result.push(next), } } - (result, errors, encountered_null) + (result, errors) } /// Merges adjacent text tokens and adjacent attribute value text tokens. @@ -614,6 +564,11 @@ 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, + /// 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. @@ -646,6 +601,8 @@ impl<'a> HtmlLexer<'a> { leading_trivia_chars: None, range_start_pos: 0, range_end_pos: length, + continuation_ends: Vec::new(), + recovered_texts: Vec::new(), range_line_offset: 0, range_col_offset: 0, } @@ -750,74 +707,167 @@ impl<'a> HtmlLexer<'a> { /// Tokenizes the input. pub fn tokenize(mut self) -> HtmlTokenizeResult { - // Like Angular's loop, stop at a NUL: its cursor peeks one as `$EOF`. + 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.scan_token(); } 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 = std::mem::take(&mut self.tokens); // Process escape sequences if enabled 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; - - for (token_idx, token) in tokens.iter_mut().enumerate() { - if null_encountered { - break; + // The errors the lexer already reported, without the expansion form hint: the escape pass finds some of + // them again. + let reported: std::collections::HashSet<(u32, &str)> = self + .errors + .iter() + .map(|e| (e.offset, e.msg.strip_suffix(ICU_HINT).unwrap_or(&e.msg))) + .collect(); + 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 + // 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_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 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 ` 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 in &mut token.parts { - let (processed, errs, has_null) = process_escape_sequences(part); - *part = processed; + 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 < 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 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, with JavaScript's `trim`. + js_trim(&processed).to_string() + } 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; 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 { + u32::try_from(part_start + offset).unwrap_or(token.end) + }; + if !reported.contains(&(offset, msg.as_str())) { + errors_to_add.push((msg, offset)); + } } - if has_null { - null_encountered = true; - null_token_idx = Some(token_idx); - break; + if cut_short { + cut_short_token = Some((token_idx, token.end)); + break 'tokens; } } } - // 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)); + 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(); let positions = offsets_to_positions(self.input, &offsets); 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 } + // 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). @@ -831,16 +881,123 @@ 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; - } - // 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 + 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') + } + + /// Normalizes the line endings of token text, but only outside an escaped string: there, the escape pass does it + /// once the escapes are decoded, as Angular's `_processCarriageReturns` runs on the characters its cursor reads. + fn normalize_plain_line_endings(&self, text: &str) -> String { + 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 + } + + /// The characters the cursor reads from byte `start` to `end`, as Angular's `getChars`. A bad escape or one cut + /// short reads as U+FFFD: the entity scan, its only user, stops before either. + 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() + } + + /// 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); + } + } + + /// 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; + } } } @@ -863,57 +1020,125 @@ 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, 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).filter(|&ch| ch != '\0'); + let ch = value.and_then(char::from_u32); 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, 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`. 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(|&v| escape.end == EscapeEnd::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. - /// `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() == '\\' { - 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 + /// 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; } + // 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 escape = code_point_escape(self.input.get(pos..)?)?; + if escape.end == EscapeEnd::Eof { + return Some(EscapeError::Eof); + } + if escape.value.is_some() { + return None; + } + let at = |offset: usize| u32::try_from(pos + offset).ok(); + Some(EscapeError::InvalidHex { + digits: at(escape.digits)?, + end: if escape.end == EscapeEnd::Complete { at(escape.len) } else { None }, + }) + } + + /// 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.end != EscapeEnd::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; + 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 `\` (the cursor still + /// peeks the backslash, then moves on from the escape's end): as text, or between the cases of an expansion form + /// as the start of a case value, which the cursor then reads from the backslash. Otherwise, the input ends. + fn recover_at_bad_escape(&mut self) -> bool { + let Some(error) = self.cursor_escape_error() else { return false }; + let start = self.index; + if let EscapeError::InvalidHex { digits, end } = error { + let (line, column) = (self.line, self.column); + self.move_raw_to(digits); + self.error("Invalid hexadecimal escape sequence"); + if end.is_some() && self.tokenize_icu && self.is_in_expansion_form() { + // The escape pass decodes the case value, reading the escape as a `\` again. + self.index = start; + self.line = line; + self.column = column; + return true; + } + 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)); + self.recovered_texts.push(start); + return true; + } + } + self.move_raw_to(self.length); + self.error("Unexpected character \"EOF\""); + true } /// Peeks at a character at offset from current position. @@ -924,145 +1149,68 @@ 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) } } - /// Advances the index and returns the current character. + /// Advances the index and returns the current character, then skips a line continuation the cursor lands on. fn advance(&mut self) -> char { if self.index >= self.length { return chars::EOF; } let raw_ch = self.raw_peek(); + let pos = self.index as usize; - // Handle escape sequences when escaped_string is true - if self.escaped_string && raw_ch == '\\' { - let next_pos = self.index as usize + 1; - if next_pos >= self.length as usize { + // Handle escape sequences when escaped_string is true (not right after a line continuation) + let ch = if self.escaped_string && raw_ch == '\\' && !self.reads_raw_at(pos) { + if pos + 1 >= self.length as usize { // Backslash at end of input - just advance past it self.index += 1; self.column += 1; - return '\\'; - } - - 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; - self.column += len as u32; - return ch; + '\\' + } else if let Some((ch, len)) = self.code_point_escape_at(pos) { + // A code-point escape is one character, as in Angular's cursor + let len = u32::try_from(len).unwrap_or(self.length); + self.index += len; + self.column += len; + ch + } else { + // Otherwise skip the backslash and the escaped character + let next = self.input[pos + 1..].chars().next().unwrap_or(chars::EOF); + self.index = u32::try_from(pos + 1 + next.len_utf8()).unwrap_or(self.length); + self.column += 2; + Self::unescape_char(next) } - - // Otherwise skip the backslash and the escaped character - let unescaped = Self::unescape_char(next); - - // Skip backslash + } else if raw_ch == '\n' { self.index += 1; - self.column += 1; - - // Skip escaped character - self.index += next.len_utf8() as u32; - self.column += 1; - - return unescaped; - } - - // Normal character handling - if raw_ch == '\n' { self.line += 1; self.column = 0; + raw_ch } else if raw_ch == '\r' { - // CR can be standalone or part of CRLF - let next_pos = self.index as usize + 1; - let next = if next_pos < self.length as usize { - self.input[next_pos..].chars().next() - } else { - None - }; - if next == Some('\n') { - // CRLF - consume both, count as single newline - self.index += 2; - self.line += 1; - self.column = 0; - return '\n'; - } else { - // Standalone CR - treat as newline - self.index += 1; - self.line += 1; - self.column = 0; - return '\r'; - } + // CR can be standalone or part of CRLF; either is one newline + let crlf = + self.input.get(pos + 1..self.length as usize).is_some_and(|s| s.starts_with('\n')); + self.index += if crlf { 2 } else { 1 }; + self.line += 1; + self.column = 0; + if crlf { '\n' } else { '\r' } } else { + self.index = u32::try_from(pos + raw_ch.len_utf8()).unwrap_or(self.length); self.column += 1; - } - // Advance by the byte length of the current character - self.index += raw_ch.len_utf8() as u32; - raw_ch + raw_ch + }; + self.skip_line_continuation(); + ch } /// Checks if the input starts with the given string at current position. @@ -1074,7 +1222,8 @@ 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 { "Unexpected character \"EOF\"".to_string() @@ -1092,9 +1241,7 @@ impl<'a> HtmlLexer<'a> { /// form (between its cases) tells how to escape a `{`. fn push_error(&mut self, mut msg: String, position: (u32, u32), offset: u32, end: u32) { if self.is_in_expansion_form() { - msg.push_str( - " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)", - ); + msg.push_str(ICU_HINT); } self.errors.push(HtmlTokenError { msg, position, offset, end }); } @@ -1135,13 +1282,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" @@ -1167,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)); } @@ -1616,6 +1755,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()) { @@ -1660,7 +1815,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_plain_line_endings(expr); let parts = vec![self.interpolation_start.to_string(), normalized_expr]; self.tokens.push(HtmlToken::new( HtmlTokenType::Interpolation, @@ -1731,7 +1886,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_plain_line_endings(expr); let parts = if has_end { vec![ self.interpolation_start.to_string(), @@ -1788,19 +1943,11 @@ impl<'a> HtmlLexer<'a> { if self.peek() == '-' { // ` 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_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -1987,7 +2134,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_plain_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2024,7 +2171,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_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2034,7 +2181,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_plain_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2052,7 +2199,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_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2204,7 +2351,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_plain_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2229,7 +2376,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_plain_line_endings(content); self.tokens.push(HtmlToken::with_part( token_type, &normalized, @@ -2328,12 +2475,22 @@ impl<'a> HtmlLexer<'a> { return; } - // Scan tag name - let (prefix, name) = self.scan_tag_name(); + // 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| !Self::is_name_end(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`. @@ -2342,6 +2499,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, @@ -2352,7 +2513,38 @@ impl<'a> HtmlLexer<'a> { )); } - /// Scans a tag name (with optional namespace prefix). + /// 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 { + 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 !ch.is_ascii_alphanumeric() { + break; + } + pos = self.next_cursor_pos(pos); + } + ("", &self.input[start..end]) + } + + /// 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(); @@ -2366,16 +2558,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 off the namespace prefix + let (prefix, name) = self.split_prefix(name_start, self.index); + (prefix.to_string(), name.to_string()) } /// Scans a selectorless directive: @DirectiveName or @DirectiveName(attrs) @@ -2484,7 +2669,7 @@ impl<'a> HtmlLexer<'a> { break; } - let (prefix, name) = split_attr_ns_prefix(attr_name); + let (prefix, name) = self.split_prefix(attr_start, self.index); self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::AttrName, @@ -2630,7 +2815,7 @@ impl<'a> HtmlLexer<'a> { } } - let (prefix, name) = split_attr_ns_prefix(attr_full_name); + let (prefix, name) = self.split_prefix(attr_start, self.index); self.tokens.push(HtmlToken::with_prefix_name( HtmlTokenType::AttrName, @@ -2791,7 +2976,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, @@ -2805,17 +2992,19 @@ impl<'a> HtmlLexer<'a> { /// After a `scan_entity` in an attribute value: when the entity had an error, /// Angular's `_consumeTagOpen` catches it, marks the tag incomplete and goes on - /// after the entity. EOF is not caught there: the tag is left as it is. The - /// text before the entity is kept. Returns whether the tag was stopped. + /// after the entity. A `CursorError` (EOF, a bad escape) is not caught there: the + /// tag is left as it is, and lexing goes on as text from a bad escape. The text + /// before the entity is kept. Returns whether the tag was stopped. fn abort_tag_on_entity_error(&mut self, text_start: u32, entity_start: u32) -> bool { - let (index, line, column, mark_incomplete) = match self.entity_error.take() { - None => return false, - Some(EntityError::At(index, line, column)) => (index, line, column, true), - Some(EntityError::Eof(index, line, column)) => (index, line, column, false), - }; - if entity_start > text_start { + let Some(error) = self.entity_error.take() else { return false }; + let (EntityError::At(index, line, column) + | EntityError::Eof(index, line, column) + | EntityError::BadEscape(index, line, column)) = error; + let bad_escape = matches!(error, EntityError::BadEscape(..)); + // At a bad escape, Angular has ended the text token before the entity, an empty one too. + if entity_start > text_start || bad_escape { let text = &self.input[text_start as usize..entity_start as usize]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, &normalized, @@ -2826,7 +3015,9 @@ impl<'a> HtmlLexer<'a> { self.index = index; self.line = line; self.column = column; - if mark_incomplete { + if bad_escape { + self.recover_at_bad_escape(); + } else if matches!(error, EntityError::At(..)) { for token in self.tokens.iter_mut().rev() { if token.token_type == HtmlTokenType::TagOpenStart { token.token_type = HtmlTokenType::IncompleteTagOpen; @@ -2857,13 +3048,16 @@ 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 { 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_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, &normalized, @@ -2942,6 +3136,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, "", @@ -2954,7 +3149,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_plain_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() { @@ -2967,6 +3162,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, "", @@ -2979,16 +3175,58 @@ 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(); } } + 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 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[kept_end as usize..self.index as usize]; + let first_raw = self.reads_raw_at(kept_end as usize); + let errors: Vec<(String, u32)> = + process_escape_sequences(text, text.len(), first_raw) + .1 + .into_iter() + .filter(|(msg, _)| msg != EOF_ERROR) + .filter_map(|(msg, offset)| { + Some((msg, kept_end + u32::try_from(offset).ok()?)) + }) + .collect(); + let offsets: Vec = errors.iter().map(|&(_, offset)| offset).collect(); + let positions = offsets_to_positions(self.input, &offsets); + for ((msg, offset), position) in errors.into_iter().zip(positions) { + self.push_error(msg, position, offset, offset); + } + } + if kept_end > text_start { + let text = &self.input[text_start as usize..kept_end as usize]; + let normalized = self.normalize_plain_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 + }) { + 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]; - let normalized = normalize_line_endings(text); + let normalized = self.normalize_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::AttrValueText, &normalized, @@ -3009,11 +3247,15 @@ 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]; - let normalized_content = normalize_line_endings(content); + let normalized_content = self.normalize_plain_line_endings(content); // Emit content as RAW_TEXT self.tokens.push(HtmlToken::with_part( @@ -3061,13 +3303,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(); @@ -3082,14 +3340,27 @@ 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(); + 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, @@ -3114,7 +3385,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_plain_line_endings(content); // Emit content as RAW_TEXT self.tokens.push(HtmlToken::with_part( @@ -3164,6 +3435,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) } @@ -3249,7 +3530,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\""); @@ -3282,6 +3563,10 @@ impl<'a> HtmlLexer<'a> { fn scan_expansion_case_end(&mut self) { let start = self.index; self.advance(); // consume '}' + // Angular's cursor throws when it moves past the `}` onto a bad escape: the case is not ended. + if self.recover_at_bad_escape() { + return; + } self.tokens.push(HtmlToken::empty(HtmlTokenType::ExpansionCaseExpEnd, start, self.index)); self.skip_whitespace(); @@ -3292,6 +3577,10 @@ impl<'a> HtmlLexer<'a> { fn scan_expansion_form_end(&mut self) { let start = self.index; self.advance(); // consume '}' + // Angular's cursor throws when it moves past the `}` onto a bad escape: the form is not ended. + if self.recover_at_bad_escape() { + return; + } self.tokens.push(HtmlToken::empty(HtmlTokenType::ExpansionFormEnd, start, self.index)); self.expansion_case_stack.pop(); @@ -3396,7 +3685,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_plain_line_endings(text); self.tokens.push(HtmlToken::with_part( HtmlTokenType::Text, &normalized, @@ -3421,6 +3710,21 @@ 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) + | EntityError::BadEscape(index, line, column)) = error; + self.index = index; + self.line = line; + self.column = column; + if matches!(error, EntityError::BadEscape(..)) { + self.recover_at_bad_escape(); + } + return; + } // If entity parsing failed, scan_entity reverted the index // so just advance past the & and treat it as regular text } @@ -3430,21 +3734,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 = 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_plain_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). @@ -3453,13 +3761,27 @@ impl<'a> HtmlLexer<'a> { let start = self.index; let start_line = self.line; let start_col = self.column; - self.advance(); // consume '&' + // Moves past a character, but stops at a bad escape: Angular's cursor throws out of `_consumeEntity` there. + macro_rules! advance { + () => { + match self.advance_in_entity() { + Some(ch) => ch, + None => { + self.index = start; + self.line = start_line; + self.column = start_col; + return false; + } + } + }; + } + advance!(); // consume '&' if self.peek() == '#' { // Numeric entity: { or { - self.advance(); // consume '#' + advance!(); // consume '#' let is_hex = self.peek() == 'x' || self.peek() == 'X'; - let hex_marker = if is_hex { Some(self.advance()) } else { None }; // consume 'x' or 'X' + let hex_marker = if is_hex { Some(advance!()) } else { None }; // consume 'x' or 'X' // Consume digits (the characters the cursor reads, so escaped ones count) let mut num_str = String::new(); @@ -3472,12 +3794,12 @@ impl<'a> HtmlLexer<'a> { } else if !ch.is_ascii_digit() { break; } - num_str.push(self.advance()); + num_str.push(advance!()); } if self.peek() == ';' { let num_str = num_str.as_str(); - self.advance(); // consume ';' + advance!(); // consume ';' // Parse and decode let code_point = @@ -3486,7 +3808,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" ); @@ -3519,8 +3841,9 @@ impl<'a> HtmlLexer<'a> { // Numeric entity doesn't end with semicolon - this is an error // Advance cursor to include the peeked character in the error message // (unless we're at the end; a NUL is read like Angular's cursor does) - if self.index >= self.length { - // EOF - report "Unexpected character EOF" + if self.index >= self.length || self.at_escape_cut_short() { + // EOF, or an escape the cursor cannot move past - report "Unexpected character EOF" at the end + self.move_raw_to(self.length); self.push_error( "Unexpected character \"EOF\"".to_string(), (self.line, self.column), @@ -3529,8 +3852,20 @@ 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]; + // 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 \";\"" @@ -3551,12 +3886,12 @@ impl<'a> HtmlLexer<'a> { if !ch.is_ascii_alphanumeric() { break; } - name.push(self.advance()); + name.push(advance!()); } // Check for semicolon (an empty name is an unknown entity, as in Angular) if self.peek() == ';' { - self.advance(); // consume ';' + advance!(); // consume ';' if get_named_entities().contains_key(name.as_str()) { // As Angular's `getChars`, both parts hold the characters the cursor read @@ -3595,6 +3930,17 @@ impl<'a> HtmlLexer<'a> { self.column = start_col; false } + + /// Moves past the cursor character inside an entity. When it lands on a bad escape, Angular's cursor throws out of + /// `_consumeEntity`: records where in `entity_error` and returns none. + fn advance_in_entity(&mut self) -> Option { + let ch = self.advance(); + if self.cursor_escape_error().is_some() { + self.entity_error = Some(EntityError::BadEscape(self.index, self.line, self.column)); + return None; + } + Some(ch) + } } #[cfg(test)] @@ -3682,15 +4028,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(); @@ -3749,11 +4096,10 @@ 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), + // 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 bf99bc835..b6dbcca9d 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -2,7 +2,7 @@ //! //! Ported from Angular's `test/ml_parser/lexer_spec.ts`. -use oxc_angular_compiler::parser::html::{HtmlLexer, HtmlTokenType, HtmlTokenizeResult}; +use oxc_angular_compiler::parser::html::{HtmlLexer, HtmlTokenType, HtmlTokenizeResult, ICU_HINT}; // ============================================================================ // Helper Functions @@ -41,6 +41,50 @@ fn tokenize_selectorless_and_humanize_parts(input: &str) -> Vec<(HtmlTokenType, result.tokens.into_iter().map(|t| (t.token_type, t.parts)).collect() } +/// A token type with its parts and span. +type Token = (HtmlTokenType, Vec, u32, u32); +/// Tokens with their spans, and errors with their offsets. +type Lexed = (Vec, Vec<(String, u32)>); + +/// Tokens with their spans, and errors with their offsets. +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()) +} + +/// Tokens with their spans, and errors with their offsets, of an escaped string. +fn lex_escaped(input: &str) -> Lexed { + lex(input, true) +} + +/// Tokens with their spans, and errors with their offsets, of an escaped string with expansion forms. +fn lex_icu(input: &str) -> Lexed { + let result = + HtmlLexer::new(input).with_escaped_string(true).with_expansion_forms(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()) +} + +/// A token of `token_type` with `parts` from byte `start` to `end`. +fn token(token_type: HtmlTokenType, parts: &[&str], start: u32, end: u32) -> Token { + (token_type, parts.iter().map(ToString::to_string).collect(), start, end) +} + +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) +} + // ============================================================================ // Basic Tag Tests // ============================================================================ @@ -227,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![]) + ); + } } // ============================================================================ @@ -531,6 +613,108 @@ mod attributes { let result = tokenize(r#"); - type Lexed = (Vec<(Part, u32, u32)>, Vec<(String, u32)>); - - fn pi(content: &str) -> Part { - (HtmlTokenType::ProcessingInstruction, vec![content.to_string()]) - } - - fn text(value: &str) -> Part { - (HtmlTokenType::Text, vec![value.to_string()]) - } - - fn eof() -> Part { - (HtmlTokenType::Eof, vec![]) - } - - fn eof_error(offset: u32) -> (String, u32) { - ("Unexpected character \"EOF\"".to_string(), offset) - } - - /// Tokens with their spans, and errors with their offsets. - 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()) + fn pi(content: &str, start: u32, end: u32) -> Token { + token(HtmlTokenType::ProcessingInstruction, &[content], start, end) } fn errors(input: &str) -> Vec<(String, u32)> { @@ -1796,31 +1977,30 @@ mod processing_instructions { #[test] fn should_parse_a_processing_instruction() { // TS: it("should parse a processing instruction", ...) - let result = tokenize_and_humanize_parts(r#""#); - assert_eq!(result, vec![pi(r#"xml version="1.0" encoding="UTF-8""#), eof()]); + let result = lex(r#""#, false).0; + assert_eq!(result, vec![pi(r#"xml version="1.0" encoding="UTF-8""#, 0, 38), eof(38)]); } #[test] fn should_parse_a_processing_instruction_ending_with_gt() { // TS: it("should parse a processing instruction ending with > instead of ?>", ...) - let result = tokenize_and_humanize_parts(r#""#); - assert_eq!(result, vec![pi(r#"xml version="1.0" encoding="UTF-8""#), eof()]); + let result = lex(r#""#, false).0; + assert_eq!(result, vec![pi(r#"xml version="1.0" encoding="UTF-8""#, 0, 37), eof(37)]); } #[test] fn should_parse_a_processing_instruction_surrounded_by_other_content() { // TS: it("should parse a processing instruction surrounded by other content", ...) - let result = tokenize_and_humanize_parts( - "\n hello", - ); + let result = + lex("\n hello", false).0; assert_eq!( result, vec![ - (HtmlTokenType::DocType, vec!["DOCTYPE html".to_string()]), - text("\n"), - pi(r#"xml version="1.0" encoding="UTF-8""#), - text(" hello"), - eof(), + token(HtmlTokenType::DocType, &["DOCTYPE html"], 0, 15), + text("\n", 15, 16), + pi(r#"xml version="1.0" encoding="UTF-8""#, 16, 54), + text(" hello", 54, 60), + eof(60), ] ); } @@ -1828,8 +2008,8 @@ mod processing_instructions { #[test] fn should_parse_a_processing_instruction_that_contains_question_marks_inside_quoted_content() { // TS: it("should parse a processing instruction that contains question marks inside quoted content", ...) - let result = tokenize_and_humanize_parts(r#"-8"?>"#); - assert_eq!(result, vec![pi(r#"xml version="?" encoding="UTF?>-8""#), eof()]); + let result = lex(r#"-8"?>"#, false).0; + assert_eq!(result, vec![pi(r#"xml version="?" encoding="UTF?>-8""#, 0, 38), eof(38)]); } #[test] @@ -1855,23 +2035,23 @@ mod processing_instructions { #[test] fn should_ignore_end_chars_inside_all_quote_kinds() { - let result = tokenize_and_humanize_parts(r#"' `b>` "c\"?>"?>d"#); - assert_eq!(result, vec![pi(r#"pi 'a?>' `b>` "c\"?>""#), text("d"), eof()]); + let result = lex(r#"' `b>` "c\"?>"?>d"#, false).0; + assert_eq!(result, vec![pi(r#"pi 'a?>' `b>` "c\"?>""#, 0, 25), text("d", 25, 26), eof(26)]); } #[test] fn should_report_an_unterminated_processing_instruction() { assert_eq!(errors(""), [eof_error(9)]); assert_eq!(errors("y"), [("Unexpected character \"x\"".to_string(), 6)]); } #[test] fn should_end_text_and_interpolations_at_a_processing_instruction() { assert_eq!( - tokenize_and_humanize_parts("ab"), - vec![text("a"), pi("pi"), text("b"), eof()] + lex("ab", false).0, + vec![text("a", 0, 1), pi("pi", 1, 7), text("b", 7, 8), eof(8)] ); assert_eq!(errors("{{ a z"), pi_end, 8), (eof(), 8, 8)], vec![]); + let ended = |pi_end| (vec![pi("x", 0, pi_end), text("y?>z", pi_end, 8), eof(8)], vec![]); assert_eq!(lex("z", false), ended(4)); assert_eq!(lex("z", true), ended(4)); // NUL at the end of the input: the instruction ends there, with no error. - assert_eq!(lex("z", false).0, - [(pi("\"\0\""), 0, 7), (text("z"), 7, 8), (eof(), 8, 8)] - ); + assert_eq!(lex("z", false).0, [pi("\"\0\"", 0, 7), text("z", 7, 8), eof(8)]); } #[test] @@ -1898,14 +2074,626 @@ mod processing_instructions { for (nul, end) in [(r"\0", 5), (r"\000", 7), (r"\x00", 7), (r"\u0000", 9), (r"\u{0}", 8)] { let input = format!("z"); let len = end + 4; - let tokens = vec![(pi("x"), 0, end), (text("y?>z"), end, len), (eof(), len, len)]; + let tokens = vec![pi("x", 0, end), text("y?>z", end, len), eof(len)]; assert_eq!(lex(&input, true), (tokens, vec![]), "{input}"); } // A backslash before a raw NUL. - assert_eq!(lex("z", true).0[..2], [(pi("x"), 0, 5), (text("y?>z"), 5, 9)]); + assert_eq!(lex("z", true).0[..2], [pi("x", 0, 5), text("y?>z", 5, 9)]); // A backslash that ends the input is no NUL: the instruction is unterminated. - assert_eq!(lex(r"z", pi_end, len), eof(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)], 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)], vec![]) + ); + assert_eq!(lex("z", true), (vec![pi("", 0, 6), text("z", 6, 7), eof(7)], vec![])); + assert_eq!( + lex("z", true), + (vec![pi("\n", 0, 7), text("z", 7, 8), eof(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)], vec![])); + assert_eq!(lex("\\\n", true), (vec![pi("", 0, 5), eof(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)]; + 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)], vec![]) + ); + assert_eq!(lex(r#"z"#, true).0[0], pi("\"a\u{0}8\"", 0, 10)); + assert_eq!( + lex(r#"c"#, true), + ( + vec![ + pi("\"a\0b\"", 0, 10), + text("c", 10, 11), + token(HtmlTokenType::TagOpenStart, &["", "i"], 11, 13), + token(HtmlTokenType::TagOpenEnd, &[], 13, 14), + token(HtmlTokenType::TagClose, &["", "i"], 14, 18), + eof(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)], 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)], 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), + token(HtmlTokenType::TagOpenStart, &["", "b"], 11, 13), + token(HtmlTokenType::TagOpenEnd, &[], 13, 14), + eof(14), + ], + vec![invalid(7)] + ) + ); + assert_eq!( + lex(r"\u{zz}{{a}}", true), + ( + vec![ + text("\\", 4, 10), + token(HtmlTokenType::Interpolation, &["{{", "a", "}}"], 10, 15), + text("", 15, 15), + eof(15), + ], + vec![invalid(7)] + ) + ); + // Moving past the `?` of `?>` too. + assert_eq!(lex(r"", true), (vec![text("\\>", 4, 9), eof(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)], vec![invalid(7), eof_error(10)])); + // A good escape keeps the instruction. + assert_eq!( + lex(r"\u{41}", true), + (vec![pi("x", 0, 5), text("A", 5, 11), eof(11)], 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)], vec![invalid(7)])); + assert_eq!(lex("\\x😀a", true), (vec![text("\\a", 5, 12), eof(12)], vec![invalid(7)])); + assert_eq!(lex("\\ué😀a", true), (vec![text("\\", 5, 14), eof(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. + assert_eq!(lex("\\\n\\xZZ", true).0, [pi("x", 0, 7), text("\\xZZ", 7, 11), eof(11)]); + assert_eq!(lex("\\\n\\u{", true).0, [pi("x", 0, 6), text("\\u{", 6, 9), eof(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. + for nul in [r"\0", r"\x00", r"\u0000", r"\u{0}"] { + let input = format!("z"); + assert_eq!(lex(&input, true), (vec![eof(4)], vec![eof_error(4)]), "{input}"); + } + assert_eq!(lex("z", false), (vec![eof(4)], vec![eof_error(4)])); + assert_eq!(lex(r""), (vec![text("a", 0, 3), eof(3)], vec![])); + // A backslash after it is a character, which starts no line continuation. + assert_eq!(lex_escaped("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_escaped("\\\n\\x41"), (vec![text("\\x41", 2, 6), eof(6)], vec![])); + let block_close = (HtmlTokenType::BlockClose, vec![], 6, 7); + assert_eq!( + lex_escaped("\\\n\\u{0}"), + (vec![text("\\u{0", 2, 6), block_close, eof(7)], vec![]) + ); + let parts = |parts: &[&str]| parts.iter().map(ToString::to_string).collect::>(); + assert_eq!( + lex_escaped("").0[3], + (HtmlTokenType::AttrValueText, parts(&["\\x41"]), 8, 12) + ); + assert_eq!( + 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_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_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_escaped(""), + (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_escaped("").0[0], tag(TagClose, "", "\\x41", 0, 10)); + // Not after a prefix, nor at a tag starting there. + 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_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_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_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_escaped("\\\r\\\r{{a"), + (vec![text("\\\n", 2, 4), interpolation, text("", 7, 7), eof(7)], vec![]) + ); + 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_escaped("{{x\r\\\r\ny}}").0[1].1[1], "x\ny"); + // An escaped CR is a CR too. + 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"); + // So does an ICU's switch value. + assert_eq!(lex_icu("{a\r\n\\r, select, c {d}}").0[1].1, ["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. + assert_eq!(lex_escaped("a\\0"), + ( + 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 +/// values are from Angular 22.3.0. +mod escaped_code_points { + use super::*; + + #[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_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_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_escaped(r"a\u{12"), (vec![eof(6)], vec![eof_error(6)])); + assert_eq!(lex_escaped(r"{{a\u{"), (vec![text("", 0, 0), eof(6)], vec![eof_error(6)])); + assert_eq!(lex_escaped(r#"e"), + (vec![text("\\cd?>e", 4, 13), eof(13)], vec![invalid(6)]) + ); + 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_escaped(r"c"), + (vec![comment_start, text("\\b-->c", 5, 14), eof(14)], vec![invalid(7)]) + ); + } + + #[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_escaped(r"é\xzz"), + (vec![text("\\\\", 0, 13), eof(13)], vec![invalid(2), invalid(11)]) + ); + } + + #[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_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_escaped(r"a\u{\xzz"), (vec![eof(8)], vec![eof_error(8)])); + assert_eq!(lex_escaped(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!(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] + 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";\" 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_stop_an_entity_at_a_bad_escape_in_it() { + // Angular's cursor throws out of `_consumeEntity` when it moves onto a bad escape: the entity is lost, and its + // tokenizer reads the escape as a `\` of text. Expected values are from Angular 22.3.0 (with UTF-8 offsets). + use HtmlTokenType::*; + let invalid = |offset| vec![("Invalid hexadecimal escape sequence".to_string(), offset)]; + assert_eq!(lex(r"&#\xz;", true), (vec![text("\\", 0, 6), eof(6)], invalid(4))); + assert_eq!(lex(r"\xz;", true), (vec![text("\\", 0, 7), eof(7)], invalid(5))); + assert_eq!(lex(r"&#x\xé;", true), (vec![text("\\", 0, 8), eof(8)], invalid(5))); + assert_eq!(lex(r"\ué00;", true), (vec![text("\\", 0, 10), eof(10)], invalid(5))); + assert_eq!(lex(r"a&#\xz;b", true), (vec![text("a\\b", 0, 8), eof(8)], invalid(5))); + assert_eq!(lex(r"&\xzz;", true), (vec![text("\\;", 0, 6), eof(6)], invalid(3))); + // In an attribute value, the tag is left as it is and lexing goes on as text. + let parts = |parts: &[&str]| parts.iter().map(ToString::to_string).collect::>(); + assert_eq!( + lex(r#""#, true), + ( + vec![ + (TagOpenStart, parts(&["", "a"]), 0, 2), + (AttrName, parts(&["", "b"]), 3, 4), + (AttrQuote, parts(&["\""]), 5, 6), + (AttrValueText, parts(&[""]), 6, 6), + text("\\\">", 8, 14), + eof(14), + ], + invalid(10) + ) + ); + // An escape the end of the input cuts short: the cursor cannot move past it. + let eof_error = vec![("Unexpected character \"EOF\"".to_string(), 6)]; + assert_eq!(lex(r"\x4", true), (vec![text("", 0, 0), eof(6)], eof_error)); + } + #[test] fn should_parse_entities_with_more_than_4_hex_digits() { // TS: it("should parse entities with more than 4 hex digits", ...) @@ -2901,6 +3786,66 @@ 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])); + } + + #[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)]) + ); + } } // ============================================================================ @@ -3250,6 +4195,40 @@ mod closing_tags { let result = tokenize("` 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(""), (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])); + } } // ============================================================================