diff --git a/crates/angular_conformance/snapshots/angular.snap.md b/crates/angular_conformance/snapshots/angular.snap.md
index 312bc0958..df40697d4 100644
--- a/crates/angular_conformance/snapshots/angular.snap.md
+++ b/crates/angular_conformance/snapshots/angular.snap.md
@@ -7,15 +7,15 @@
| ast_serializer | 6 | 0 | 0 | 0 | 6 | 100.0% |
| ast_spans | 55 | 0 | 0 | 0 | 55 | 100.0% |
| expression_lexer | 154 | 0 | 0 | 0 | 154 | 100.0% |
-| expression_parser | 401 | 1 | 1 | 0 | 403 | 99.5% |
+| expression_parser | 402 | 0 | 1 | 0 | 403 | 99.8% |
| expression_serializer | 44 | 0 | 0 | 0 | 44 | 100.0% |
-| html_lexer | 291 | 6 | 0 | 0 | 297 | 98.0% |
-| html_parser | 89 | 1 | 0 | 0 | 90 | 98.9% |
+| html_lexer | 297 | 0 | 0 | 0 | 297 | 100.0% |
+| html_parser | 90 | 0 | 0 | 0 | 90 | 100.0% |
| html_whitespace | 21 | 0 | 0 | 0 | 21 | 100.0% |
| r3_transform | 180 | 4 | 0 | 0 | 184 | 97.8% |
| shadow_css | 185 | 2 | 0 | 0 | 187 | 98.9% |
| style_parser | 15 | 0 | 0 | 0 | 15 | 100.0% |
-| **Total** | **1441** | **14** | **1** | **0** | **1456** | **99.0%** |
+| **Total** | **1449** | **6** | **1** | **0** | **1456** | **99.5%** |
## Failed Tests
@@ -29,114 +29,6 @@ Path: `parser/parseAction/template literals/should report error if interpolation
Unexpected parse errors: ["Unexpected token } at column 10 in [`hello ${}`]", "Template literal interpolation cannot be empty at column 10 in [`hello ${}`]"]
```
-#### should report an error if a template literal with an interpolation is not closed: ExpectBindingError { input: "`hello ${a}", error_contains: "Unterminated template literal" }
-Path: `parser/parseAction/template literals/should report an error if a template literal with an interpolation is not closed`
-
-**Expected:**
-```
-Error containing: Unterminated template literal
-```
-
-**Actual:**
-```
-No errors
-```
-
-### html_lexer
-
-#### should parse a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("")]
-```
-
-#### should parse a processing instruction ending with > instead of ?>: HtmlLexerTest { input: "", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction ending with > instead of ?>`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("")]
-```
-
-#### should parse a processing instruction surrounded by other content: HtmlLexerTest { input: "\n hello", test_type: HumanizeParts, expected: [Array [String("TokenType.DOC_TYPE"), String("DOCTYPE html")], Array [String("TokenType.TEXT"), String("\n")], Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.TEXT"), String(" hello")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction surrounded by other content`
-
-**Expected:**
-```
-5 tokens
-```
-
-**Actual:**
-```
-3 tokens: [Array [String("TokenType.DOC_TYPE"), String("DOCTYPE html")], Array [String("TokenType.TEXT"), String("\n hello")], Array [String("TokenType.EOF")]]
-```
-
-#### should parse a processing instruction that contains question marks inside quoted content: HtmlLexerTest { input: "-8\"?>", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"?\" encoding=\"UTF?>-8\"")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction that contains question marks inside quoted content`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"?\" encoding=\"UTF?>-8\"")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("-8\"?>")]
-```
-
-#### should store the location of a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeSourceSpans, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("")], Array [String("TokenType.EOF"), String("")]], options: None }
-Path: `HtmlLexer/processing instructions/should store the location of a processing instruction`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("")]
-```
-
-#### should report missing end of a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeErrors, expected: [Array [String("Unexpected character \"EOF\""), String("0:2")]], options: None }
-Path: `HtmlLexer/processing instructions/should report missing end of a processing instruction`
-
-**Expected:**
-```
-1 errors
-```
-
-**Actual:**
-```
-0 errors
-```
-
-### html_parser
-
-#### should ignore processing instruction: HumanizeDom { input: "hello", expected: [Array [String("html.Text"), String("hello"), Number(0.0), Array [String("hello")]]] }
-Path: `HtmlParser/parse/ignored syntax/should ignore processing instruction`
-
-**Expected:**
-```
-[Array [String("html.Text"), String("hello"), Number(0.0), Array [String("hello")]]]
-```
-
-**Actual:**
-```
-[Array [String("html.Text"), String("hello"), Number(0), Array [String("hello")]]]
-```
-
### r3_transform
#### should ignore safe", expected: [Array [String("Element"), String(":xhtml:div")], Array [String("TextAttribute"), String(":xmlns:xhtml"), String("http://www.w3.org/1999/xhtml")], Array [String("Element"), String(":xhtml:span")], Array [String("Text"), String("safe")]], ignore_error: false }
diff --git a/crates/angular_conformance/src/subsystems/html_lexer.rs b/crates/angular_conformance/src/subsystems/html_lexer.rs
index 11c0fbd75..fb6c9fee0 100644
--- a/crates/angular_conformance/src/subsystems/html_lexer.rs
+++ b/crates/angular_conformance/src/subsystems/html_lexer.rs
@@ -33,6 +33,7 @@ impl HtmlLexerRunner {
HtmlTokenType::AttrValueText => "ATTR_VALUE_TEXT",
HtmlTokenType::AttrValueInterpolation => "ATTR_VALUE_INTERPOLATION",
HtmlTokenType::DocType => "DOC_TYPE",
+ HtmlTokenType::ProcessingInstruction => "PROCESSING_INSTRUCTION",
HtmlTokenType::ExpansionFormStart => "EXPANSION_FORM_START",
HtmlTokenType::ExpansionCaseValue => "EXPANSION_CASE_VALUE",
HtmlTokenType::ExpansionCaseExpStart => "EXPANSION_CASE_EXP_START",
diff --git a/crates/oxc_angular_compiler/src/ast/expression.rs b/crates/oxc_angular_compiler/src/ast/expression.rs
index 2804c7771..16d3244e3 100644
--- a/crates/oxc_angular_compiler/src/ast/expression.rs
+++ b/crates/oxc_angular_compiler/src/ast/expression.rs
@@ -120,6 +120,76 @@ pub enum AngularExpression<'a> {
}
impl<'a> AngularExpression<'a> {
+ /// Whether this tree is more than `limit` nodes deep (a lone node is 1 deep).
+ ///
+ /// Walks the tree with an explicit stack, so a deep tree cannot overflow the
+ /// call stack here.
+ pub fn depth_exceeds(&self, limit: usize) -> bool {
+ let mut stack: std::vec::Vec<(&Self, usize)> = vec![(self, 1)];
+ while let Some((expr, depth)) = stack.pop() {
+ if depth > limit {
+ return true;
+ }
+ let mut push = |child| stack.push((child, depth + 1));
+ match expr {
+ Self::Empty(_)
+ | Self::ImplicitReceiver(_)
+ | Self::ThisReceiver(_)
+ | Self::LiteralPrimitive(_)
+ | Self::RegularExpressionLiteral(_) => {}
+ Self::Chain(e) => e.expressions.iter().for_each(push),
+ Self::Conditional(e) => {
+ push(&e.condition);
+ push(&e.true_exp);
+ push(&e.false_exp);
+ }
+ Self::PropertyRead(e) => push(&e.receiver),
+ Self::SafePropertyRead(e) => push(&e.receiver),
+ Self::KeyedRead(e) => {
+ push(&e.receiver);
+ push(&e.key);
+ }
+ Self::SafeKeyedRead(e) => {
+ push(&e.receiver);
+ push(&e.key);
+ }
+ Self::BindingPipe(e) => {
+ push(&e.exp);
+ e.args.iter().for_each(push);
+ }
+ Self::LiteralArray(e) => e.expressions.iter().for_each(push),
+ Self::LiteralMap(e) => e.values.iter().for_each(push),
+ Self::Interpolation(e) => e.expressions.iter().for_each(push),
+ Self::Binary(e) => {
+ push(&e.left);
+ push(&e.right);
+ }
+ Self::Unary(e) => push(&e.expr),
+ Self::PrefixNot(e) => push(&e.expression),
+ Self::TypeofExpression(e) => push(&e.expression),
+ Self::VoidExpression(e) => push(&e.expression),
+ Self::NonNullAssert(e) => push(&e.expression),
+ Self::Call(e) => {
+ push(&e.receiver);
+ e.args.iter().for_each(push);
+ }
+ Self::SafeCall(e) => {
+ push(&e.receiver);
+ e.args.iter().for_each(push);
+ }
+ Self::TaggedTemplateLiteral(e) => {
+ push(&e.tag);
+ e.template.expressions.iter().for_each(push);
+ }
+ Self::TemplateLiteral(e) => e.expressions.iter().for_each(push),
+ Self::ParenthesizedExpression(e) => push(&e.expression),
+ Self::SpreadElement(e) => push(&e.expression),
+ Self::ArrowFunction(e) => push(&e.body),
+ }
+ }
+ false
+ }
+
/// Returns the span of this expression.
pub fn span(&self) -> ParseSpan {
match self {
diff --git a/crates/oxc_angular_compiler/src/ast/html.rs b/crates/oxc_angular_compiler/src/ast/html.rs
index bf07f8489..424943cf1 100644
--- a/crates/oxc_angular_compiler/src/ast/html.rs
+++ b/crates/oxc_angular_compiler/src/ast/html.rs
@@ -266,6 +266,8 @@ pub enum BlockType {
Boundary,
/// An @error block (inside @defer or @boundary).
Error,
+ /// A block with any other name (`@ifx`), which Angular reports as unrecognized.
+ Unknown,
}
/// A block node (@if, @for, @switch, @defer).
diff --git a/crates/oxc_angular_compiler/src/component/decorator.rs b/crates/oxc_angular_compiler/src/component/decorator.rs
index fcab6a019..6771ed0fa 100644
--- a/crates/oxc_angular_compiler/src/component/decorator.rs
+++ b/crates/oxc_angular_compiler/src/component/decorator.rs
@@ -116,6 +116,23 @@ pub fn extract_component_metadata<'a>(
_ => None,
}
.map(|span| Span::new(span.start + 1, span.end - 1));
+ // ngtsc parses an inline literal's raw text, escapes and all,
+ // with Angular's `EscapedCharacterCursor`: the text it reads
+ // can differ from the literal's value (`\400`, a line
+ // continuation), and a lone surrogate has no `&str` value.
+ if let (Some(span), Some(source)) = (metadata.template_span, source_text)
+ && let Some(raw) = source.get(span.start as usize..span.end as usize)
+ && raw.contains('\\')
+ {
+ let is_template_literal =
+ matches!(&prop.value, Expression::TemplateLiteral(_));
+ if let Some((text, _)) =
+ super::source_locations::cook_literal(raw, 0, is_template_literal)
+ && metadata.template.as_ref().is_none_or(|value| value.as_str() != text)
+ {
+ metadata.template = Some(Ident::from(allocator.alloc_str(&text)));
+ }
+ }
}
"templateUrl" => {
// Evaluated like ngtsc's `parseTemplateDeclaration`, so a
diff --git a/crates/oxc_angular_compiler/src/component/source_locations.rs b/crates/oxc_angular_compiler/src/component/source_locations.rs
index 2fcc61076..1f425145c 100644
--- a/crates/oxc_angular_compiler/src/component/source_locations.rs
+++ b/crates/oxc_angular_compiler/src/component/source_locations.rs
@@ -231,73 +231,156 @@ fn typescript_line_and_character(source: &str, offset: usize) -> (u32, u32) {
(line, character)
}
-/// The value of a string or template literal from its raw text (between the
-/// quotes), with the byte offset in the source of the character each value
-/// byte comes from: an escaped character comes from its backslash, as in
-/// Angular's `EscapedCharacterCursor`.
+/// The template text Angular parses from a string or template literal's raw
+/// text (between the quotes), with the byte offset in the source of the
+/// character each text byte comes from. This is what Angular's
+/// `EscapedCharacterCursor` reads, and ngtsc parses the raw text with it: an
+/// escaped character comes from its backslash. For valid JavaScript the text
+/// is the literal's value, except where the cursor reads an escape another
+/// way:
///
-/// `None` for escapes oxc does not map (legacy octal, `\u` surrogates); the
-/// caller then emits no source locations.
+/// - an octal escape takes up to three octal digits (`\400` is U+0100, not
+/// `\40` then `0`);
+/// - a line continuation skips one character only, so `\` CR LF keeps the
+/// LF, and `\` U+2028 or U+2029 keeps that character;
+/// - after a `\` LF or `\` CR line continuation, the next character is read
+/// as written, even a backslash (`\` LF `\n` is a backslash then `n`).
+///
+/// A lone surrogate (`\uD83D`) is stored as `util::lone_surrogate`
+/// describes, like oxc's value of the literal. A template literal's value
+/// reads a CR LF or CR line break as LF, and so does this text.
+///
+/// `None` for text that is not valid JavaScript: an escape with bad hex
+/// digits, or a backslash at the end.
pub(super) fn cook_literal(
raw: &str,
base: u32,
is_template_literal: bool,
) -> Option<(String, Vec)> {
- let mut cooked = String::with_capacity(raw.len());
- let mut offsets = Vec::with_capacity(raw.len());
- let mut push = |c: char, at: usize| {
- cooked.push(c);
- let at = base.saturating_add(u32::try_from(at).unwrap_or(u32::MAX));
- offsets.extend(std::iter::repeat_n(at, c.len_utf8()));
+ let mut out = Cooked {
+ text: String::with_capacity(raw.len()),
+ offsets: Vec::with_capacity(raw.len()),
+ base,
+ high_surrogate: None,
};
let mut chars = raw.char_indices().peekable();
+ // Whether the next character is read as written, after a line continuation.
+ let mut as_written = false;
while let Some((at, c)) = chars.next() {
- match c {
- '\\' => {
- let (_, escape) = chars.next()?;
- let value = match escape {
- 'n' => '\n',
- 'r' => '\r',
- 't' => '\t',
- 'b' => '\u{8}',
- 'f' => '\u{c}',
- 'v' => '\u{b}',
- '0' if !chars.peek().is_some_and(|(_, c)| c.is_ascii_digit()) => '\0',
- '0'..='9' => return None,
- 'x' => {
- let hex: String =
- (0..2).filter_map(|_| chars.next().map(|(_, c)| c)).collect();
- char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?
- }
- 'u' => {
- let hex: String = if chars.peek().is_some_and(|&(_, c)| c == '{') {
- chars.next();
- chars.by_ref().map(|(_, c)| c).take_while(|&c| c != '}').collect()
- } else {
- (0..4).filter_map(|_| chars.next().map(|(_, c)| c)).collect()
- };
- // A surrogate (half of a pair) has no `char`.
- char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?
- }
- // A line continuation adds nothing.
- '\r' => {
- chars.next_if(|&(_, c)| c == '\n');
- continue;
+ if std::mem::take(&mut as_written) || c != '\\' {
+ if c == '\r' && is_template_literal {
+ chars.next_if(|&(_, c)| c == '\n');
+ out.push('\n', at);
+ } else {
+ out.push(c, at);
+ }
+ continue;
+ }
+ let (_, escape) = chars.next()?;
+ match escape {
+ 'n' => out.push('\n', at),
+ 'r' => out.push('\r', at),
+ 't' => out.push('\t', at),
+ 'b' => out.push('\u{8}', at),
+ 'f' => out.push('\u{c}', at),
+ 'v' => out.push('\u{b}', at),
+ 'x' => out.push_code_point(hex_digits(&mut chars, 2)?, at)?,
+ 'u' => {
+ let code_point = if chars.next_if(|&(_, c)| c == '{').is_some() {
+ let mut value: u32 = 0;
+ let mut digits = 0;
+ loop {
+ let (_, c) = chars.next()?;
+ if c == '}' {
+ break;
+ }
+ value = value.checked_mul(16)?.checked_add(c.to_digit(16)?)?;
+ digits += 1;
}
- '\n' | '\u{2028}' | '\u{2029}' => continue,
- other => other,
+ (digits > 0).then_some(value)?
+ } else {
+ hex_digits(&mut chars, 4)?
};
- push(value, at);
+ out.push_code_point(code_point, at)?;
}
- // A template literal's value reads `\r\n` and `\r` as `\n`.
- '\r' if is_template_literal => {
- chars.next_if(|&(_, c)| c == '\n');
- push('\n', at);
+ '0'..='7' => {
+ let mut value = escape.to_digit(8)?;
+ for _ in 0..2 {
+ let Some((_, digit)) = chars.next_if(|(_, c)| c.is_digit(8)) else { break };
+ value = value * 8 + digit.to_digit(8)?;
+ }
+ out.push_code_point(value, at)?;
}
- _ => push(c, at),
+ // The line break is skipped and the next character, the LF of a CR
+ // LF included, is read as written.
+ '\r' | '\n' => as_written = true,
+ other => out.push(other, at),
}
}
- Some((cooked, offsets))
+ out.flush_high_surrogate();
+ Some((out.text, out.offsets))
+}
+
+/// The value of `count` hex digits.
+fn hex_digits(
+ chars: &mut std::iter::Peekable>,
+ count: usize,
+) -> Option {
+ (0..count).try_fold(0, |value, _| Some(value * 16 + chars.next()?.1.to_digit(16)?))
+}
+
+/// The text [`cook_literal`] builds, with the source offset of each byte.
+struct Cooked {
+ text: String,
+ offsets: Vec,
+ base: u32,
+ /// A high surrogate code unit not yet written, and the raw offset of its
+ /// escape: a low surrogate right after it makes one character with it.
+ high_surrogate: Option<(u32, usize)>,
+}
+
+impl Cooked {
+ fn push(&mut self, c: char, at: usize) {
+ self.flush_high_surrogate();
+ self.push_str(c.encode_utf8(&mut [0; 4]), at);
+ }
+
+ fn push_str(&mut self, s: &str, at: usize) {
+ self.text.push_str(s);
+ let at = self.base.saturating_add(u32::try_from(at).unwrap_or(u32::MAX));
+ self.offsets.extend(std::iter::repeat_n(at, s.len()));
+ }
+
+ /// Writes code point `value`, which may be one half of a surrogate pair.
+ /// `None` past U+10FFFF.
+ fn push_code_point(&mut self, value: u32, at: usize) -> Option<()> {
+ match value {
+ 0xD800..=0xDBFF => {
+ self.flush_high_surrogate();
+ self.high_surrogate = Some((value, at));
+ }
+ 0xDC00..=0xDFFF => match self.high_surrogate.take() {
+ Some((high, high_at)) => {
+ let c = char::from_u32(0x10000 + ((high - 0xD800) << 10) + (value - 0xDC00))?;
+ self.push(c, high_at);
+ }
+ None => self.push_lone_surrogate(value, at),
+ },
+ _ => self.push(char::from_u32(value)?, at),
+ }
+ Some(())
+ }
+
+ fn flush_high_surrogate(&mut self) {
+ if let Some((high, at)) = self.high_surrogate.take() {
+ self.push_lone_surrogate(high, at);
+ }
+ }
+
+ fn push_lone_surrogate(&mut self, unit: u32, at: usize) {
+ let unit = u16::try_from(unit).unwrap_or(0xD800);
+ self.push_str(&crate::util::lone_surrogate::stored(unit), at);
+ }
}
#[cfg(test)]
@@ -378,8 +461,106 @@ d",
.unwrap();
assert_eq!(cooked, "a\nb String {
+ use oxc_ast::ast::{Expression, Statement};
+ let allocator = Allocator::default();
+ let source = allocator.alloc_str(&format!("({literal});"));
+ let ret = oxc_parser::Parser::new(&allocator, source, oxc_span::SourceType::cjs()).parse();
+ let Some(Statement::ExpressionStatement(statement)) = ret.program.body.first() else {
+ panic!("{literal:?} does not parse");
+ };
+ let Expression::ParenthesizedExpression(paren) = &statement.expression else {
+ panic!("{literal:?} is not parenthesized");
+ };
+ let value = match &paren.expression {
+ Expression::StringLiteral(lit) => lit.value,
+ Expression::TemplateLiteral(lit) => lit.quasis[0].value.cooked.unwrap(),
+ _ => panic!("{literal:?} is not a literal"),
+ };
+ crate::util::lone_surrogate::js_str_to_str(value).into_owned()
+ }
+
+ #[test]
+ fn cooks_the_value_oxc_reads() {
+ // Each raw text, and whether it is valid in a template literal too
+ // (octal escapes, `\8` and `\9` are not).
+ for (raw, in_template_literal) in [
+ ("plain é😀", true),
+ (r#"\n\r\t\b\f\v\'\"\\\`\$\a"#, true),
+ (r"\x41\x3c\u0041\u00e9\u{1F600}\u{41}\u{0000041}", true),
+ (r"\uD83D\uDE00 \uD83D \uDE00 \uDE00\uD83D \uD83D\u{DE00} \uD83D\uD83D", true),
+ (r"\u{D83D}x\u{DE00}", true),
+ (r"\0x\0", true),
+ (r"\101\0\00\000\08\377\3777\47\1234\7", false),
+ (r"\8\9\😀", false),
+ ("\\😀", true),
+ ("a\\\nb\\\rc", true),
+ ("\u{2028}a\u{2029}", true),
+ ] {
+ for quote in ['\'', '`'] {
+ if quote == '`' && !in_template_literal {
+ continue;
+ }
+ let literal = format!("{quote}{raw}{quote}");
+ let (cooked, offsets) = cook_literal(raw, 0, quote == '`').unwrap();
+ assert_eq!(cooked, oxc_value(&literal), "{literal:?}");
+ assert_eq!(offsets.len(), cooked.len(), "{literal:?}");
+ }
+ }
+ // Template literals read CR LF and CR as LF.
+ assert_eq!(cook_literal("a\r\nb\rc", 0, true).unwrap().0, oxc_value("`a\r\nb\rc`"));
+ }
+
+ /// Where Angular's `EscapedCharacterCursor` reads an escape another way
+ /// than JavaScript, the text is what ngtsc 22.3.0 compiles.
+ #[test]
+ fn cooks_escapes_like_angular_where_javascript_differs() {
+ let cook = |raw| cook_literal(raw, 0, false).unwrap();
+ // Three octal digits, past `\377`.
+ assert_eq!(oxc_value(r"'\400'"), " 0");
+ assert_eq!(cook(r"\400"), ("\u{100}".into(), vec![0, 0]));
+ assert_eq!(cook(r"\777").0, "\u{1FF}");
+ assert_eq!(cook(r"\4000").0, "\u{100}0");
+ // A line continuation skips one character.
+ assert_eq!(cook("a\\\r\nb"), ("a\nb".into(), vec![0, 3, 4]));
+ assert_eq!(cook("a\\\u{2028}b"), ("a\u{2028}b".into(), vec![0, 1, 1, 1, 5]));
+ assert_eq!(cook("a\\\u{2029}b").0, "a\u{2029}b");
+ assert_eq!(cook_literal("a\\\r\nb", 0, true).unwrap().0, "a\nb");
+ // After `\` LF and `\` CR, the next character is read as written.
+ assert_eq!(cook("a\\\n\\nb"), ("a\\nb".into(), vec![0, 3, 4, 5]));
+ assert_eq!(cook("a\\\r\\nb").0, "a\\nb");
+ assert_eq!(cook("a\\\n\\\nb").0, "a\\\nb");
+ // The escape after it is a lone low surrogate.
+ assert_eq!(
+ cook("a\\\n\\uD83D\\uDE00b").0,
+ format!("a\\uD83D{}b", crate::util::lone_surrogate::stored(0xDE00))
+ );
+ // After `\` CR LF the LF is that character, and escapes go on.
+ assert_eq!(cook("a\\\r\n\\nb").0, "a\n\nb");
+ assert_eq!(cook("a\\\u{2028}\\nb").0, "a\u{2028}\nb");
}
#[test]
diff --git a/crates/oxc_angular_compiler/src/component/transform.rs b/crates/oxc_angular_compiler/src/component/transform.rs
index 001dde100..0e217d2f5 100644
--- a/crates/oxc_angular_compiler/src/component/transform.rs
+++ b/crates/oxc_angular_compiler/src/component/transform.rs
@@ -6598,7 +6598,10 @@ fn html_parse_error_diagnostic(
error: &crate::util::ParseError,
origin: &TemplateOrigin<'_>,
) -> OxcDiagnostic {
- let diagnostic = OxcDiagnostic::error(error.msg.clone());
+ // A message quoting template text with a lone surrogate (`\uD83D`) shows it
+ // as U+FFFD, as ngc's message reads once it is written out as UTF-8.
+ let diagnostic =
+ OxcDiagnostic::error(crate::util::lone_surrogate::lossy(&error.msg).into_owned());
// An error with an empty default span has no position. The transform places
// expression parser errors where Angular reports them, so this is a fallback.
if error.span.start.file.content.is_empty() {
@@ -6613,7 +6616,16 @@ fn html_parse_error_diagnostic(
Some(raw) => raw.get(at as usize).or(raw.last()).copied().unwrap_or(*offset),
None => offset + at,
};
- let (start, end) = (map(start), map(end.max(start)));
+ let (start, mut end) = (map(start), map(end.max(start)));
+ // ngc's `getTemplateDiagnostics` widens an empty span by one, so the
+ // label covers the character at the error (the closing quote at the end).
+ if end <= start {
+ let width = source
+ .get(start as usize..)
+ .and_then(|rest| rest.chars().next())
+ .map_or(0, char::len_utf8);
+ end = start + u32::try_from(width).unwrap_or(0);
+ }
let (line, column) = if *whole_file {
crate::util::file_line_and_column(source, start)
} else {
diff --git a/crates/oxc_angular_compiler/src/i18n/digest.rs b/crates/oxc_angular_compiler/src/i18n/digest.rs
index 059aea867..f2726b745 100644
--- a/crates/oxc_angular_compiler/src/i18n/digest.rs
+++ b/crates/oxc_angular_compiler/src/i18n/digest.rs
@@ -229,6 +229,16 @@ impl Visitor for SerializerIgnoreIcuExpVisitor {
}
}
+/// The bytes `TextEncoder` gives for `str`, as Angular's `sha1` and
+/// `fingerprint` read it: its UTF-8, with a lone surrogate (stored as
+/// `util::lone_surrogate` describes) as U+FFFD.
+fn utf8_encode(str: &str) -> std::borrow::Cow<'_, [u8]> {
+ match crate::util::lone_surrogate::lossy(str) {
+ std::borrow::Cow::Borrowed(text) => std::borrow::Cow::Borrowed(text.as_bytes()),
+ std::borrow::Cow::Owned(text) => std::borrow::Cow::Owned(text.into_bytes()),
+ }
+}
+
// ============================================================================
// SHA1 Implementation
// ============================================================================
@@ -241,7 +251,7 @@ impl Visitor for SerializerIgnoreIcuExpVisitor {
/// DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
#[expect(clippy::many_single_char_names, clippy::unreadable_literal)]
pub fn sha1(str: &str) -> String {
- let utf8 = str.as_bytes();
+ let utf8 = &*utf8_encode(str);
let words32 = bytes_to_words32(utf8, Endian::Big);
let len = utf8.len() * 8;
@@ -331,7 +341,7 @@ fn fk(index: usize, b: u32, c: u32, d: u32) -> (u32, u32) {
/// Based on:
///
pub fn fingerprint(str: &str) -> u64 {
- let utf8 = str.as_bytes();
+ let utf8 = &*utf8_encode(str);
let mut hi = hash32(utf8, 0);
#[expect(clippy::unreadable_literal)]
diff --git a/crates/oxc_angular_compiler/src/lib.rs b/crates/oxc_angular_compiler/src/lib.rs
index eda6c7fae..6d67b165c 100644
--- a/crates/oxc_angular_compiler/src/lib.rs
+++ b/crates/oxc_angular_compiler/src/lib.rs
@@ -66,6 +66,10 @@ pub use transform::{HtmlToR3Transform, html_to_r3::html_ast_to_r3_ast};
// column units as `helpMessage` and `ngc`.
pub use util::{file_line_and_column, line_and_column};
+// The NAPI binding uses it to hand a string with a stored lone surrogate
+// (an inline template written with `\uD83D`) to JavaScript as it is.
+pub use util::lone_surrogate::encode_utf16;
+
// Re-export component module types for convenience
pub use component::{
AngularVersion, ChangeDetectionStrategy, CompiledComponent, ComponentHmrFingerprint,
diff --git a/crates/oxc_angular_compiler/src/output/emitter.rs b/crates/oxc_angular_compiler/src/output/emitter.rs
index fdbb57311..0ccb9a5ba 100644
--- a/crates/oxc_angular_compiler/src/output/emitter.rs
+++ b/crates/oxc_angular_compiler/src/output/emitter.rs
@@ -1068,7 +1068,7 @@ impl JsEmitter {
) {
ctx.print("`");
for (i, element) in expr.elements.iter().enumerate() {
- ctx.print(&element.raw_text);
+ ctx.print(&template_part_text(&element.raw_text));
if i < expr.expressions.len() {
ctx.print("${");
self.visit_expression(&expr.expressions[i], ctx);
@@ -1535,6 +1535,24 @@ fn template_raw_text(raw: &str) -> Cow<'_, str> {
Cow::Owned(result)
}
+/// The raw text of a template literal part as ngtsc prints it. The TypeScript printer
+/// writes the raw text verbatim, and a lone surrogate there (`\`\uD83D\`` in a template
+/// expression, which Angular cooks to the code unit) comes out of its UTF-8 output as
+/// U+FFFD, so the runtime string holds U+FFFD too.
+fn template_part_text(raw: &str) -> Cow<'_, str> {
+ if !has_lone_surrogate(raw) {
+ return Cow::Borrowed(raw);
+ }
+ Cow::Owned(
+ pieces(raw)
+ .map(|piece| match piece {
+ Piece::Lone(_) => char::REPLACEMENT_CHARACTER,
+ Piece::Char(c) => c,
+ })
+ .collect(),
+ )
+}
+
/// Push a `\uXXXX` escape sequence for a 16-bit code unit.
fn push_unicode_escape(buf: &mut String, code: u32) {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
diff --git a/crates/oxc_angular_compiler/src/parser/expression/lexer.rs b/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
index 9ac0d15c1..9805efb2e 100644
--- a/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
+++ b/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
@@ -303,11 +303,38 @@ impl<'a> Token<'a> {
self.token_type == TokenType::Number
}
+ /// The text Angular's `Token.toString()` gives for the token in a message: a
+ /// number's JavaScript value (`1.50` -> `1.5`), else the token's string value.
+ /// A lone surrogate (`'\uD83D'`) is shown as U+FFFD, as ngc's UTF-8 output
+ /// prints the lone code unit Angular's message holds.
+ pub fn message_text(&self) -> String {
+ if self.is_number() {
+ return crate::output::emitter::format_number_like_js(self.num_value);
+ }
+ let text = self.str_value.as_str();
+ if !crate::util::lone_surrogate::has_lone_surrogate(text) {
+ return text.to_string();
+ }
+ crate::util::lone_surrogate::pieces(text)
+ .map(|piece| match piece {
+ crate::util::lone_surrogate::Piece::Char(c) => c,
+ crate::util::lone_surrogate::Piece::Lone(_) => char::REPLACEMENT_CHARACTER,
+ })
+ .collect()
+ }
+
/// Returns true if this is an error token.
pub fn is_error(&self) -> bool {
self.token_type == TokenType::Error
}
+ /// For an error token: Angular's index of the token, the UTF-16 column of the error,
+ /// which the lexer keeps in `num_value`.
+ #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ pub fn error_column(&self) -> usize {
+ self.num_value as usize
+ }
+
/// Returns true if this is a template literal token (any type).
pub fn is_template(&self) -> bool {
matches!(
@@ -396,7 +423,119 @@ const KEYWORDS: &[&str] = &[
"instanceof",
];
-/// Angular expression lexer.
+/// What a `{` on the lexer's brace stack opened: a plain brace (an object literal), or the
+/// `${` of a template literal, whose `}` resumes the template literal.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Brace {
+ Expression,
+ Interpolation,
+}
+
+/// The cooked text of a string or template literal part, built as Angular's `buffer`. An
+/// escape can give a surrogate code unit (`'\uD83D'`): a high one followed at once by a low
+/// one makes their character, as in JavaScript, and a lone one is stored as
+/// `util::lone_surrogate` describes.
+#[derive(Default)]
+struct CookedText {
+ text: String,
+ high_surrogate: Option,
+}
+
+impl CookedText {
+ fn flush_high_surrogate(&mut self) {
+ if let Some(unit) = self.high_surrogate.take() {
+ crate::util::lone_surrogate::push_lone_surrogate(&mut self.text, unit);
+ }
+ }
+
+ fn push_str(&mut self, s: &str) {
+ if !s.is_empty() {
+ self.flush_high_surrogate();
+ self.text.push_str(s);
+ }
+ }
+
+ fn push_char(&mut self, ch: char) {
+ self.flush_high_surrogate();
+ self.text.push(ch);
+ }
+
+ fn push_code_unit(&mut self, unit: u16) {
+ match unit {
+ 0xD800..=0xDBFF => {
+ self.flush_high_surrogate();
+ self.high_surrogate = Some(unit);
+ }
+ 0xDC00..=0xDFFF => {
+ if let Some(high) = self.high_surrogate.take() {
+ let code =
+ 0x10000 + ((u32::from(high) - 0xD800) << 10) + (u32::from(unit) - 0xDC00);
+ self.text.push(char::from_u32(code).unwrap_or(char::REPLACEMENT_CHARACTER));
+ } else {
+ crate::util::lone_surrogate::push_lone_surrogate(&mut self.text, unit);
+ }
+ }
+ _ => self
+ .push_char(char::from_u32(u32::from(unit)).unwrap_or(char::REPLACEMENT_CHARACTER)),
+ }
+ }
+
+ /// The text, followed by `last`.
+ fn finish(mut self, last: &str) -> String {
+ self.push_str(last);
+ self.flush_high_surrogate();
+ self.text
+ }
+}
+
+/// Angular's `unescape`: the character a backslash before `ch` stands for in a string.
+/// Only `\n`, `\f`, `\r`, `\t` and `\v` are escapes; any other character stands for itself
+/// (`'\x41'` is `x41`, `'\0'` is `0`).
+fn unescape(ch: char) -> char {
+ match ch {
+ 'n' => '\n',
+ 'f' => '\u{000C}',
+ 'r' => '\r',
+ 't' => '\t',
+ 'v' => '\u{000B}',
+ _ => ch,
+ }
+}
+
+/// JavaScript's `parseFloat` on the text of a number token (digits, `.`, an exponent): the
+/// value of its longest prefix that is a decimal literal (`1.2.3` reads as `1.2`, `1e5e5` as
+/// `1e5`), rounded as JavaScript does (`100000000000000000000000` is `1e+23`).
+fn parse_float_prefix(text: &str) -> f64 {
+ let bytes = text.as_bytes();
+ let digits_from = |mut i: usize| {
+ while i < bytes.len() && bytes[i].is_ascii_digit() {
+ i += 1;
+ }
+ i
+ };
+ let mut end = digits_from(0);
+ if bytes.get(end) == Some(&b'.') {
+ end = digits_from(end + 1);
+ }
+ if matches!(bytes.get(end), Some(b'e' | b'E')) {
+ let mut exponent = end + 1;
+ if matches!(bytes.get(exponent), Some(b'+' | b'-')) {
+ exponent += 1;
+ }
+ let exponent_end = digits_from(exponent);
+ if exponent_end > exponent {
+ end = exponent_end;
+ }
+ }
+ text[..end].parse::().unwrap_or(f64::NAN)
+}
+
+/// Angular expression lexer: a port of Angular's `_Scanner`.
+///
+/// Angular scans UTF-16 code units. The tokens here keep byte offsets into the input, and the
+/// lexer counts UTF-16 units alongside for the columns of its error messages. An error is an
+/// [`TokenType::Error`] token, whose `num_value` is that UTF-16 column; the parser reports it
+/// when it reaches it, as Angular's does.
pub struct Lexer<'a> {
/// The allocator.
allocator: &'a Allocator,
@@ -406,8 +545,13 @@ pub struct Lexer<'a> {
length: u32,
/// The current byte position.
index: u32,
+ /// Angular's `index`: the UTF-16 index of `index`. Like Angular's, it moves on when the
+ /// lexer advances at the end of the input.
+ utf16: u32,
/// The generated tokens.
tokens: std::vec::Vec>,
+ /// The braces open at the current position.
+ brace_stack: std::vec::Vec,
}
impl<'a> Lexer<'a> {
@@ -416,49 +560,63 @@ impl<'a> Lexer<'a> {
Self {
allocator,
input,
- length: input.len() as u32,
+ length: u32::try_from(input.len()).unwrap_or(u32::MAX),
index: 0,
+ utf16: 0,
tokens: std::vec::Vec::new(),
+ brace_stack: std::vec::Vec::new(),
}
}
/// Tokenizes the input and returns the tokens.
pub fn tokenize(mut self) -> std::vec::Vec> {
- while self.index < self.length {
- let start = self.index;
- self.scan_token(start);
+ while let Some(token) = self.scan_token() {
+ self.tokens.push(token);
}
self.tokens
}
- /// Peeks at the current character.
- /// Returns the next UTF-8 character or EOF if at end of input.
+ /// The character at the current position, or `EOF` at the end of the input. As
+ /// Angular's `peek`, a NUL in the input reads as `EOF` too.
fn peek(&self) -> char {
- if self.index >= self.length {
- chars::EOF
- } else {
- self.input[self.index as usize..].chars().next().unwrap_or(chars::EOF)
- }
- }
-
- /// Peeks at a character at offset from current position.
- /// Note: offset is in characters, not bytes. For multi-byte UTF-8 characters,
- /// this iterates through the characters to find the one at the given offset.
- fn peek_at(&self, offset: u32) -> char {
- if self.index >= self.length {
- return chars::EOF;
+ self.input
+ .get(self.index as usize..)
+ .and_then(|rest| rest.chars().next())
+ .unwrap_or(chars::EOF)
+ }
+
+ /// The byte at `index`, or 0 outside the input.
+ fn byte_at(&self, index: u32) -> u8 {
+ self.input.as_bytes().get(index as usize).copied().unwrap_or(0)
+ }
+
+ /// Moves past the current character. At the end of the input only the UTF-16 index moves
+ /// on, as Angular's `index` does.
+ fn advance(&mut self) {
+ let mut rest = self.input.get(self.index as usize..).unwrap_or("").chars();
+ match rest.next() {
+ Some(ch) => {
+ // A stored lone surrogate (`util::lone_surrogate`, two characters) is the
+ // one UTF-16 unit it stands for.
+ if let Some(second) = rest.next()
+ && crate::util::lone_surrogate::is_stored(ch, second)
+ {
+ self.index +=
+ u32::try_from(ch.len_utf8() + second.len_utf8()).unwrap_or_default();
+ self.utf16 += 1;
+ return;
+ }
+ self.index += u32::try_from(ch.len_utf8()).unwrap_or_default();
+ self.utf16 += u32::try_from(ch.len_utf16()).unwrap_or_default();
+ }
+ None => self.utf16 += 1,
}
- self.input[self.index as usize..].chars().nth(offset as usize).unwrap_or(chars::EOF)
}
- /// Advances the index by the current character's byte length and returns the character.
- fn advance(&mut self) -> char {
- let ch = self.peek();
- // By the index, not the character: a NUL in the input reads as `EOF` too.
- if !self.is_eof() {
- self.index += ch.len_utf8() as u32;
- }
- ch
+ /// Whether the next two characters are a stored lone surrogate.
+ fn at_stored_lone_surrogate(&self) -> bool {
+ let mut rest = self.input.get(self.index as usize..).unwrap_or("").chars();
+ matches!((rest.next(), rest.next()), (Some(a), Some(b)) if crate::util::lone_surrogate::is_stored(a, b))
}
/// Returns true if at end of input.
@@ -466,1094 +624,494 @@ impl<'a> Lexer<'a> {
self.index >= self.length
}
- /// Whitespace as Angular's `scanToken` skips it: every character up to the space (NUL and the
- /// other control characters too), and NBSP.
- fn is_skipped_whitespace(ch: char) -> bool {
- ch <= chars::SPACE || ch == chars::NBSP
- }
-
- /// Skips whitespace characters.
- fn skip_whitespace(&mut self) {
- while !self.is_eof() && Self::is_skipped_whitespace(self.peek()) {
+ /// Angular's `scanToken`.
+ fn scan_token(&mut self) -> Option> {
+ // Angular skips every character up to the space (NUL and the other control
+ // characters too), and whitespace after an NBSP.
+ while !self.is_eof() && (self.peek() <= chars::SPACE || self.peek() == chars::NBSP) {
self.advance();
}
- }
-
- /// Scans a single token.
- fn scan_token(&mut self, start: u32) {
- let ch = self.advance();
-
- // Whitespace
- if Self::is_skipped_whitespace(ch) {
- return;
+ if self.is_eof() {
+ return None;
}
- // Identifier or keyword
+ let start = self.index;
+ let ch = self.peek();
if chars::is_identifier_start(ch) {
- self.scan_identifier(start);
- return;
- }
-
- // Private identifier or invalid hash
- if ch == chars::HASH {
- if chars::is_identifier_start(self.peek()) {
- self.scan_private_identifier(start);
- } else {
- // Invalid hash character - emit an error matching Angular's format
- let message = format!(
- "Lexer Error: Invalid character [#] at column {} in expression [{}]",
- start, self.input
- );
- self.error(start, &message);
- }
- return;
+ return Some(self.scan_identifier());
}
-
- // Number
if chars::is_digit(ch) {
- self.scan_number(start);
- return;
+ return Some(self.scan_number(start));
}
- match ch {
- // String literals
- chars::SQ | chars::DQ => {
- self.scan_string(start, ch);
- }
- // Template literal
- chars::BT => {
- self.scan_template_string(start);
- }
- // Operators and punctuation
- chars::PLUS | chars::MINUS => self.scan_plus_or_minus(start, ch),
- chars::STAR => {
- if self.peek() == chars::STAR {
- self.advance();
- // Check for **= (exponentiation assignment)
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "**=");
- } else {
- self.scan_operator(start, "**");
- }
- } else if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "*=");
- } else {
- self.scan_operator(start, "*");
+ let token = match ch {
+ chars::PERIOD => {
+ self.advance();
+ if chars::is_digit(self.peek()) {
+ return Some(self.scan_number(start));
}
- }
- chars::SLASH => {
- // Check if this is a regex or division
- if self.last_token_allows_regex() {
- // In regex context, scan as regex (errors will be reported if unterminated)
- self.scan_regex(start);
- } else if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "/=");
- } else {
- self.scan_operator(start, "/");
+ if self.peek() != chars::PERIOD {
+ return Some(Token::new_character(start, self.index, ch, self.allocator));
}
- }
- chars::PERCENT => {
- if self.peek() == chars::EQ {
+ self.advance();
+ if self.peek() == chars::PERIOD {
self.advance();
- self.scan_operator(start, "%=");
- } else {
- self.scan_operator(start, "%");
+ return Some(Token::new_operator(start, self.index, "...", self.allocator));
}
+ self.error("Unexpected character [.]", 0)
}
- chars::CARET => {
- self.scan_operator(start, "^");
- }
- chars::QUESTION => {
- if self.peek() == chars::QUESTION {
- self.advance();
- // Check for ??= (nullish coalescing assignment)
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "??=");
- } else {
- self.scan_operator(start, "??");
- }
- } else if self.peek() == chars::PERIOD {
- self.advance();
- self.scan_operator(start, "?.");
- } else {
- self.scan_character(start, ch);
- }
+ '(' | ')' | '[' | ']' | ',' | ':' | ';' => self.scan_character(start, ch),
+ chars::LBRACE => {
+ self.brace_stack.push(Brace::Expression);
+ self.scan_character(start, ch)
}
- chars::LT => {
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "<=");
- } else {
- self.scan_operator(start, "<");
- }
+ chars::RBRACE => self.scan_close_brace(start),
+ chars::SQ | chars::DQ => self.scan_string(),
+ chars::BT => {
+ self.advance();
+ self.scan_template_literal_part(start, true)
}
- chars::GT => {
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, ">=");
+ chars::HASH => self.scan_private_identifier(),
+ chars::PLUS | chars::MINUS => self.scan_plus_or_minus(start, ch),
+ chars::SLASH => {
+ if self.is_start_of_regex() {
+ self.scan_regex(start)
} else {
- self.scan_operator(start, ">");
+ self.scan_complex_operator(start, ch, chars::EQ, None)
}
}
- chars::BANG => {
- if self.peek() == chars::EQ {
- self.advance();
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "!==");
- } else {
- self.scan_operator(start, "!=");
- }
- } else {
- // Standalone ! is an operator (negation/non-null assertion)
- self.scan_operator(start, "!");
- }
+ chars::PERCENT | chars::LT | chars::GT => {
+ self.scan_complex_operator(start, ch, chars::EQ, None)
}
- chars::EQ => {
- if self.peek() == chars::EQ {
- self.advance();
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "===");
- } else {
- self.scan_operator(start, "==");
- }
- } else if self.peek() == chars::GT {
- // Arrow function =>
- self.advance();
- self.scan_operator(start, "=>");
- } else {
- // Standalone = is an operator (assignment)
- self.scan_operator(start, "=");
- }
+ chars::CARET => {
+ self.advance();
+ Token::new_operator(start, self.index, "^", self.allocator)
}
- chars::AMPERSAND => {
- if self.peek() == chars::AMPERSAND {
- self.advance();
- // Check for &&= (logical AND assignment)
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "&&=");
- } else {
- self.scan_operator(start, "&&");
- }
- } else {
- self.scan_character(start, ch);
- }
+ chars::STAR => self.scan_star(start),
+ chars::QUESTION => self.scan_question(start),
+ chars::BANG => self.scan_complex_operator(start, ch, chars::EQ, Some(chars::EQ)),
+ chars::EQ => self.scan_equals(start),
+ chars::AMPERSAND | chars::BAR => {
+ self.scan_complex_operator(start, ch, ch, Some(chars::EQ))
}
- chars::BAR => {
- if self.peek() == chars::BAR {
- self.advance();
- // Check for ||= (logical OR assignment)
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "||=");
- } else {
- self.scan_operator(start, "||");
- }
- } else if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "|=");
- } else {
- // Single | is an operator (used for pipes in Angular)
- self.scan_operator(start, "|");
- }
+ // A stored lone surrogate is one character, which a message shows as U+FFFD.
+ _ if self.at_stored_lone_surrogate() => {
+ self.advance();
+ self.error(&format!("Unexpected character [{}]", char::REPLACEMENT_CHARACTER), 0)
}
- chars::PERIOD => {
- if chars::is_digit(self.peek()) {
- self.index = start;
- self.advance(); // re-consume the period
- self.scan_number(start);
- } else if self.peek() == chars::PERIOD {
- // Could be spread operator ...
- self.advance(); // Second period
- if self.peek() == chars::PERIOD {
- self.advance(); // Third period
- self.scan_operator(start, "...");
- } else {
- // Two dots is an error - Angular uses `peek` from start (the first period)
- // Error position should be at current index (after second period)
- let error_pos = self.index;
- let message = format!(
- "Lexer Error: Unexpected character [{ch}] at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error(error_pos, &message);
- }
+ _ => {
+ self.advance();
+ if ch.len_utf16() == 2 {
+ // Angular reads the two halves of a surrogate pair one at a time, and
+ // each is an unexpected character (printed as U+FFFD).
+ let message = self.error_message(
+ &format!("Unexpected character [{}]", char::REPLACEMENT_CHARACTER),
+ self.utf16 - 1,
+ );
+ let first = self.error_token(start, start, self.utf16 - 1, &message);
+ self.tokens.push(first);
+ self.error(
+ &format!("Unexpected character [{}]", char::REPLACEMENT_CHARACTER),
+ 0,
+ )
} else {
- self.scan_character(start, ch);
+ self.error(&format!("Unexpected character [{ch}]"), 0)
}
}
- // Other characters
- _ => {
- self.scan_character(start, ch);
- }
- }
+ };
+ Some(token)
}
/// Scans a character token.
- fn scan_character(&mut self, start: u32, ch: char) {
- let token = Token::new_character(start, self.index, ch, &self.allocator);
- self.tokens.push(token);
- }
-
- /// Scans `+`, `-`, `++`, `--`, `+=` or `-=`. `ch` has already been consumed.
- fn scan_plus_or_minus(&mut self, start: u32, ch: char) {
- let op = if self.peek() == ch {
- self.advance();
- if ch == chars::PLUS { "++" } else { "--" }
- } else if self.peek() == chars::EQ {
- self.advance();
- if ch == chars::PLUS { "+=" } else { "-=" }
- } else if ch == chars::PLUS {
- "+"
- } else {
- "-"
- };
- self.scan_operator(start, op);
+ fn scan_character(&mut self, start: u32, ch: char) -> Token<'a> {
+ self.advance();
+ Token::new_character(start, self.index, ch, self.allocator)
}
- /// Scans an operator token.
- fn scan_operator(&mut self, start: u32, op: &str) {
- let token = Token::new_operator(start, self.index, op, &self.allocator);
- self.tokens.push(token);
+ /// Angular's `scanCloseBrace`: a `}` that closes a template literal's `${` gives its
+ /// character token, and the lexer goes on with the template literal.
+ fn scan_close_brace(&mut self, start: u32) -> Token<'a> {
+ self.advance();
+ if self.brace_stack.pop() == Some(Brace::Interpolation) {
+ self.tokens.push(Token::new_character(
+ start,
+ self.index,
+ chars::RBRACE,
+ self.allocator,
+ ));
+ return self.scan_template_literal_part(self.index, false);
+ }
+ Token::new_character(start, self.index, chars::RBRACE, self.allocator)
}
- /// Scans an identifier or keyword.
- fn scan_identifier(&mut self, start: u32) {
- while chars::is_identifier_part(self.peek()) {
+ /// Angular's `scanComplexOperator`: `one`, then `two` if it follows, then `three` if it
+ /// follows (`!`, `!=`, `!==`; `&`, `&&`, `&=`, `&&=`).
+ fn scan_complex_operator(
+ &mut self,
+ start: u32,
+ one: char,
+ two: char,
+ three: Option,
+ ) -> Token<'a> {
+ self.advance();
+ let mut op = String::from(one);
+ if self.peek() == two {
self.advance();
+ op.push(two);
}
-
- let text = &self.input[start as usize..self.index as usize];
- let token = if KEYWORDS.contains(&text) {
- Token::new_keyword(start, self.index, text, &self.allocator)
- } else {
- Token::new_identifier(start, self.index, text, &self.allocator)
- };
- self.tokens.push(token);
- }
-
- /// Scans a private identifier.
- fn scan_private_identifier(&mut self, start: u32) {
- self.advance(); // consume the identifier start character
- while chars::is_identifier_part(self.peek()) {
+ if let Some(three) = three
+ && self.peek() == three
+ {
self.advance();
+ op.push(three);
}
-
- // Include the # in the str_value to match Angular's TypeScript implementation
- let text = &self.input[start as usize..self.index as usize];
- let token = Token::new_private_identifier(start, self.index, text, &self.allocator);
- self.tokens.push(token);
+ Token::new_operator(start, self.index, &op, self.allocator)
}
- /// Scans a number literal, including support for numeric separators.
- fn scan_number(&mut self, start: u32) {
- // Check if number starts with a period (e.g., .5)
- let start_char = self.input[start as usize..].chars().next();
- let mut is_float = start_char == Some('.');
-
- // Check for hex, octal, or binary
- if start_char == Some('0') {
- let next = self.peek();
- if next == 'x' || next == 'X' {
- self.advance();
- return self.scan_hex_number(start);
- }
- if next == 'o' || next == 'O' {
- self.advance();
- return self.scan_octal_number(start);
- }
- if next == 'b' || next == 'B' {
+ /// Angular's `scanEquals`: `=`, `==`, `===` or `=>`.
+ fn scan_equals(&mut self, start: u32) -> Token<'a> {
+ self.advance();
+ let op = if self.peek() == chars::EQ {
+ self.advance();
+ if self.peek() == chars::EQ {
self.advance();
- return self.scan_binary_number(start);
- }
- }
-
- // Scan integer part (with numeric separators)
- let mut last_underscore_pos: Option = None;
- while chars::is_digit(self.peek()) || self.peek() == '_' {
- if self.peek() == '_' {
- if let Some(error_pos) = last_underscore_pos {
- // Double underscore is invalid - report at the first underscore
- let message = format!(
- "Lexer Error: Invalid numeric separator at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error_at(error_pos, error_pos, &message);
- return;
- }
- last_underscore_pos = Some(self.index);
+ "==="
} else {
- last_underscore_pos = None;
+ "=="
}
+ } else if self.peek() == chars::GT {
self.advance();
- }
-
- // Check for trailing underscore before decimal point
- if let Some(underscore_pos) = last_underscore_pos {
- let message = format!(
- "Lexer Error: Invalid numeric separator at column {} in expression [{}]",
- underscore_pos, self.input
- );
- self.error_at(underscore_pos, underscore_pos, &message);
- return;
- }
+ "=>"
+ } else {
+ "="
+ };
+ Token::new_operator(start, self.index, op, self.allocator)
+ }
- // Scan decimal part
- if self.peek() == chars::PERIOD {
- is_float = true;
+ /// Angular's `scanQuestion`: `?`, `??`, `??=` or `?.`. A lone `?` is a character token
+ /// here (an operator in Angular).
+ fn scan_question(&mut self, start: u32) -> Token<'a> {
+ self.advance();
+ let op = if self.peek() == chars::QUESTION {
self.advance();
-
- // Check for leading underscore after decimal point
- if self.peek() == '_' {
- let error_pos = self.index;
- let message = format!(
- "Lexer Error: Invalid numeric separator at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error_at(error_pos, error_pos, &message);
- return;
- }
-
- last_underscore_pos = None;
- while chars::is_digit(self.peek()) || self.peek() == '_' {
- if self.peek() == '_' {
- if let Some(error_pos) = last_underscore_pos {
- let message = format!(
- "Lexer Error: Invalid numeric separator at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error_at(error_pos, error_pos, &message);
- return;
- }
- last_underscore_pos = Some(self.index);
- } else {
- last_underscore_pos = None;
- }
+ if self.peek() == chars::EQ {
self.advance();
+ "??="
+ } else {
+ "??"
}
+ } else if self.peek() == chars::PERIOD {
+ self.advance();
+ "?."
+ } else {
+ return Token::new_character(start, self.index, chars::QUESTION, self.allocator);
+ };
+ Token::new_operator(start, self.index, op, self.allocator)
+ }
- // Check for trailing underscore
- if let Some(underscore_pos) = last_underscore_pos {
- let message = format!(
- "Lexer Error: Invalid numeric separator at column {} in expression [{}]",
- underscore_pos, self.input
- );
- self.error_at(underscore_pos, underscore_pos, &message);
- return;
- }
- }
-
- // Scan exponent
- if self.peek() == 'e' || self.peek() == 'E' {
- is_float = true;
+ /// Angular's `scanStar`: `*`, `**`, `**=` or `*=`.
+ fn scan_star(&mut self, start: u32) -> Token<'a> {
+ self.advance();
+ let op = if self.peek() == chars::STAR {
self.advance();
- if self.peek() == chars::PLUS || self.peek() == chars::MINUS {
- self.advance();
- }
- // Check for valid exponent start (not an underscore)
- if self.peek() == '_' || !chars::is_digit(self.peek()) {
- let error_pos = self.index;
- let message = format!(
- "Lexer Error: Invalid exponent at column {} in expression [{}]",
- error_pos - 1,
- self.input
- );
- self.error_at(error_pos - 1, error_pos, &message);
- return;
- }
- while chars::is_digit(self.peek()) {
+ if self.peek() == chars::EQ {
self.advance();
+ "**="
+ } else {
+ "**"
}
- }
-
- let text = &self.input[start as usize..self.index as usize];
- // Remove underscores for parsing
- let cleaned_text = text.replace('_', "");
- let value = if is_float {
- cleaned_text.parse::().unwrap_or(0.0)
+ } else if self.peek() == chars::EQ {
+ self.advance();
+ "*="
} else {
- cleaned_text.parse::().unwrap_or(0) as f64
+ "*"
};
+ Token::new_operator(start, self.index, op, self.allocator)
+ }
- let token = Token::new_number(start, self.index, value, &self.allocator);
- self.tokens.push(token);
+ /// Scans `+`, `-`, `++`, `--`, `+=` or `-=`.
+ fn scan_plus_or_minus(&mut self, start: u32, ch: char) -> Token<'a> {
+ self.advance();
+ let op = if self.peek() == ch {
+ self.advance();
+ if ch == chars::PLUS { "++" } else { "--" }
+ } else if self.peek() == chars::EQ {
+ self.advance();
+ if ch == chars::PLUS { "+=" } else { "-=" }
+ } else if ch == chars::PLUS {
+ "+"
+ } else {
+ "-"
+ };
+ Token::new_operator(start, self.index, op, self.allocator)
}
- /// Scans a hexadecimal number.
- fn scan_hex_number(&mut self, start: u32) {
- if !chars::is_ascii_hex_digit(self.peek()) {
- self.error(start, "Invalid hexadecimal number");
- return;
- }
- while chars::is_ascii_hex_digit(self.peek()) || self.peek() == '_' {
+ /// Scans an identifier or keyword.
+ fn scan_identifier(&mut self) -> Token<'a> {
+ let start = self.index;
+ self.advance();
+ while chars::is_identifier_part(self.peek()) {
self.advance();
}
- let text = &self.input[(start + 2) as usize..self.index as usize];
- let text = text.replace('_', "");
- let value = i64::from_str_radix(&text, 16).unwrap_or(0) as f64;
- let token = Token::new_number(start, self.index, value, &self.allocator);
- self.tokens.push(token);
- }
-
- /// Scans an octal number.
- fn scan_octal_number(&mut self, start: u32) {
- if !chars::is_octal_digit(self.peek()) {
- self.error(start, "Invalid octal number");
- return;
- }
- while chars::is_octal_digit(self.peek()) || self.peek() == '_' {
- self.advance();
+ let text = &self.input[start as usize..self.index as usize];
+ if KEYWORDS.contains(&text) {
+ Token::new_keyword(start, self.index, text, self.allocator)
+ } else {
+ Token::new_identifier(start, self.index, text, self.allocator)
}
- let text = &self.input[(start + 2) as usize..self.index as usize];
- let text = text.replace('_', "");
- let value = i64::from_str_radix(&text, 8).unwrap_or(0) as f64;
- let token = Token::new_number(start, self.index, value, &self.allocator);
- self.tokens.push(token);
- }
-
- /// Scans a binary number.
- fn scan_binary_number(&mut self, start: u32) {
- if self.peek() != '0' && self.peek() != '1' {
- self.error(start, "Invalid binary number");
- return;
+ }
+
+ /// Angular's `scanPrivateIdentifier`: `#` and an identifier, which keeps the `#`.
+ fn scan_private_identifier(&mut self) -> Token<'a> {
+ let start = self.index;
+ self.advance();
+ if !chars::is_identifier_start(self.peek()) {
+ return self.error("Invalid character [#]", -1);
}
- while self.peek() == '0' || self.peek() == '1' || self.peek() == '_' {
+ while chars::is_identifier_part(self.peek()) {
self.advance();
}
- let text = &self.input[(start + 2) as usize..self.index as usize];
- let text = text.replace('_', "");
- let value = i64::from_str_radix(&text, 2).unwrap_or(0) as f64;
- let token = Token::new_number(start, self.index, value, &self.allocator);
- self.tokens.push(token);
+ let text = &self.input[start as usize..self.index as usize];
+ Token::new_private_identifier(start, self.index, text, self.allocator)
}
- /// Scans a string literal.
- fn scan_string(&mut self, start: u32, quote: char) {
- let mut result = String::new();
-
+ /// Angular's `scanNumber`: digits with `.`s, exponents and numeric separators (`_`
+ /// between two digits), read by JavaScript's `parseInt` or `parseFloat`. There are no
+ /// hexadecimal, octal or binary numbers (`0x10` is `0` and then `x10`).
+ fn scan_number(&mut self, start: u32) -> Token<'a> {
+ let mut has_separators = false;
+ self.advance();
loop {
let ch = self.peek();
- if ch == chars::EOF {
- self.error(start, "Unterminated string");
- return;
- }
- if ch == quote {
- self.advance();
- break;
- }
- if ch == chars::BACKSLASH {
- let escape_start = self.index;
- self.advance();
- match self.scan_escape_sequence_with_error(escape_start) {
- Ok(escaped) => result.push(escaped),
- Err((err_index, err_end, message)) => {
- self.error_at(err_index, err_end, &message);
- return;
- }
+ if chars::is_digit(ch) {
+ // A digit.
+ } else if ch == chars::UNDERSCORE {
+ if !self.byte_at(self.index.wrapping_sub(1)).is_ascii_digit()
+ || !self.byte_at(self.index + 1).is_ascii_digit()
+ {
+ return self.error("Invalid numeric separator", 0);
}
- } else {
- result.push(self.advance());
- }
- }
-
- let token = Token::new_string(start, self.index, &result, &self.allocator);
- self.tokens.push(token);
- }
-
- /// Scans a template string, handling ${...} interpolations.
- /// This method handles the full template including embedded expressions.
- fn scan_template_string(&mut self, start: u32) {
- let mut result = String::new();
- let part_start = start;
-
- loop {
- let ch = self.peek();
- if ch == chars::EOF {
- // Error at the end of input where we expected more
- let error_pos = self.index;
- let message = format!(
- "Lexer Error: Unterminated template literal at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error_at(error_pos, error_pos, &message);
- return;
- }
- if ch == chars::BT {
+ has_separators = true;
+ } else if ch == chars::PERIOD {
+ // Part of the number, as many times as it comes.
+ } else if ch == 'e' || ch == 'E' {
self.advance();
- // No substitutions - complete template
- let token = Token::new_no_substitution_template(
- part_start,
- self.index,
- &result,
- &self.allocator,
- );
- self.tokens.push(token);
- return;
- }
- if ch == chars::DOLLAR && self.peek_at(1) == chars::LBRACE {
- // Start of substitution - create TemplateHead ending at current position
- let head_end = self.index;
- let token =
- Token::new_template_head(part_start, head_end, &result, &self.allocator);
- self.tokens.push(token);
-
- // Emit the ${ as an operator token
- let interp_start = self.index;
- self.advance(); // $
- self.advance(); // {
- let interp_token =
- Token::new_operator(interp_start, self.index, "${", &self.allocator);
- self.tokens.push(interp_token);
-
- // Scan the expression tokens inside ${...}
- self.scan_template_expression();
-
- // Only continue scanning if we haven't hit EOF or an error
- // (An error token would have been created inside if EOF was reached)
- if !self.is_eof() {
- // Continue scanning the rest of the template
- self.scan_template_continuation_internal();
+ if self.peek() == chars::PLUS || self.peek() == chars::MINUS {
+ self.advance();
+ }
+ if !chars::is_digit(self.peek()) {
+ return self.error("Invalid exponent", -1);
}
- return;
- }
- if ch == chars::BACKSLASH {
- self.advance();
- let escaped = self.scan_escape_sequence();
- result.push(escaped);
} else {
- result.push(self.advance());
- }
- }
- }
-
- /// Scans tokens inside a template expression ${...}.
- /// Stops when it sees a closing } at the right nesting level.
- fn scan_template_expression(&mut self) {
- let mut brace_depth = 1; // We already consumed the opening {
-
- while !self.is_eof() && brace_depth > 0 {
- self.skip_whitespace();
- if self.is_eof() {
break;
}
-
- let start = self.index;
- let ch = self.peek();
-
- // Track brace nesting
- if ch == chars::LBRACE {
- brace_depth += 1;
- self.advance();
- self.scan_character(start, ch);
- continue;
- }
- if ch == chars::RBRACE {
- brace_depth -= 1;
- if brace_depth == 0 {
- // End of template expression - emit the closing } as a Character token
- self.advance();
- self.scan_character(start, ch);
- return;
- }
- self.advance();
- self.scan_character(start, ch);
- continue;
- }
-
- // Scan regular token
- self.scan_token_at(start, ch);
+ self.advance();
}
+ let text = &self.input[start as usize..self.index as usize];
+ // `parseInt` and `parseFloat` agree on digits alone.
+ let value = if has_separators {
+ parse_float_prefix(&text.replace('_', ""))
+ } else {
+ parse_float_prefix(text)
+ };
+ Token::new_number(start, self.index, value, self.allocator)
}
- /// Internal helper for scanning template continuation after an expression.
- fn scan_template_continuation_internal(&mut self) {
- let mut result = String::new();
- let part_start = self.index;
-
- loop {
- let ch = self.peek();
- if ch == chars::EOF {
- // Error at the end of input where we expected more
- let error_pos = self.index;
- let message = format!(
- "Lexer Error: Unterminated template literal at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error_at(error_pos, error_pos, &message);
- return;
- }
- if ch == chars::BT {
- self.advance();
- // End of template - create TemplateTail
- let token =
- Token::new_template_tail(part_start, self.index, &result, &self.allocator);
- self.tokens.push(token);
- return;
- }
- if ch == chars::DOLLAR && self.peek_at(1) == chars::LBRACE {
- // Another substitution - create TemplateMiddle ending at current position
- let middle_end = self.index;
- let token =
- Token::new_template_middle(part_start, middle_end, &result, &self.allocator);
- self.tokens.push(token);
-
- // Emit the ${ as an operator token
- let interp_start = self.index;
- self.advance(); // $
- self.advance(); // {
- let interp_token =
- Token::new_operator(interp_start, self.index, "${", &self.allocator);
- self.tokens.push(interp_token);
-
- // Scan the expression tokens
- self.scan_template_expression();
-
- // Continue recursively
- self.scan_template_continuation_internal();
- return;
- }
- if ch == chars::BACKSLASH {
- self.advance();
- let escaped = self.scan_escape_sequence();
- result.push(escaped);
+ /// Angular's `scanString`.
+ fn scan_string(&mut self) -> Token<'a> {
+ let start = self.index;
+ let quote = self.peek();
+ self.advance();
+ let mut buffer = CookedText::default();
+ let mut marker = self.index;
+ while self.peek() != quote {
+ if self.peek() == chars::BACKSLASH {
+ if let Err(error) = self.scan_string_backslash(&mut buffer, marker) {
+ return error;
+ }
+ marker = self.index;
+ } else if self.peek() == chars::EOF {
+ return self.error("Unterminated quote", 0);
} else {
- result.push(self.advance());
+ self.advance();
}
}
- }
-
- /// Scans a single token at the current position.
- /// This is used by scan_template_expression to tokenize embedded expressions.
- fn scan_token_at(&mut self, start: u32, ch: char) {
- // Advance past the first character (like scan_token does)
+ let text = buffer.finish(&self.input[marker as usize..self.index as usize]);
self.advance();
-
- // Identifier or keyword
- if chars::is_identifier_start(ch) {
- self.scan_identifier(start);
- return;
- }
-
- // Number
- if chars::is_digit(ch) {
- self.scan_number(start);
- return;
- }
-
- match ch {
- // String literals
- chars::SQ | chars::DQ => {
- self.scan_string(start, ch);
- }
- // Nested template literal - recursively scan it
- chars::BT => {
- self.scan_template_string(start);
- }
- // Operators and punctuation - reuse existing scanning logic
- chars::PLUS | chars::MINUS => self.scan_plus_or_minus(start, ch),
- chars::STAR => {
- if self.peek() == chars::STAR {
- self.advance();
- self.scan_operator(start, "**");
- } else {
- self.scan_operator(start, "*");
- }
- }
- chars::SLASH => self.scan_operator(start, "/"),
- chars::PERCENT => self.scan_operator(start, "%"),
- chars::CARET => self.scan_operator(start, "^"),
- chars::QUESTION => {
- if self.peek() == chars::QUESTION {
- self.advance();
- self.scan_operator(start, "??");
- } else if self.peek() == chars::PERIOD {
- self.advance();
- self.scan_operator(start, "?.");
- } else {
- self.scan_character(start, ch);
- }
- }
- chars::LT => {
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "<=");
- } else {
- self.scan_operator(start, "<");
+ Token::new_string(start, self.index, &text, self.allocator)
+ }
+
+ /// Angular's `scanTemplateLiteralPart`: the text of a template literal from the current
+ /// position up to a `${` (a head or middle part, followed by the `${` token, which is
+ /// returned) or to the closing backtick (a whole template or its tail). `first` is
+ /// whether the part starts the template literal.
+ fn scan_template_literal_part(&mut self, start: u32, first: bool) -> Token<'a> {
+ let mut buffer = CookedText::default();
+ let mut marker = self.index;
+ while self.peek() != chars::BT {
+ if self.peek() == chars::BACKSLASH {
+ if let Err(error) = self.scan_string_backslash(&mut buffer, marker) {
+ return error;
}
- }
- chars::GT => {
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, ">=");
- } else {
- self.scan_operator(start, ">");
- }
- }
- chars::BANG => {
- if self.peek() == chars::EQ {
- self.advance();
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "!==");
- } else {
- self.scan_operator(start, "!=");
- }
- } else {
- self.scan_operator(start, "!");
- }
- }
- chars::EQ => {
- if self.peek() == chars::EQ {
- self.advance();
- if self.peek() == chars::EQ {
- self.advance();
- self.scan_operator(start, "===");
+ marker = self.index;
+ } else if self.peek() == chars::DOLLAR {
+ let dollar = self.index;
+ self.advance();
+ if self.peek() == chars::LBRACE {
+ self.brace_stack.push(Brace::Interpolation);
+ let text = buffer.finish(&self.input[marker as usize..dollar as usize]);
+ let part = if first {
+ Token::new_template_head(start, dollar, &text, self.allocator)
} else {
- self.scan_operator(start, "==");
- }
- } else {
- self.scan_character(start, ch);
- }
- }
- chars::AMPERSAND => {
- if self.peek() == chars::AMPERSAND {
- self.advance();
- self.scan_operator(start, "&&");
- } else {
- self.scan_operator(start, "&");
- }
- }
- chars::BAR => {
- if self.peek() == chars::BAR {
+ Token::new_template_middle(start, dollar, &text, self.allocator)
+ };
+ self.tokens.push(part);
self.advance();
- self.scan_operator(start, "||");
- } else {
- self.scan_operator(start, "|");
+ return Token::new_operator(dollar, self.index, "${", self.allocator);
}
+ } else if self.peek() == chars::EOF {
+ return self.error("Unterminated template literal", 0);
+ } else {
+ self.advance();
}
- // Single characters
- _ => {
- self.scan_character(start, ch);
- }
- }
- }
-
- /// Scans an escape sequence and returns the escaped character.
- /// Used for template literals where we don't need error recovery.
- fn scan_escape_sequence(&mut self) -> char {
- // For template literals, we don't do error recovery - just return the best effort
- match self.scan_escape_sequence_with_error(self.index - 1) {
- Ok(ch) => ch,
- Err(_) => '\u{FFFD}',
}
- }
-
- /// Scans an escape sequence with proper error handling.
- /// Returns Ok(char) on success, or Err((index, end, message)) on error.
- fn scan_escape_sequence_with_error(
- &mut self,
- escape_start: u32,
- ) -> Result {
- let ch = self.advance();
- match ch {
- 'n' => Ok('\n'),
- 'r' => Ok('\r'),
- 't' => Ok('\t'),
- 'b' => Ok('\u{0008}'),
- 'f' => Ok('\u{000C}'),
- 'v' => Ok('\u{000B}'),
- '0' => Ok('\0'),
- 'x' => self.scan_hex_escape_with_error(2, escape_start),
- 'u' => {
- if self.peek() == chars::LBRACE {
- self.advance();
- let result = self.scan_unicode_escape_with_error(escape_start);
- if self.peek() == chars::RBRACE {
- self.advance();
- }
- result
- } else {
- self.scan_hex_escape_with_error(4, escape_start)
- }
- }
- _ => Ok(ch),
+ let text = buffer.finish(&self.input[marker as usize..self.index as usize]);
+ self.advance();
+ if first {
+ Token::new_no_substitution_template(start, self.index, &text, self.allocator)
+ } else {
+ Token::new_template_tail(start, self.index, &text, self.allocator)
}
}
- /// Scans a hex escape sequence of the given length with error handling.
- fn scan_hex_escape_with_error(
+ /// Angular's `scanStringBackslash`: adds the text since `marker` and the escape at the
+ /// current position to `buffer`. `\u` takes the four code units after it, which must be
+ /// hexadecimal digits (fewer at the end of the input); else it is an error.
+ fn scan_string_backslash(
&mut self,
- len: u32,
- escape_start: u32,
- ) -> Result {
- let mut value = 0u32;
- let mut count = 0u32;
-
- for _ in 0..len {
+ buffer: &mut CookedText,
+ marker: u32,
+ ) -> Result<(), Token<'a>> {
+ buffer.push_str(&self.input[marker as usize..self.index as usize]);
+ self.advance();
+ if self.peek() != 'u' {
let ch = self.peek();
- if let Some(digit) = ch.to_digit(16) {
- value = value * 16 + digit;
- self.advance();
- count += 1;
- } else {
- break;
- }
+ self.advance();
+ buffer.push_char(unescape(ch));
+ return Ok(());
}
- if count < len {
- // Build the invalid escape sequence for the error message
- // Read ahead to find what the invalid sequence looks like
- let mut invalid_seq = String::new();
- invalid_seq.push_str(&self.input[escape_start as usize..self.index as usize]);
- // Continue reading non-hex chars to show in the error (like Angular does)
- let mut ahead = 0u32;
- while ahead < (len - count) && !self.is_eof() {
- let next = self.peek_at(ahead);
- if next == chars::EOF {
- break;
- }
- invalid_seq.push(next);
- ahead += 1;
+ // Angular's `input.substring(index + 1, index + 5)`: four UTF-16 code units (half
+ // of a surrogate pair shows as U+FFFD).
+ let rest = self.input.get(self.index as usize + 1..).unwrap_or_default();
+ let mut hex = String::new();
+ let mut units = 0;
+ let mut all_hex = true;
+ for ch in rest.chars() {
+ if units >= 4 {
+ break;
}
-
- let error_index = escape_start + 1; // Position of the 'u' in \u
- let message = format!(
- "Lexer Error: Invalid unicode escape [{}] at column {} in expression [{}]",
- invalid_seq, error_index, self.input
- );
- return Err((error_index, error_index, message));
+ units += ch.len_utf16();
+ all_hex &= ch.is_ascii_hexdigit();
+ hex.push(if units > 4 { char::REPLACEMENT_CHARACTER } else { ch });
}
-
- Ok(char::from_u32(value).unwrap_or('\u{FFFD}'))
- }
-
- /// Scans a unicode escape sequence (for \u{...} syntax).
- fn scan_unicode_escape_with_error(
- &mut self,
- escape_start: u32,
- ) -> Result {
- let mut value = 0u32;
- let mut count = 0;
-
- while chars::is_ascii_hex_digit(self.peek()) {
- let ch = self.advance();
- if let Some(digit) = ch.to_digit(16) {
- value = value * 16 + digit;
- count += 1;
- }
+ if hex.is_empty() || !all_hex {
+ return Err(self.error(&format!("Invalid unicode escape [\\u{hex}]"), 0));
}
-
- if count == 0 {
- let error_index = escape_start + 1;
- let invalid_seq = &self.input[escape_start as usize..self.index as usize];
- let message = format!(
- "Lexer Error: Invalid unicode escape [{}] at column {} in expression [{}]",
- invalid_seq, error_index, self.input
- );
- return Err((error_index, error_index, message));
+ let unit = u16::from_str_radix(&hex, 16).unwrap_or(0);
+ for _ in 0..5 {
+ self.advance();
}
-
- Ok(char::from_u32(value).unwrap_or('\u{FFFD}'))
+ buffer.push_code_unit(unit);
+ Ok(())
}
- /// Records an error with the current position as the end.
- fn error(&mut self, start: u32, message: &str) {
- let token = Token::new_error(start, self.index, message, &self.allocator);
- self.tokens.push(token);
+ /// Angular's `error`: an error token at `offset` from the current position, with
+ /// Angular's message.
+ fn error(&self, message: &str, offset: i32) -> Token<'a> {
+ let utf16 = self.utf16.saturating_add_signed(offset);
+ let index = self.index.saturating_add_signed(offset).min(self.length);
+ let message = self.error_message(message, utf16);
+ self.error_token(index, self.index, utf16, &message)
}
- /// Records an error at specific index and end positions.
- fn error_at(&mut self, index: u32, end: u32, message: &str) {
- let token = Token::new_error(index, end, message, &self.allocator);
- self.tokens.push(token);
+ /// Angular's lexer error message for an error at UTF-16 index `column`.
+ fn error_message(&self, message: &str, column: u32) -> String {
+ format!("Lexer Error: {message} at column {column} in expression [{}]", self.input)
}
- /// Scans a regex literal starting from the current position.
- /// Assumes the opening `/` has already been consumed.
- ///
- /// Returns true if a valid regex was found, false otherwise.
- pub fn scan_regex(&mut self, start: u32) -> bool {
- let mut in_class = false;
- let mut pattern = String::new();
+ /// An error token, whose `num_value` is its UTF-16 index (Angular's token index).
+ fn error_token(&self, index: u32, end: u32, utf16: u32, message: &str) -> Token<'a> {
+ let mut token = Token::new_error(index, end, message, self.allocator);
+ token.num_value = f64::from(utf16);
+ token
+ }
- // Scan the regex body
+ /// Angular's `isStartOfRegex`: whether a `/` here starts a regular expression rather
+ /// than a division, from the token before it.
+ fn is_start_of_regex(&self) -> bool {
+ let Some(prev) = self.tokens.last() else {
+ return true;
+ };
+ if prev.is_operator("!") {
+ // A `!` after a value is a non-null assertion; else it is a negation.
+ let before = self.tokens.len().checked_sub(2).map(|i| &self.tokens[i]);
+ return before.is_none_or(|before| {
+ before.token_type != TokenType::Identifier
+ && !before.is_character(')')
+ && !before.is_character(']')
+ });
+ }
+ // A lone `?` is an operator in Angular.
+ prev.token_type == TokenType::Operator
+ || prev.is_character('?')
+ || prev.is_character('(')
+ || prev.is_character('[')
+ || prev.is_character(',')
+ || prev.is_character(':')
+ }
+
+ /// Angular's `scanRegex`: the body of a regular expression, and its flags (any ASCII
+ /// letters, which the parser checks) as a second token.
+ fn scan_regex(&mut self, token_start: u32) -> Token<'a> {
+ self.advance();
+ let text_start = self.index;
+ let mut in_escape = false;
+ let mut in_character_class = false;
loop {
let ch = self.peek();
-
- if ch == chars::EOF || ch == '\n' || ch == '\r' {
- // Error at the end of input where we expected more
- let error_pos = self.index;
- let message = format!(
- "Lexer Error: Unterminated regular expression at column {} in expression [{}]",
- error_pos, self.input
- );
- self.error_at(error_pos, error_pos, &message);
- return false;
+ // Angular stops only at the end of the input, and then emits a regex with a
+ // line break in it, which is not valid JavaScript. We keep the error we gave
+ // before for a line terminator (also after a backslash or inside `[...]`).
+ if ch == chars::EOF || matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}') {
+ return self.error("Unterminated regular expression", 0);
}
-
- if in_class {
- // Inside character class [...]
- if ch == ']' {
- in_class = false;
- pattern.push(self.advance());
- } else if ch == chars::BACKSLASH {
- pattern.push(self.advance());
- if !self.is_eof() {
- pattern.push(self.advance());
- }
- } else {
- pattern.push(self.advance());
- }
- } else {
- // Outside character class
- if ch == '/' {
- self.advance(); // consume closing /
- break;
- } else if ch == '[' {
- in_class = true;
- pattern.push(self.advance());
- } else if ch == chars::BACKSLASH {
- pattern.push(self.advance());
- if !self.is_eof() {
- pattern.push(self.advance());
- }
- } else {
- pattern.push(self.advance());
- }
+ if in_escape {
+ in_escape = false;
+ } else if ch == chars::BACKSLASH {
+ in_escape = true;
+ } else if ch == '[' {
+ in_character_class = true;
+ } else if ch == ']' {
+ in_character_class = false;
+ } else if ch == chars::SLASH && !in_character_class {
+ break;
}
- }
-
- // The body ends at the closing / (which we already advanced past)
- let body_end = self.index;
-
- // Create the body token (just the pattern, not including slashes)
- let body_token = Token::new_regexp_body(start, body_end, &pattern, &self.allocator);
- self.tokens.push(body_token);
-
- // Scan flags
- let flags_start = self.index;
- while self.is_regex_flag(self.peek()) {
self.advance();
}
-
- // Only create flags token if there are flags
- if self.index > flags_start {
- let flags = &self.input[flags_start as usize..self.index as usize];
- let flags_token =
- Token::new_regexp_flags(flags_start, self.index, flags, &self.allocator);
- self.tokens.push(flags_token);
-
- // Validate flags (this reports errors but doesn't prevent token creation)
- self.validate_regex_flags(flags, flags_start);
- }
-
- true
- }
-
- /// Returns true if the character could be a regex flag (any ASCII letter).
- /// Validation of actual flag values is done in validate_regex_flags.
- fn is_regex_flag(&self, ch: char) -> bool {
- ch.is_ascii_alphabetic()
- }
-
- /// Validates regex flags and reports errors for duplicates or invalid combinations.
- fn validate_regex_flags(&mut self, flags: &str, start: u32) -> bool {
- let mut seen = [false; 8];
-
- for ch in flags.chars() {
- let idx = match ch {
- 'd' => 0,
- 'g' => 1,
- 'i' => 2,
- 'm' => 3,
- 's' => 4,
- 'u' => 5,
- 'v' => 6,
- 'y' => 7,
- _ => {
- self.error(start, &format!("Unsupported regular expression flag \"{ch}\""));
- return false;
- }
- };
-
- if seen[idx] {
- self.error(start, &format!("Duplicate regular expression flag \"{ch}\""));
- return false;
- }
- seen[idx] = true;
- }
-
- // Check for invalid flag combinations
- // 'u' and 'v' are mutually exclusive
- if seen[5] && seen[6] {
- self.error(start, "Regular expression flags 'u' and 'v' cannot be used together");
- return false;
+ let body = &self.input[text_start as usize..self.index as usize];
+ self.advance();
+ let body = Token::new_regexp_body(token_start, self.index, body, self.allocator);
+ if !self.peek().is_ascii_alphabetic() {
+ return body;
}
-
- true
- }
-
- /// Checks if the last token suggests that `/` should be interpreted as regex start.
- /// This is used to disambiguate between division and regex.
- pub fn last_token_allows_regex(&self) -> bool {
- if let Some(last) = self.tokens.last() {
- match last.token_type {
- // After these operators, `/` is more likely to be regex
- TokenType::Operator => {
- let op = last.str_value.as_str();
- // `!` can be non-null assertion (postfix) or negation (prefix)
- // Check the token before `!` to determine:
- // - If preceded by value-like token (identifier, ), ], keyword), it's non-null assertion
- // - Otherwise, it's negation and `/` is regex
- if op == "!" {
- if self.tokens.len() >= 2 {
- let before_bang = &self.tokens[self.tokens.len() - 2];
- return match before_bang.token_type {
- TokenType::Identifier
- | TokenType::PrivateIdentifier
- | TokenType::Number
- | TokenType::String => false, // non-null assertion, division
- TokenType::Character => {
- let ch = before_bang.num_value as u32;
- // After ) or ], `!` is non-null assertion
- if matches!(char::from_u32(ch), Some(')' | ']')) {
- false // non-null assertion, division
- } else {
- true // negation, regex
- }
- }
- TokenType::Keyword => false, // non-null assertion
- _ => true, // negation, regex
- };
- }
- // `!` at start of expression is negation
- return true;
- }
- // After other operators like =, +, -, *, etc., `/` is regex
- true
- }
- TokenType::Character => {
- // After (, [, {, ,, :, ;, etc.
- let ch = last.num_value as u32;
- matches!(char::from_u32(ch), Some('(' | '[' | '{' | ',' | ':' | ';'))
- }
- TokenType::Keyword => {
- // After keywords like return, typeof, void, in, etc.
- let kw = last.str_value.as_str();
- matches!(kw, "return" | "typeof" | "void" | "in" | "else" | "if" | "case")
- }
- _ => false,
- }
- } else {
- // At start of expression, `/` is regex
- true
+ self.tokens.push(body);
+ let flags_start = self.index;
+ while self.peek().is_ascii_alphabetic() {
+ self.advance();
}
+ let flags = &self.input[flags_start as usize..self.index as usize];
+ Token::new_regexp_flags(flags_start, self.index, flags, self.allocator)
}
}
@@ -1586,7 +1144,7 @@ mod tests {
#[test]
fn test_numbers() {
let allocator = Allocator::default();
- let lexer = Lexer::new(&allocator, "42 3.14 0xff");
+ let lexer = Lexer::new(&allocator, "42 3.14 1e3");
let tokens = lexer.tokenize();
assert_eq!(tokens.len(), 3);
assert!(tokens[0].is_number());
@@ -1594,7 +1152,7 @@ mod tests {
assert!(tokens[1].is_number());
assert_eq!(tokens[1].num_value, 3.14);
assert!(tokens[2].is_number());
- assert_eq!(tokens[2].num_value, 255.0);
+ assert_eq!(tokens[2].num_value, 1000.0);
}
#[test]
diff --git a/crates/oxc_angular_compiler/src/parser/expression/parser.rs b/crates/oxc_angular_compiler/src/parser/expression/parser.rs
index 41cac1907..786ddfad5 100644
--- a/crates/oxc_angular_compiler/src/parser/expression/parser.rs
+++ b/crates/oxc_angular_compiler/src/parser/expression/parser.rs
@@ -22,6 +22,7 @@ use crate::util::ParseError;
use super::lexer::{Lexer, Token};
use super::{TemplateBindingParseResult, is_comment_only, strip_comments};
+use crate::parser::{MAX_CALL_STACK_ERROR, depth_limit_reached, depth_limits};
/// Angular's error for an interpolation with a blank expression (`{{ }}`), raised by
/// `splitInterpolation`; `column` is the offset of the `{{` in `input`.
@@ -132,6 +133,14 @@ pub struct Parser<'a> {
/// For `parse_interpolation`: parse as Angular does without interpolation tokens,
/// so the expressions' errors print the whole input.
without_tokens: bool,
+ /// How deep an expression may nest: `MAX_EXPRESSION_DEPTH`, or the lower limit
+ /// of `with_depth_limits`.
+ max_depth: usize,
+ /// How many levels `nested` has entered: the parser's own recursion depth.
+ nesting: usize,
+ /// Set when the expression nests deeper than `max_depth`: the rest of the input
+ /// is skipped and the parse reports only `MAX_CALL_STACK_ERROR`.
+ too_deep: bool,
}
impl<'a> Parser<'a> {
@@ -139,23 +148,16 @@ impl<'a> Parser<'a> {
pub fn new(allocator: &'a Allocator, source: &'a str) -> Self {
// Strip comments from the source before tokenizing. The stripped source is a prefix
// of `source`, so it is borrowed rather than copied.
+ // The lexer's errors are error tokens, reported when the parser reaches them.
let lexer = Lexer::new(allocator, strip_comments(source).stripped);
let tokens = lexer.tokenize();
- // Collect error tokens from the lexer
- let mut errors = std::vec::Vec::new();
- for token in &tokens {
- if token.is_error() {
- errors.push(ParseError::new(Default::default(), token.str_value.to_string()));
- }
- }
-
Self {
allocator,
tokens,
index: 0,
source,
- errors,
+ errors: std::vec::Vec::new(),
absolute_offset: 0,
rparens_expected: 0,
rbrackets_expected: 0,
@@ -166,6 +168,9 @@ impl<'a> Parser<'a> {
interpolation_offset: 0,
error_input: None,
without_tokens: false,
+ max_depth: depth_limits().expression,
+ nesting: 0,
+ too_deep: false,
}
}
@@ -198,6 +203,9 @@ impl<'a> Parser<'a> {
interpolation_offset: 0,
error_input: None,
without_tokens: false,
+ max_depth: depth_limits().expression,
+ nesting: 0,
+ too_deep: false,
}
}
@@ -298,16 +306,45 @@ impl<'a> Parser<'a> {
self.check_no_interpolation();
// Angular parses a binding as a chain too, and reports each `;`.
let ast = self.parse_chain();
- ParseResult { ast, errors: self.errors }
+ self.finish(ast)
}
/// Parses an expression as Angular's `parseInterpolationExpression` (an ICU's switch
/// value): a chain, with no check for `{{ }}` in it.
pub fn parse_interpolation_expression(mut self) -> ParseResult<'a> {
let ast = self.parse_chain();
+ self.finish(ast)
+ }
+
+ /// The result of a parse: the expression and its errors, or, for an expression
+ /// nested deeper than `max_depth`, the result of Angular's binding
+ /// parser for a parse that overflows the stack: an `'ERROR'` literal and only
+ /// `MAX_CALL_STACK_ERROR`, at the binding.
+ fn finish(self, ast: AngularExpression<'a>) -> ParseResult<'a> {
+ if self.too_deep || self.depth_exceeds_limit(&ast) {
+ return self.too_deep_result();
+ }
ParseResult { ast, errors: self.errors }
}
+ /// Whether `ast` nests deeper than `max_depth`. Every node with children
+ /// consumes a token of its own, so an expression of few tokens is not walked.
+ fn depth_exceeds_limit(&self, ast: &AngularExpression<'a>) -> bool {
+ let exceeds =
+ self.tokens.len() * 2 + 2 > self.max_depth && ast.depth_exceeds(self.max_depth);
+ if exceeds {
+ depth_limit_reached();
+ }
+ exceeds
+ }
+
+ /// See `finish`.
+ fn too_deep_result(&self) -> ParseResult<'a> {
+ let ast = self.wrap_literal_primitive(Some("ERROR"), "", self.absolute_offset).ast;
+ let error = ParseError::new(crate::util::ParseSourceSpan::default(), MAX_CALL_STACK_ERROR);
+ ParseResult { ast, errors: vec![error] }
+ }
+
/// Sets Angular's `offset` of an interpolation's expression (the UTF-16 index just
/// past its `{{` in the template text), which the "Expected identifier for property
/// access" location adds to a span end.
@@ -326,7 +363,7 @@ impl<'a> Parser<'a> {
self.check_no_interpolation();
self.action_mode = true;
let ast = self.parse_chain();
- ParseResult { ast, errors: self.errors }
+ self.finish(ast)
}
/// Wraps a literal primitive value in an AST.
@@ -628,6 +665,20 @@ impl<'a> Parser<'a> {
}
}
+ // Angular's binding parser keeps no binding of a parse that overflows the stack.
+ let too_deep = self.too_deep
+ || bindings.iter().any(|binding| match binding {
+ TemplateBinding::Expression(ExpressionBinding { value: Some(value), .. }) => {
+ self.depth_exceeds_limit(&value.ast)
+ }
+ _ => false,
+ });
+ if too_deep {
+ bindings.clear();
+ errors.push(MAX_CALL_STACK_ERROR.to_string());
+ return TemplateBindingParseResult { bindings, errors, warnings };
+ }
+
// Collect any parse errors
for err in &self.errors {
errors.push(err.msg.clone());
@@ -877,7 +928,7 @@ impl<'a> Parser<'a> {
/// the first `end_delimiter` outside quotes, or, after an unquoted `//`, the next
/// `end_delimiter` anywhere. A quote preceded by an odd number of backslashes does not
/// open or close a string (`_forEachUnquotedChar`). Returns a byte index into `input`.
- fn find_interpolation_end(input: &str, end_delimiter: &str) -> Option {
+ pub(crate) fn find_interpolation_end(input: &str, end_delimiter: &str) -> Option {
let bytes = input.as_bytes();
let mut quote: Option = None;
let mut escapes = 0usize;
@@ -970,14 +1021,20 @@ impl<'a> Parser<'a> {
);
// Counted on from the previous interpolation, not from the start
// of the text, so many interpolations stay linear.
- utf16_cursor.1 +=
- self.source[utf16_cursor.0..expr_start].encode_utf16().count();
+ utf16_cursor.1 += crate::util::lone_surrogate::utf16_len(
+ &self.source[utf16_cursor.0..expr_start],
+ );
utf16_cursor.0 = expr_start;
expr_parser.interpolation_offset = utf16_cursor.1;
if self.without_tokens {
expr_parser.error_input = Some(self.source);
}
let result = expr_parser.parse_simple_binding();
+ // Angular reports a parse that overflows the stack at the whole
+ // text, with none of the text's other errors.
+ if result.errors.len() == 1 && result.errors[0].msg == MAX_CALL_STACK_ERROR {
+ return Some(self.too_deep_result());
+ }
// With the interpolation's span known, its errors are placed
// there: only the offsets, as the error has no file to point into.
let mut errors = result.errors;
@@ -1170,18 +1227,34 @@ impl<'a> Parser<'a> {
/// UTF-16 code units as in JavaScript, or the end of the expression.
fn location_text(&self, token_index: usize) -> String {
match self.tokens.get(token_index) {
- Some(token) => format!("at column {} in", self.utf16_index(token.index as usize) + 1),
+ Some(token) => format!("at column {} in", self.token_utf16_index(token) + 1),
None => "at the end of the expression".to_string(),
}
}
+ /// Angular's `index` of a token: the UTF-16 index where it starts. A lexer error
+ /// token carries its own (Angular's position of the error).
+ fn token_utf16_index(&self, token: &Token<'_>) -> usize {
+ if token.is_error() { token.error_column() } else { self.utf16_index(token.index as usize) }
+ }
+
+ /// Reports the lexer error token at `token_index`, as Angular does when its parser
+ /// reaches one; `location` is the token index Angular takes the location from.
+ fn push_lexer_error(&mut self, token_index: usize, location: usize) {
+ if let Some(token) = self.tokens.get(token_index) {
+ let message = token.str_value.to_string();
+ self.push_error_at_token(&message, location);
+ }
+ }
+
/// The UTF-16 index of the byte offset `byte` in the source, clamped to the source.
+ /// A stored lone surrogate (`util::lone_surrogate`) is the one unit it stands for.
fn utf16_index(&self, byte: usize) -> usize {
let mut end = byte.min(self.source.len());
while !self.source.is_char_boundary(end) {
end -= 1;
}
- self.source[..end].encode_utf16().count()
+ crate::util::lone_surrogate::utf16_len(&self.source[..end])
}
/// `source[start..end]` with JavaScript `substring` rules (the bounds swap when
@@ -1210,14 +1283,9 @@ impl<'a> Parser<'a> {
self.peek().map_or_else(|| self.current_end_index(), |t| t.index)
}
- /// The text Angular's `Token.toString()` gives for a token in a message: a
- /// number's JavaScript value (`1.50` -> `1.5`), else the token's string value.
+ /// The text of a token in a message ([`Token::message_text`]).
fn token_text(token: &Token<'_>) -> String {
- if token.is_number() {
- crate::output::emitter::format_number_like_js(token.num_value)
- } else {
- token.str_value.to_string()
- }
+ token.message_text()
}
/// The text of the current token for a message (`''` at the end, as Angular's EOF).
@@ -1315,6 +1383,13 @@ impl<'a> Parser<'a> {
break;
}
+ // Angular reports a lexer error it skips, located by a quirk at the token
+ // whose index is the error's column.
+ if let Some(token) = self.peek().filter(|token| token.is_error()) {
+ let location = token.error_column();
+ self.push_lexer_error(self.index, location);
+ }
+
self.advance();
}
}
@@ -1424,9 +1499,10 @@ impl<'a> Parser<'a> {
let condition = self.parse_logical_or();
if self.optional_character('?') {
- let true_exp = self.parse_pipe();
+ // The branches nest in the conditional, and a branch can be one itself.
+ let true_exp = self.nested(Self::parse_pipe);
let false_exp = if self.optional_character(':') {
- self.parse_pipe()
+ self.nested(Self::parse_pipe)
} else {
// Missing colon - emit error with the expression so far
let end = self.input_index();
@@ -1673,7 +1749,7 @@ impl<'a> Parser<'a> {
}
// Right-associative: recursively parse the right side
- let right = self.parse_exponentiation();
+ let right = self.nested(Self::parse_exponentiation);
let end = self.current_end_index();
let span = ParseSpan::new(start, end);
let source_span = span.to_absolute(self.absolute_offset);
@@ -1685,8 +1761,36 @@ impl<'a> Parser<'a> {
result
}
- /// Parses prefix expressions.
+ /// Parses prefix expressions. Every operand is parsed through here.
fn parse_prefix(&mut self) -> AngularExpression<'a> {
+ self.nested(Self::parse_prefix_operand)
+ }
+
+ /// Parses with `parse` an expression one level deeper in the tree. Every cycle of
+ /// the parser's recursion goes through here (an operand, a conditional's branch,
+ /// the right side of `**`), so this bounds the recursion: past `max_depth`, the
+ /// rest of the input is skipped. Each level entered is a node of the tree, so an
+ /// expression within `max_depth` is never cut.
+ fn nested(&mut self, parse: fn(&mut Self) -> AngularExpression<'a>) -> AngularExpression<'a> {
+ if self.nesting >= self.max_depth {
+ depth_limit_reached();
+ self.too_deep = true;
+ self.index = self.tokens.len();
+ let end = self.current_end_index();
+ let span = ParseSpan::new(end, end);
+ let source_span = span.to_absolute(self.absolute_offset);
+ return AngularExpression::Empty(Box::new_in(
+ EmptyExpr { span, source_span },
+ &self.allocator,
+ ));
+ }
+ self.nesting += 1;
+ let expr = parse(self);
+ self.nesting -= 1;
+ expr
+ }
+
+ fn parse_prefix_operand(&mut self) -> AngularExpression<'a> {
let start = self.peek().map(|t| t.index).unwrap_or(0);
if let Some(operator) = self.peek_update_operator() {
@@ -2624,10 +2728,12 @@ impl<'a> Parser<'a> {
self.expect_character('}');
self.rbraces_expected -= 1;
- // Skip ahead to the next template part, as Angular does after an error
- // (lexer error tokens were reported when the parser was created).
+ // Skip ahead to the next template part, as Angular does after an error,
+ // reporting the lexer errors on the way.
while let Some(token) = self.peek().cloned() {
- if token.is_template_middle() || token.is_template_tail() {
+ if token.is_error() {
+ self.push_lexer_error(self.index, self.index);
+ } else if token.is_template_middle() || token.is_template_tail() {
self.advance();
let part_span = ParseSpan::new(token.index, token.end);
let part_source_span = part_span.to_absolute(self.absolute_offset);
@@ -2705,12 +2811,11 @@ impl<'a> Parser<'a> {
self.advance();
// Check for optional flags token
- let (flags, end) = match self.peek() {
+ let (flags, end) = match self.peek().cloned() {
Some(t) if t.is_regexp_flags() => {
- let flags_str = t.str_value.clone();
- let flags_end = t.end;
self.advance();
- (Some(flags_str), flags_end)
+ self.check_regex_flags(&t);
+ (Some(t.str_value), t.end)
}
_ => (None, token.end),
};
@@ -2722,6 +2827,38 @@ impl<'a> Parser<'a> {
AngularExpression::RegularExpressionLiteral(Box::new_in(regex, &self.allocator))
}
+ /// Angular's checks of a regular expression's flags (in `parseRegularExpressionLiteral`):
+ /// each error is located, by a quirk, at the token whose index is the flag's column.
+ fn check_regex_flags(&mut self, flags: &Token<'a>) {
+ let start = self.token_utf16_index(flags);
+ let mut seen = std::vec::Vec::new();
+ for (i, flag) in flags.str_value.chars().enumerate() {
+ if !matches!(flag, 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'v' | 'y') {
+ self.error_at_token(
+ &format!(
+ "Unsupported regular expression flag \"{flag}\". The supported flags are: \"d\", \"g\", \"i\", \"m\", \"s\", \"u\", \"v\", \"y\""
+ ),
+ start + i,
+ );
+ } else if seen.contains(&flag) {
+ self.error_at_token(
+ &format!("Duplicate regular expression flag \"{flag}\""),
+ start + i,
+ );
+ } else {
+ seen.push(flag);
+ }
+ }
+ // Not an error in Angular's parser, so it skips nothing; it is located at the flags
+ // (the token before the current one).
+ if seen.contains(&'u') && seen.contains(&'v') {
+ self.push_error_at_token(
+ "Regular expression flags 'u' and 'v' cannot be used together",
+ self.index.saturating_sub(1),
+ );
+ }
+ }
+
/// Parses an object literal.
/// Note: The opening `{` was already consumed before calling this.
fn parse_object_literal(&mut self, start: u32) -> AngularExpression<'a> {
diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs
index acaa9bed5..a3611e51c 100644
--- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs
+++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs
@@ -23,8 +23,21 @@ const SUPPORTED_BLOCKS: &[&str] = &[
"loading",
"boundary",
"error",
+ // Lexed as Angular does; the parser has no `@content` block yet, so it is an
+ // unknown block ("Unrecognized block @content.").
+ "content",
];
+/// An entity error, with the cursor position (index, line, column) Angular's
+/// cursor has after it.
+#[derive(Debug, Clone, Copy)]
+enum EntityError {
+ /// `Unknown entity` / `Unable to parse entity`, a `ParseError`.
+ At(u32, u32, u32),
+ /// The input ended inside the entity, a `CursorError`.
+ Eof(u32, u32, u32),
+}
+
/// Token types for HTML templates.
/// Matches Angular's `TokenType` enum from `ml_parser/tokens.ts`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -67,6 +80,8 @@ pub enum HtmlTokenType {
AttrValueInterpolation,
/// DOCTYPE
DocType,
+ /// A processing instruction (``), which the parser skips.
+ ProcessingInstruction,
/// Expansion form start: `{`
ExpansionFormStart,
/// Expansion case value
@@ -545,6 +560,8 @@ pub struct HtmlTokenError {
/// The byte offset where the error occurred. `position` is a `(line, column)`
/// pair, which the parser must not read as a source span.
pub offset: u32,
+ /// The byte offset where the error's span ends (`offset` for an empty span).
+ pub end: u32,
}
/// HTML template lexer.
@@ -576,6 +593,13 @@ pub struct HtmlLexer<'a> {
/// Stack to track expansion form/case nesting.
/// Values are HtmlTokenType::ExpansionFormStart or HtmlTokenType::ExpansionCaseExpStart.
expansion_case_stack: Vec,
+ /// Set when a quoted attribute value runs to the end of the input. Angular's
+ /// cursor then throws out of `_consumeTagOpen` without marking the tag as
+ /// incomplete, so the start tag is left as it is. Also set (with the tag
+ /// marked incomplete) when an entity in an attribute value has an error.
+ attr_value_unterminated: bool,
+ /// The error of the last `scan_entity` call, if any.
+ entity_error: Option,
/// Enable escape sequence processing (for inline template strings).
escaped_string: bool,
/// Enable block tokenization (default: true).
@@ -614,6 +638,8 @@ impl<'a> HtmlLexer<'a> {
selectorless_enabled: false,
tokenize_icu: false,
expansion_case_stack: Vec::new(),
+ attr_value_unterminated: false,
+ entity_error: None,
escaped_string: false,
tokenize_blocks: true, // default to true like Angular
tokenize_let: true, // default to true like Angular
@@ -729,16 +755,6 @@ impl<'a> HtmlLexer<'a> {
self.scan_token();
}
- // If we hit EOF while still in an expansion form, report an unescaped `{` error
- // (only when ICU tokenization is enabled)
- if self.tokenize_icu && !self.expansion_case_stack.is_empty() {
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\" (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
- }
-
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)
@@ -796,12 +812,9 @@ impl<'a> HtmlLexer<'a> {
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 }),
- );
+ self.errors.extend(errors_to_add.into_iter().zip(positions).map(
+ |((msg, offset), position)| HtmlTokenError { msg, position, offset, end: offset },
+ ));
}
HtmlTokenizeResult { tokens, errors: self.errors }
@@ -1041,42 +1054,40 @@ impl<'a> HtmlLexer<'a> {
self.input[self.index as usize..].starts_with(s)
}
+ /// Angular's `_unexpectedCharacterErrorMsg` for the character at the cursor.
+ fn unexpected_character_message(&self) -> String {
+ if self.index >= self.length || self.peek() == chars::EOF {
+ "Unexpected character \"EOF\"".to_string()
+ } else {
+ format!("Unexpected character \"{}\"", self.peek())
+ }
+ }
+
/// Reports an error at the current position.
fn error(&mut self, msg: &str) {
- self.errors.push(HtmlTokenError {
- msg: msg.to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
+ self.push_error(msg.to_string(), (self.line, self.column), self.index, self.index);
+ }
+
+ /// Reports an error. As Angular's `_createError`, an error inside an expansion
+ /// 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.)",
+ );
+ }
+ self.errors.push(HtmlTokenError { msg, position, offset, end });
}
/// Checks if the current position is the start of a supported block.
/// A block starts with `@` followed by a supported block keyword.
fn is_block_start(&self) -> bool {
- if self.peek() != '@' {
- return false;
- }
- // Check if followed by a supported block keyword
- for &block_name in SUPPORTED_BLOCKS {
- let check_str = format!("@{block_name}");
- if self.starts_with(&check_str) {
- // Make sure the block name is not followed by an identifier char
- // (e.g., "@iffy" should not match "@if"). Deliberate divergence
- // from upstream `_isBlockStart`, which is a pure `_peekStr`
- // prefix match: there `@ifx`/`@else5` lex as
- // IncompleteBlockOpen ("Incomplete block \"ifx\"") instead of
- // staying plain text.
- let next_char_index = self.index as usize + check_str.len();
- if next_char_index >= self.input.len() {
- return true; // At end of input, it's a match
- }
- let next_char = self.input[next_char_index..].chars().next().unwrap_or(chars::EOF);
- if !chars::is_identifier_part(next_char) || chars::is_whitespace(next_char) {
- return true;
- }
- }
- }
- false
+ // A plain prefix match, as Angular's `_isBlockStart` (`_peekStr`): `@iffy`
+ // starts a block named `iffy`, which the parser reports as incomplete.
+ self.peek() == '@'
+ && SUPPORTED_BLOCKS
+ .iter()
+ .any(|name| name.chars().zip(1..).all(|(ch, i)| self.peek_at(i) == ch))
}
/// Scans a single token.
@@ -1170,6 +1181,7 @@ impl<'a> HtmlLexer<'a> {
// An underscore starts a name only for a selectorless component.
if next == '/'
|| next == '!'
+ || next == '?'
|| next.is_ascii_alphabetic()
|| (next == '_' && self.selectorless_enabled)
{
@@ -1259,7 +1271,10 @@ impl<'a> HtmlLexer<'a> {
let mut params_unclosed = false;
if self.peek() == '(' {
self.advance(); // consume (
- self.scan_block_parameters();
+ if !self.scan_block_parameters() {
+ // As Angular, the block start stays a block start without parameters.
+ return;
+ }
// Skip whitespace after parameters
self.skip_whitespace();
// Expect )
@@ -1457,9 +1472,17 @@ impl<'a> HtmlLexer<'a> {
self.advance();
}
- // Check for unclosed quotes - report error
+ // An unclosed quote: Angular's cursor throws at the end of the input, which
+ // drops the value and leaves the start token as it is.
if in_quote.is_some() {
self.error("Unexpected character \"EOF\"");
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::LetStart,
+ &var_name,
+ start,
+ name_end,
+ ));
+ return;
}
let value_end = self.index;
@@ -1502,95 +1525,74 @@ impl<'a> HtmlLexer<'a> {
}
}
- /// Scans block parameters inside `(...)`.
- fn scan_block_parameters(&mut self) {
- self.skip_whitespace();
-
- while self.peek() != ')' && self.peek() != chars::EOF {
+ /// Scans block parameters inside `(...)`, as Angular's `_consumeBlockParameters`.
+ ///
+ /// A parameter runs up to a `;` outside quotes (even inside parentheses) or up to
+ /// an unbalanced `)`, and keeps its text as written, trailing whitespace included.
+ /// Whitespace and `;` between parameters are skipped. Returns `false` when the end
+ /// of the input is reached inside a quote or right after a `\\`: Angular's cursor
+ /// throws there, so the parameter is dropped and the block start is left as it is.
+ fn scan_block_parameters(&mut self) -> bool {
+ self.skip_block_parameter_separators();
+
+ while self.index < self.length && self.peek() != ')' && self.peek() != chars::EOF {
let param_start = self.index;
-
let mut in_quote: Option = None;
- let mut paren_depth = 0;
-
- // Consume the parameter until the next semicolon or closing paren.
- // Note that we skip over semicolons inside of strings and inside
- // nested parens — upstream's `_consumeBlockParameters` tracks
- // `openParens` only for `)` and splits on any `;` outside quotes,
- // so `@for (i of f(a; b))` is one parameter here, two upstream.
- while self.index < self.length {
- let ch = self.peek();
+ let mut open_parens = 0u32;
- // Handle escape sequences - skip the escaped char
- if ch == '\\' {
- self.advance();
- if self.index < self.length {
- self.advance();
+ loop {
+ if self.index >= self.length {
+ if in_quote.is_none() {
+ break;
}
- continue;
+ self.error("Unexpected character \"EOF\"");
+ return false;
}
-
+ let ch = self.peek();
// A NUL ends the parameter, but not inside a quote, as in Angular.
- if ch == chars::EOF && in_quote.is_none() {
+ if in_quote.is_none() && (ch == ';' || ch == chars::EOF) {
break;
}
-
- // If in a quote, check for quote end
- if let Some(quote_char) = in_quote {
- if ch == quote_char {
- in_quote = None;
- }
+ if ch == '\\' {
self.advance();
- continue;
- }
-
- // Not in quote - check for quote start. `chars.isQuote` includes
- // the backtick, so `)`/`;` inside a template literal don't end
- // the parameter.
- if ch == '"' || ch == '\'' || ch == '`' {
+ if self.index >= self.length {
+ self.error("Unexpected character \"EOF\"");
+ return false;
+ }
+ } else if Some(ch) == in_quote {
+ in_quote = None;
+ } else if in_quote.is_none() && (ch == '"' || ch == '\'' || ch == '`') {
+ // `chars.isQuote` includes the backtick.
in_quote = Some(ch);
- self.advance();
- continue;
- }
-
- // Track parens
- if ch == '(' {
- paren_depth += 1;
- } else if ch == ')' {
- if paren_depth == 0 {
+ } else if in_quote.is_none() && ch == '(' {
+ open_parens += 1;
+ } else if in_quote.is_none() && ch == ')' {
+ if open_parens == 0 {
break;
}
- paren_depth -= 1;
- } else if ch == ';' && paren_depth == 0 {
- break;
+ open_parens -= 1;
}
-
self.advance();
}
- // If we hit EOF while still in a quote, report an error
- if in_quote.is_some() && self.index >= self.length {
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\"".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
- }
-
- let param_text = self.input[param_start as usize..self.index as usize].trim();
- if !param_text.is_empty() {
- self.tokens.push(HtmlToken::with_part(
- HtmlTokenType::BlockParameter,
- param_text,
- param_start,
- self.index,
- ));
- }
+ let param_text = &self.input[param_start as usize..self.index as usize];
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::BlockParameter,
+ param_text,
+ param_start,
+ self.index,
+ ));
- if self.peek() == ';' {
- self.advance();
- }
+ self.skip_block_parameter_separators();
+ }
+ true
+ }
- self.skip_whitespace();
+ /// Skips whitespace and `;` (Angular's `isBlockParameterChar` stops at anything else).
+ fn skip_block_parameter_separators(&mut self) {
+ while self.index < self.length && (self.peek() == ';' || chars::is_whitespace(self.peek()))
+ {
+ self.advance();
}
}
@@ -1606,8 +1608,8 @@ impl<'a> HtmlLexer<'a> {
fn is_tag_start(&self) -> bool {
if self.peek() == '<' {
let next = self.peek_at(1);
- // If the next character is alphabetic, ! or / then it is a tag start
- next.is_ascii_alphabetic() || next == '/' || next == '!'
+ // If the next character is alphabetic, !, / or ? then it is a tag start
+ next.is_ascii_alphabetic() || next == '/' || next == '!' || next == '?'
} else {
false
}
@@ -1734,6 +1736,13 @@ impl<'a> HtmlLexer<'a> {
return;
}
+ // Check for a processing instruction
+ if self.peek() == '?' {
+ self.advance();
+ self.scan_processing_instruction(start);
+ return;
+ }
+
// Check for comment
if self.starts_with("!--") {
self.scan_comment(start);
@@ -1775,6 +1784,13 @@ impl<'a> HtmlLexer<'a> {
} else if self.peek() == chars::EOF {
// Just `') {
+ // Angular reads any other ` HtmlLexer<'a> {
// Scan attributes (with directive support if selectorless is enabled)
self.scan_attributes();
+ if std::mem::take(&mut self.attr_value_unterminated) {
+ return;
+ }
// Check for tag close
self.skip_whitespace();
@@ -1979,6 +1998,8 @@ impl<'a> HtmlLexer<'a> {
// Raw text reads through a NUL, as Angular's `_consumeRawText` does.
if self.index >= self.length {
+ // Angular's cursor throws at the end of the input before the end tag.
+ self.error("Unexpected character \"EOF\"");
// End of input - emit what we have (if non-empty)
if consume_entities {
if text_start < self.index {
@@ -2062,6 +2083,9 @@ impl<'a> HtmlLexer<'a> {
// Scan attributes (with directive support)
self.scan_attributes();
+ if std::mem::take(&mut self.attr_value_unterminated) {
+ return;
+ }
// Check for component close
self.skip_whitespace();
@@ -2265,11 +2289,12 @@ impl<'a> HtmlLexer<'a> {
// Check for missing >
if self.peek() != '>' {
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\"".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
+ self.push_error(
+ "Unexpected character \"EOF\"".to_string(),
+ (self.line, self.column),
+ self.index,
+ self.index,
+ );
} else {
self.advance();
}
@@ -2286,29 +2311,17 @@ impl<'a> HtmlLexer<'a> {
// Scan tag name
let (prefix, name) = self.scan_tag_name();
- // Check for missing tag name
- if name.is_empty() && prefix.is_empty() {
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\"".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
- return;
- }
-
+ // An empty name is allowed (`>`), as in Angular's `_consumeTagClose`.
// Skip whitespace
self.skip_whitespace();
- // Check for missing >
+ // A missing `>` is an error at the character found instead, and the end tag
+ // is dropped, as Angular's `_requireCharCode` throws out of `_consumeTagClose`.
if self.peek() != '>' {
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\"".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
- } else {
- self.advance();
+ self.error(&self.unexpected_character_message());
+ return;
}
+ self.advance();
self.tokens.push(HtmlToken::with_prefix_name(
HtmlTokenType::TagClose,
@@ -2468,6 +2481,9 @@ impl<'a> HtmlLexer<'a> {
self.advance();
self.skip_whitespace();
self.scan_attribute_value();
+ if self.attr_value_unterminated {
+ break;
+ }
}
}
}
@@ -2509,6 +2525,9 @@ impl<'a> HtmlLexer<'a> {
&& Self::is_selectorless_name_start(self.peek_at(1))
{
self.scan_directive();
+ if self.attr_value_unterminated {
+ break;
+ }
continue;
}
@@ -2608,6 +2627,9 @@ impl<'a> HtmlLexer<'a> {
self.advance();
self.skip_whitespace();
self.scan_attribute_value();
+ if self.attr_value_unterminated {
+ break;
+ }
}
}
}
@@ -2629,6 +2651,9 @@ impl<'a> HtmlLexer<'a> {
// Scan value with interpolation support
self.scan_attribute_value_text(quote);
+ if self.attr_value_unterminated {
+ return;
+ }
// Closing quote
if self.peek() == quote {
@@ -2642,11 +2667,8 @@ impl<'a> HtmlLexer<'a> {
));
} else {
// Missing closing quote - report error
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\"".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
+ self.error("Unexpected character \"EOF\"");
+ self.attr_value_unterminated = true;
}
} else {
// Unquoted value - may contain interpolation
@@ -2711,20 +2733,49 @@ impl<'a> HtmlLexer<'a> {
self.index,
));
} else {
- // Regular unquoted value
+ // Regular unquoted value. As Angular's `_consumeWithInterpolation`,
+ // entities are decoded here too.
+ let mut text_start = value_start;
while !chars::is_whitespace(self.peek())
&& self.peek() != '>'
&& self.peek() != '/'
&& self.peek() != chars::EOF
{
- self.advance();
+ if self.peek() != '&' {
+ self.advance();
+ continue;
+ }
+ let entity_start = self.index;
+ if self.scan_entity() {
+ if let Some(entity_token) = self.tokens.pop() {
+ let text = &self.input[text_start as usize..entity_start as usize];
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::AttrValueText,
+ text,
+ text_start,
+ entity_start,
+ ));
+ self.tokens.push(entity_token);
+ text_start = self.index;
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::AttrValueText,
+ "",
+ text_start,
+ text_start,
+ ));
+ }
+ } else if self.abort_tag_on_entity_error(text_start, entity_start) {
+ return;
+ } else {
+ self.advance();
+ }
}
- let value = &self.input[value_start as usize..self.index as usize];
+ let value = &self.input[text_start as usize..self.index as usize];
if !value.is_empty() {
self.tokens.push(HtmlToken::with_part(
HtmlTokenType::AttrValueText,
value,
- value_start,
+ text_start,
self.index,
));
}
@@ -2732,6 +2783,45 @@ 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.
+ 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 text = &self.input[text_start as usize..entity_start as usize];
+ let normalized = normalize_line_endings(text);
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::AttrValueText,
+ &normalized,
+ text_start,
+ entity_start,
+ ));
+ }
+ self.index = index;
+ self.line = line;
+ self.column = column;
+ if mark_incomplete {
+ for token in self.tokens.iter_mut().rev() {
+ if token.token_type == HtmlTokenType::TagOpenStart {
+ token.token_type = HtmlTokenType::IncompleteTagOpen;
+ break;
+ }
+ if token.token_type == HtmlTokenType::ComponentOpenStart {
+ token.token_type = HtmlTokenType::IncompleteComponentOpen;
+ break;
+ }
+ }
+ }
+ self.attr_value_unterminated = true;
+ true
+ }
+
/// Scans attribute value text (with interpolation and entity support).
fn scan_attribute_value_text(&mut self, quote: char) {
// Check for empty value (immediately at closing quote)
@@ -2864,6 +2954,8 @@ impl<'a> HtmlLexer<'a> {
text_start,
));
}
+ } else if self.abort_tag_on_entity_error(text_start, entity_start) {
+ return;
} else {
// scan_entity reverted, so & is just regular text - advance past it
self.advance();
@@ -2935,16 +3027,58 @@ impl<'a> HtmlLexer<'a> {
}
let content = &self.input[content_start as usize..self.index as usize];
- if self.peek() == '>' {
- self.advance();
- } else {
- // Report error for unterminated DOCTYPE
- self.error("Unexpected end of DOCTYPE");
+ if self.peek() != '>' {
+ // As Angular's cursor at the end of the input; the DOCTYPE is dropped.
+ self.error("Unexpected character \"EOF\"");
+ return;
}
+ self.advance();
self.tokens.push(HtmlToken::with_part(HtmlTokenType::DocType, content, start, self.index));
}
+ /// Scans a processing instruction after ``, as Angular's
+ /// `_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() != '>' {
+ let ch = self.peek();
+ self.advance();
+ if ch == '"' || ch == '\'' || ch == '`' {
+ while self.index < self.length && self.peek() != ch {
+ if self.peek() == '\\' {
+ self.advance();
+ }
+ if self.index < self.length {
+ self.advance();
+ }
+ }
+ if self.index < self.length {
+ self.advance(); // closing quote
+ }
+ }
+ }
+ if self.index >= self.length {
+ self.error("Unexpected character \"EOF\"");
+ return;
+ }
+ let content = self.input[content_start as usize..self.index as usize].to_string();
+ let end_char = self.advance();
+ if end_char == '?' {
+ if self.peek() != '>' {
+ self.error(&self.unexpected_character_message());
+ return;
+ }
+ self.advance();
+ }
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::ProcessingInstruction,
+ &content,
+ start,
+ self.index,
+ ));
+ }
+
/// Scans a CDATA section.
fn scan_cdata(&mut self, start: u32) {
// Skip ![CDATA[
@@ -3055,9 +3189,14 @@ impl<'a> HtmlLexer<'a> {
self.expansion_case_stack.push(HtmlTokenType::ExpansionFormStart);
- // Read the switch value (until comma)
+ // Read the switch value (until comma). As Angular's `_readUntil`, reaching
+ // the end is an error, and the token being read is dropped.
let value_start = self.index;
let condition = self.read_until(',');
+ if self.index >= self.length {
+ self.error("Unexpected character \"EOF\"");
+ return;
+ }
self.tokens.push(HtmlToken::with_part(
HtmlTokenType::RawText,
&condition,
@@ -3065,14 +3204,16 @@ impl<'a> HtmlLexer<'a> {
self.index,
));
- if self.peek() == ',' {
- self.advance();
- }
+ self.advance(); // consume ','
self.skip_whitespace();
// Read the type (until comma)
let type_start = self.index;
let icu_type = self.read_until(',');
+ if self.index >= self.length {
+ self.error("Unexpected character \"EOF\"");
+ return;
+ }
self.tokens.push(HtmlToken::with_part(
HtmlTokenType::RawText,
&icu_type,
@@ -3080,9 +3221,7 @@ impl<'a> HtmlLexer<'a> {
self.index,
));
- if self.peek() == ',' {
- self.advance();
- }
+ self.advance(); // consume ','
self.skip_whitespace();
}
@@ -3091,6 +3230,11 @@ impl<'a> HtmlLexer<'a> {
// Read case value (until '{')
let value_start = self.index;
let value = self.read_until('{').trim().to_string();
+ if self.index >= self.length {
+ // As Angular's `_readUntil`: the case value token is dropped.
+ self.error("Unexpected character \"EOF\"");
+ return;
+ }
self.tokens.push(HtmlToken::with_part(
HtmlTokenType::ExpansionCaseValue,
&value,
@@ -3184,31 +3328,28 @@ impl<'a> HtmlLexer<'a> {
break;
}
- // Stop at @let declaration
- if ch == '@' && self.starts_with("@let") {
- let next_char_index = self.index as usize + 4;
- if next_char_index < self.input.len() {
- let next_char =
- self.input[next_char_index..].chars().next().unwrap_or(chars::EOF);
- if chars::is_whitespace(next_char) {
- break;
- }
- }
- }
-
- // Stop at block start (supported block keywords only)
- if self.is_block_start() {
+ // Stop at `@let` (which `scan_token` reads as a declaration or an
+ // incomplete one, `a@letter` too) or a block start. As Angular's
+ // `_isTextEnd`, only outside expansions: `me@forum.com` in an ICU case
+ // is text.
+ if ch == '@'
+ && self.tokenize_blocks
+ && !self.is_in_expansion_case()
+ && !self.is_in_expansion_form()
+ && ((self.tokenize_let && self.starts_with("@let")) || self.is_block_start())
+ {
break;
}
// Handle `<` - only stop if it's a valid tag start
if ch == '<' {
let next = self.peek_at(1);
- // Valid tag start: `/` (close tag), `!` (comment/doctype/cdata), or a letter.
+ // Valid tag start: `/` (close tag), `!` (comment/doctype/cdata), `?`
+ // (processing instruction), or a letter.
// Upstream `_isTagStart` has no `_` case, so mid-text `<_C` stays
// text even in selectorless mode; a component only tokenizes at a
// token boundary (the dispatch check in `scan_next_token`).
- if next == '/' || next == '!' || next.is_ascii_alphabetic() {
+ if next == '/' || next == '!' || next == '?' || next.is_ascii_alphabetic() {
break;
}
// Otherwise, `<` is just text, continue
@@ -3288,6 +3429,7 @@ impl<'a> HtmlLexer<'a> {
/// 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).
fn scan_entity(&mut self) -> bool {
+ self.entity_error = None;
let start = self.index;
let start_line = self.line;
let start_col = self.column;
@@ -3313,27 +3455,39 @@ impl<'a> HtmlLexer<'a> {
num_str.push(self.advance());
}
- // Check for semicolon and that we have at least one digit
- if self.peek() == ';' && !num_str.is_empty() {
+ if self.peek() == ';' {
let num_str = num_str.as_str();
self.advance(); // consume ';'
// Parse and decode
- if let Ok(code_point) =
+ let code_point =
if is_hex { u32::from_str_radix(num_str, 16) } else { num_str.parse::() }
- {
- if let Some(ch) = char::from_u32(code_point) {
- let decoded = ch.to_string();
- let marker = hex_marker.map(String::from).unwrap_or_default();
- let original = format!("{marker}{num_str};");
- self.tokens.push(HtmlToken::new(
- HtmlTokenType::EncodedEntity,
- vec![decoded, original],
- start,
- self.index,
- ));
- return true;
- }
+ .ok();
+ // 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 msg = format!(
+ "Unknown entity \"{entity_str}\" - use the \";\" or \";\" syntax"
+ );
+ self.push_error(msg, (self.line, self.column), self.index, self.index);
+ self.entity_error = Some(EntityError::At(self.index, self.line, self.column));
+ self.index = start;
+ self.line = start_line;
+ self.column = start_col;
+ return false;
+ }
+ if let Some(ch) = code_point.and_then(char::from_u32) {
+ let decoded = ch.to_string();
+ let marker = hex_marker.map(String::from).unwrap_or_default();
+ let original = format!("{marker}{num_str};");
+ self.tokens.push(HtmlToken::new(
+ HtmlTokenType::EncodedEntity,
+ vec![decoded, original],
+ start,
+ self.index,
+ ));
+ return true;
}
// Invalid code point - revert
self.index = start;
@@ -3347,22 +3501,21 @@ impl<'a> HtmlLexer<'a> {
// (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"
- self.errors.push(HtmlTokenError {
- msg: "Unexpected character \"EOF\"".to_string(),
- position: (self.line, self.column),
- offset: self.index,
- });
+ self.push_error(
+ "Unexpected character \"EOF\"".to_string(),
+ (self.line, self.column),
+ self.index,
+ self.index,
+ );
+ self.entity_error = Some(EntityError::Eof(self.index, self.line, self.column));
} else {
self.advance();
let entity_str = &self.input[start as usize..self.index as usize];
let entity_type = if is_hex { "hexadecimal" } else { "decimal" };
- self.errors.push(HtmlTokenError {
- msg: format!(
+ self.push_error(format!(
"Unable to parse entity \"{entity_str}\" - {entity_type} character reference entities must end with \";\""
- ),
- position: (self.line, self.column),
- offset: self.index,
- });
+ ), (self.line, self.column), self.index, self.index);
+ self.entity_error = Some(EntityError::At(self.index, self.line, self.column));
}
// Revert and treat as text
self.index = start;
@@ -3381,8 +3534,8 @@ impl<'a> HtmlLexer<'a> {
name.push(self.advance());
}
- // Check for semicolon and that we have at least one char
- if self.peek() == ';' && !name.is_empty() {
+ // Check for semicolon (an empty name is an unknown entity, as in Angular)
+ if self.peek() == ';' {
self.advance(); // consume ';'
if get_named_entities().contains_key(name.as_str()) {
@@ -3400,13 +3553,15 @@ impl<'a> HtmlLexer<'a> {
}
// Named entity with semicolon but unknown name - this is an error
- self.errors.push(HtmlTokenError {
- msg: format!(
+ self.push_error(
+ format!(
"Unknown entity \"{name}\" - use the \";\" or \";\" syntax"
),
- position: (start_line, start_col),
- offset: start,
- });
+ (start_line, start_col),
+ start,
+ self.index,
+ );
+ self.entity_error = Some(EntityError::At(self.index, self.line, self.column));
// Revert and treat as text
self.index = start;
self.line = start_line;
diff --git a/crates/oxc_angular_compiler/src/parser/html/parser.rs b/crates/oxc_angular_compiler/src/parser/html/parser.rs
index 0df96651d..609232ce7 100644
--- a/crates/oxc_angular_compiler/src/parser/html/parser.rs
+++ b/crates/oxc_angular_compiler/src/parser/html/parser.rs
@@ -9,6 +9,7 @@ use std::sync::Arc;
use oxc_allocator::{Allocator, Box, FromIn, Vec};
use oxc_span::Span;
use oxc_str::Ident;
+use rustc_hash::FxHashMap;
use crate::ast::html::{
BlockType, HtmlAttribute, HtmlBlock, HtmlBlockParameter, HtmlComment, HtmlDirective,
@@ -16,6 +17,7 @@ use crate::ast::html::{
InterpolatedToken, InterpolatedTokenType,
};
use crate::parser::expression::BindingParser;
+use crate::parser::{MAX_CALL_STACK_ERROR, depth_limit_reached, depth_limits};
use crate::transform::control_flow::is_else_if_pattern;
use crate::util::{ParseError, ParseLocation, ParseSourceFile, ParseSourceSpan};
@@ -60,6 +62,29 @@ pub struct HtmlParser<'a> {
elements: std::vec::Vec>,
/// Stack of containers (Blocks and Elements) for parent-child tracking.
container_stack: std::vec::Vec,
+ /// For each `ExpansionCaseExpStart` token index checked so far, the index of its
+ /// matching `ExpansionCaseExpEnd` (see [`Self::collect_expansion_case`]).
+ case_ends: FxHashMap,
+ /// For each entry of `elements`, the namespace it passes down to the tags
+ /// inside it (see [`Self::inherited_prefix`]).
+ element_ns: std::vec::Vec
${repeat('', 2_100)}x${repeat('
', 2_100)}`, 4],
+ beforeBlocks: [`${repeat('@if (a) {', 2_100)}x${repeat('}', 2_100)}`, 4],
+ inside: [`${repeat('', 2_100)}x${repeat('
', 2_100)}`, 10_501],
+ after: [`${repeat('', 2_100)}x${repeat('
', 2_100)}`, 23_105],
+ } as const
+ for (const [name, [template, column]] of Object.entries(deepTemplatesWithErrors)) {
+ it(`reports the errors of a deep template: ${name}`, async () => {
+ for (const result of [
+ transformAngularFileSync(source, '/x/cut.ts', {}, resources(template)),
+ await transformAngularFile(source, '/x/cut.ts', {}, resources(template)),
+ ]) {
+ expect(result.errors.map((e) => e.message)).toEqual([unexpectedSpan])
+ expect(result.errors[0].codeframe).toContain(`cut.html:1:${column}`)
+ }
+ }, 60_000)
+ }
+
+ it('reports the errors in a @switch with too many cases', () => {
+ const cases = Array.from({ length: 2_100 }, (_, i) => `@case (${i + 1}) {x}`).join('')
+ // ngc: `cut.html:1:25`.
+ const template = `@switch (a) {@case (0) {{{ a b }}}${cases}}`
+ const result = transformAngularFileSync(source, '/x/cut.ts', {}, resources(template))
+ expect(result.errors.map((e) => e.message)).toEqual([
+ "Unexpected token 'b' at column 4 in [ a b ]",
+ ])
+ expect(result.errors[0].codeframe).toContain('cut.html:1:25')
+ }, 60_000)
+})
diff --git a/napi/angular-compiler/test/extract-component-metadata.test.ts b/napi/angular-compiler/test/extract-component-metadata.test.ts
index 66309ee8d..589941580 100644
--- a/napi/angular-compiler/test/extract-component-metadata.test.ts
+++ b/napi/angular-compiler/test/extract-component-metadata.test.ts
@@ -274,3 +274,24 @@ const B = { ...A, '[attr.aria-label]': 't', role: 'link' };`,
expect(hostOf(`const HOST = { ${ENTRIES} } as const;`, 'HOST')).toEqual(literal)
})
})
+
+// `template` is the text Angular compiles: what its `EscapedCharacterCursor`
+// reads from the literal's raw text.
+describe('extractComponentMetadataSync template', () => {
+ const templateOf = (literal: string) =>
+ extractComponentMetadataSync(
+ `import { Component } from '@angular/core';\n@Component({ selector: 'x', template: ${literal} })\nexport class X {}\n`,
+ 'x.component.ts',
+ )[0]?.template
+
+ it('keeps a lone surrogate as one code unit', () => {
+ expect(templateOf(String.raw`'a\uD83Db
'`)).toBe('a\uD83Db
')
+ expect(templateOf(String.raw`'a😀b
'`)).toBe('a😀b
')
+ })
+
+ it('reads escapes like Angular', () => {
+ expect(templateOf(String.raw`'a\400b
'`)).toBe('aĀb
')
+ expect(templateOf("'a\\\r\nb
'")).toBe('a\nb
')
+ expect(templateOf("'a\\\nb
'")).toBe('ab
')
+ })
+})