Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 34 additions & 14 deletions crates/oxc_angular_compiler/src/parser/html/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>, 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{") {
Expand All @@ -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.
Expand Down Expand Up @@ -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 == '`' {
Expand Down
154 changes: 154 additions & 0 deletions crates/oxc_angular_compiler/tests/html_lexer_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1755,6 +1755,160 @@ mod let_declarations {
}
}

// ============================================================================
// Processing Instruction Tests
// ============================================================================

mod processing_instructions {
use super::*;

type Part = (HtmlTokenType, Vec<String>);
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#"<?xml version="1.0" encoding="UTF-8"?>"#);
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#"<?xml version="1.0" encoding="UTF-8">"#);
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(
"<!DOCTYPE html>\n<?xml version=\"1.0\" encoding=\"UTF-8\"?> 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#"<?xml version="?" encoding="UTF?>-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#"<?xml version="1.0" encoding="UTF-8"?>"#;
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("<?"), [eof_error(2)]);
}

#[test]
fn should_ignore_end_chars_inside_all_quote_kinds() {
let result = tokenize_and_humanize_parts(r#"<?pi 'a?>' `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("<?pi \"a?>"), [eof_error(9)]);
assert_eq!(errors("<?pi?"), [eof_error(5)]);
assert_eq!(tokenize_and_humanize_parts("<?pi"), vec![eof()]);
assert_eq!(errors("<?pi ?x>y"), [("Unexpected character \"x\"".to_string(), 6)]);
}

#[test]
fn should_end_text_and_interpolations_at_a_processing_instruction() {
assert_eq!(
tokenize_and_humanize_parts("a<?pi?>b"),
vec![text("a"), pi("pi"), text("b"), eof()]
);
assert_eq!(errors("{{ a <?b }}"), [eof_error(11)]);
}

// Expected values below are from Angular 22.3.0.

#[test]
fn should_end_at_a_nul_like_angular() {
let ended =
|pi_end| (vec![(pi("x"), 0, pi_end), (text("y?>z"), pi_end, 8), (eof(), 8, 8)], vec![]);
assert_eq!(lex("<?x\0y?>z", false), ended(4));
assert_eq!(lex("<?x\0y?>z", true), ended(4));
// NUL at the end of the input: the instruction ends there, with no error.
assert_eq!(lex("<?x\0", false), (vec![(pi("x"), 0, 4), (eof(), 4, 4)], vec![]));
// A NUL inside quotes does not end it.
assert_eq!(
lex("<?\"\0\"?>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!("<?x{nul}y?>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("<?x\\\0y?>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"<?x\", true), (vec![(eof(), 4, 4)], vec![eof_error(4)]));
assert_eq!(lex(r"<?\", true), (vec![(eof(), 3, 3)], vec![eof_error(3)]));
}
}

// ============================================================================
// DOCTYPE and CDATA Tests
// ============================================================================
Expand Down
7 changes: 7 additions & 0 deletions crates/oxc_angular_compiler/tests/html_parser_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,13 @@ mod text_nodes {
assert_eq!(result, vec![text("line1\nline2", 0)]);
}

#[test]
fn should_ignore_processing_instruction() {
// TS: it("should ignore processing instruction", ...)
let result = parse_and_humanize(r#"<?xml version="1.0" encoding="UTF-8"?>hello"#);
assert_eq!(result, vec![text("hello", 0)]);
}

#[test]
fn should_parse_cdata() {
// TS: it("should parse CDATA", ...)
Expand Down
Loading