diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs index a3611e51c..e01260611 100644 --- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs +++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs @@ -860,15 +860,26 @@ impl<'a> HtmlLexer<'a> { } } - /// A code-point escape at byte `pos` (a backslash), read as one character 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 character and the escape's length in bytes; none for any other escape. + /// 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. /// - /// The digits are read like JavaScript's `parseInt`, so `\u{41zz}` is `A`. 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. + /// 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. 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'); + 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. + /// + /// 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. + 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{") { @@ -888,12 +899,21 @@ impl<'a> HtmlLexer<'a> { } (&rest[..octal], 8, 1 + octal, true) }; - let ch = parse_int_prefix(digits, radix) - .filter(|_| complete) - .and_then(char::from_u32) - .filter(|&ch| ch != '\0') - .unwrap_or(char::REPLACEMENT_CHARACTER); - Some((ch, len)) + Some((parse_int_prefix(digits, radix).filter(|_| complete), 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. + 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 + } } /// Peeks at a character at offset from current position. @@ -3041,7 +3061,7 @@ 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 && self.peek() != '?' && self.peek() != '>' { + while self.index < self.length && !matches!(self.peek(), '?' | '>') && !self.at_nul() { let ch = self.peek(); self.advance(); if ch == '"' || ch == '\'' || ch == '`' { diff --git a/crates/oxc_angular_compiler/tests/html_lexer_test.rs b/crates/oxc_angular_compiler/tests/html_lexer_test.rs index acf01a450..bf99bc835 100644 --- a/crates/oxc_angular_compiler/tests/html_lexer_test.rs +++ b/crates/oxc_angular_compiler/tests/html_lexer_test.rs @@ -1755,6 +1755,160 @@ mod let_declarations { } } +// ============================================================================ +// Processing Instruction Tests +// ============================================================================ + +mod processing_instructions { + use super::*; + + type Part = (HtmlTokenType, Vec); + 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 errors(input: &str) -> Vec<(String, u32)> { + lex(input, false).1 + } + + #[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()]); + } + + #[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()]); + } + + #[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", + ); + 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(), + ] + ); + } + + #[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()]); + } + + #[test] + fn should_store_the_location_of_a_processing_instruction() { + // TS: it("should store the location of a processing instruction", ...) + let input = r#""#; + let tokens = tokenize(input).tokens; + let spans: Vec<_> = tokens + .iter() + .map(|t| (t.token_type, &input[t.start as usize..t.end as usize])) + .collect(); + assert_eq!( + spans, + [(HtmlTokenType::ProcessingInstruction, input), (HtmlTokenType::Eof, "")] + ); + } + + #[test] + fn should_report_missing_end_of_a_processing_instruction() { + // TS: it("should report missing end of a processing instruction", ...) + assert_eq!(errors("' `b>` "c\"?>"?>d"#); + assert_eq!(result, vec![pi(r#"pi 'a?>' `b>` "c\"?>""#), text("d"), eof()]); + } + + #[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()] + ); + assert_eq!(errors("{{ a z"), pi_end, 8), (eof(), 8, 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)] + ); + } + + #[test] + fn should_end_at_an_escaped_nul_like_angular() { + 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)]; + 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)]); + // A backslash that ends the input is no NUL: the instruction is unterminated. + assert_eq!(lex(r"hello"#); + assert_eq!(result, vec![text("hello", 0)]); + } + #[test] fn should_parse_cdata() { // TS: it("should parse CDATA", ...)