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: "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 `` 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 \"&#x;\" 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 \"&#x;\" 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>, + /// For each entry of `blocks`, the namespace the open elements around it pass + /// down (a block passes it on as it is). + block_ns: std::vec::Vec>, + /// How deep the containers set aside by the ICU cases being parsed nest, with + /// those ICUs and cases: the depth `container_stack` starts at. + outer_depth: usize, + /// How deep a template may nest: `MAX_TEMPLATE_DEPTH`, or the lower limit of + /// `with_depth_limits`. + max_depth: usize, + /// The offset of the first node nested deeper than `max_depth`. The parse then + /// reports `MAX_CALL_STACK_ERROR` there, unless it has other errors. + too_deep: Option, + /// How many ICUs are being parsed: they are parsed recursively. + icu_depth: usize, + /// When ICUs nest deeper than `max_depth`, the rest of the input is skipped: + /// how many errors were found before. The errors of the cut parse are dropped. + errors_before_skip: Option, } impl<'a> HtmlParser<'a> { @@ -160,7 +185,9 @@ impl<'a> HtmlParser<'a> { lex_err.position.0, lex_err.position.1, ); - let span = ParseSourceSpan::new(loc.clone(), loc); + let end = + ParseLocation::new(Arc::clone(&source_file), lex_err.end.max(lex_err.offset), 0, 0); + let span = ParseSourceSpan::new(loc, end); errors.push(ParseError::new(span, lex_err.msg)); } @@ -174,14 +201,47 @@ impl<'a> HtmlParser<'a> { blocks: std::vec::Vec::new(), elements: std::vec::Vec::new(), container_stack: std::vec::Vec::new(), + case_ends: FxHashMap::default(), + element_ns: std::vec::Vec::new(), + block_ns: std::vec::Vec::new(), + outer_depth: 0, + max_depth: depth_limits().template, + too_deep: None, + icu_depth: 0, + errors_before_skip: None, + } + } + + /// Records a node starting at `offset` that opens in the current container + /// nested deeper than `max_depth`. The parse goes on (open elements and blocks + /// are kept in a list, not on the call stack), so that the rest of the input is + /// checked for errors too. + fn check_depth(&mut self, offset: u32) { + if self.outer_depth + self.container_stack.len() >= self.max_depth { + self.too_deep.get_or_insert(offset); } } /// Creates a ParseError at the given offset with the given message. fn make_error(&self, offset: u32, msg: impl Into) -> ParseError { - let loc = ParseLocation::new(self.source_file.clone(), offset, 0, 0); - let span = ParseSourceSpan::new(loc.clone(), loc); - ParseError::new(span, msg) + self.make_span_error(offset, offset, msg) + } + + /// Creates a ParseError over `start..end` with the given message. + fn make_span_error(&self, start: u32, end: u32, msg: impl Into) -> ParseError { + let start_loc = ParseLocation::new(Arc::clone(&self.source_file), start, 0, 0); + let end_loc = ParseLocation::new(Arc::clone(&self.source_file), end.max(start), 0, 0); + ParseError::new(ParseSourceSpan::new(start_loc, end_loc), msg) + } + + /// The `Unclosed block "name"` error Angular reports on a block left open, over + /// the block's start (`@if (a) {`). + fn unclosed_block_error(&self, block: &HtmlBlock<'a>) -> ParseError { + self.make_span_error( + block.start_span.start, + block.start_span.end, + format!("Unclosed block \"{}\"", block.name), + ) } /// Parses the template. @@ -193,20 +253,17 @@ impl<'a> HtmlParser<'a> { // Close all remaining containers at EOF (error recovery) // This ensures we still produce AST nodes even for unclosed elements. - // Popping drains innermost→outermost, so multiple "Unclosed block" - // errors come out in that order; upstream iterates `_containerStack` - // front-to-back and reports outermost first. (Its message and span also - // differ: `Unclosed block "if"` over the whole block, no `@`.) + // Angular reports the blocks left open outermost first, as it walks + // `_containerStack` front to back. + for container in &self.container_stack { + if let ContainerIndex::Block(idx) = *container { + let err = self.unclosed_block_error(&self.blocks[idx]); + self.errors.push(err); + } + } while let Some(container) = self.container_stack.pop() { match container { ContainerIndex::Block(idx) => { - let block = &self.blocks[idx]; - let err = self.make_error( - block.span.start, - format!("Unclosed block \"@{}\"", block.name), - ); - self.errors.push(err); - // Convert block to node and add to parent let block = std::mem::replace( &mut self.blocks[idx], @@ -253,6 +310,23 @@ impl<'a> HtmlParser<'a> { } } + if let Some(count) = self.errors_before_skip { + self.errors.truncate(count); + } + // Angular's tree builder keeps its open elements and blocks in a list too, and + // its stack overflows on a deep template only in a visitor after the parse, + // which runs only if the parse has no errors. + if let Some(offset) = self.too_deep { + // The result depends on `max_depth` only then: with other errors (all + // of them found), nothing compiles the deep template. + if self.errors.is_empty() || self.errors_before_skip.is_some() { + depth_limit_reached(); + } + if self.errors.is_empty() { + self.errors.push(self.make_error(offset, MAX_CALL_STACK_ERROR)); + } + } + // Convert root_nodes to arena-allocated Vec let mut nodes = Vec::new_in(&self.allocator); for node in self.root_nodes { @@ -283,19 +357,39 @@ impl<'a> HtmlParser<'a> { } /// Pushes a block onto the container stack. - fn push_block_container(&mut self, block: HtmlBlock<'a>) -> usize { + fn push_block_container(&mut self, block: HtmlBlock<'a>) { + self.check_depth(block.span.start); let idx = self.blocks.len(); + self.block_ns.push(self.inherited_prefix(self.container_stack.len())); self.blocks.push(block); self.container_stack.push(ContainerIndex::Block(idx)); - idx } /// Pushes an element onto the container stack. - fn push_element_container(&mut self, element: HtmlElement<'a>) -> usize { + fn push_element_container(&mut self, element: HtmlElement<'a>) { + self.check_depth(element.span.start); let idx = self.elements.len(); + // The namespace this element passes down: its own prefix or implicit one, + // or the one it took from its parent, unless it stops inheritance. + let (prefix, local_name) = if element.is_component { + ( + element.component_prefix.as_ref().map(Ident::as_str), + element.component_tag_name.as_ref().map_or("ng-component", Ident::as_str), + ) + } else { + split_ns_name(element.name.as_str()) + }; + let tag_def = get_html_tag_definition(local_name); + let passes_down = if tag_def.prevent_namespace_inheritance { + None + } else { + prefix + .or(tag_def.implicit_namespace_prefix) + .or_else(|| self.inherited_prefix(self.container_stack.len())) + }; self.elements.push(element); + self.element_ns.push(passes_down); self.container_stack.push(ContainerIndex::Element(idx)); - idx } /// Whether a tag without a prefix inside the open elements takes a namespace from them, as @@ -305,28 +399,48 @@ impl<'a> HtmlParser<'a> { /// passes down its host tag (``, `ng-component` without one), as /// `_getPrefix` reads a component's `tagName`. fn inherits_namespace(&self) -> bool { - let elements = self.container_stack.iter().rev().filter_map(|container| match container { - ContainerIndex::Element(idx) => Some(&self.elements[*idx]), - ContainerIndex::Block(_) => None, - }); - for element in elements { - let (prefix, local_name) = if element.is_component { - ( - element.component_prefix.as_ref().map(|prefix| prefix.as_str()), - element.component_tag_name.as_ref().map_or("ng-component", |tag| tag.as_str()), - ) - } else { - split_ns_name(element.name.as_str()) - }; - let tag_def = get_html_tag_definition(local_name); - if tag_def.prevent_namespace_inheritance { - return false; - } - if prefix.is_some() || tag_def.implicit_namespace_prefix.is_some() { - return true; - } + self.inherited_prefix(self.container_stack.len()).is_some() + } + + /// The namespace a tag without a prefix takes from the open elements in + /// `container_stack[..depth]` (see [`Self::inherits_namespace`]). + /// + /// Each container stores what it passes down when it is pushed, so this reads + /// the innermost one only (Angular's `_getClosestElementLikeParent` skips the + /// blocks, which pass the namespace on as it is). + fn inherited_prefix(&self, depth: usize) -> Option<&'a str> { + match depth.checked_sub(1).map(|top| self.container_stack[top])? { + ContainerIndex::Element(idx) => self.element_ns[idx], + ContainerIndex::Block(idx) => self.block_ns[idx], } - false + } + + /// The name Angular's `_getElementFullName` gives a tag here (`:svg:svg` for + /// `svg`), which its error messages use. + fn angular_full_name(&self, prefix: &str, local_name: &str) -> String { + let prefix = if prefix.is_empty() { + get_html_tag_definition(local_name) + .implicit_namespace_prefix + .or_else(|| self.inherited_prefix(self.container_stack.len())) + .unwrap_or("") + } else { + prefix + }; + if prefix.is_empty() { local_name.to_string() } else { format!(":{prefix}:{local_name}") } + } + + /// The name Angular gives the open element at `container_stack[depth]`. + fn open_element_full_name(&self, depth: usize, idx: usize) -> String { + let element = &self.elements[idx]; + let name = element.name.as_str(); + if element.is_component || name.starts_with(':') { + return name.to_string(); + } + let prefix = get_html_tag_definition(name) + .implicit_namespace_prefix + .or_else(|| self.inherited_prefix(depth)) + .unwrap_or(""); + if prefix.is_empty() { name.to_string() } else { format!(":{prefix}:{name}") } } /// Whether a void name is an HTML void element here: not in a namespace, by its own prefix or @@ -336,13 +450,16 @@ impl<'a> HtmlParser<'a> { get_html_tag_definition(local_name).is_void && !has_prefix && !self.inherits_namespace() } - /// Pops a block from the container stack and returns it as an HtmlNode. - fn pop_block_container(&mut self, end_span: Option) -> Option> { + /// Pops the innermost block from the container stack and returns it as an + /// HtmlNode, with whether an element above it needed an explicit end tag. As + /// Angular's `_popContainer`, the elements above it are closed first. + fn pop_block_container(&mut self, end_span: Option) -> (Option>, bool) { // Find the topmost block in the stack for i in (0..self.container_stack.len()).rev() { if let ContainerIndex::Block(idx) = self.container_stack[i] { + let unexpected_close = self.close_containers_above(i); // Remove from stack - self.container_stack.remove(i); + self.container_stack.pop(); // Get the block and update its end span let mut block = std::mem::replace( &mut self.blocks[idx], @@ -361,49 +478,24 @@ impl<'a> HtmlParser<'a> { block.end_span = Some(es); block.span = Span::new(block.span.start, es.end); } - return Some(HtmlNode::Block(Box::new_in(block, &self.allocator))); + return ( + Some(HtmlNode::Block(Box::new_in(block, &self.allocator))), + unexpected_close, + ); } } - None + (None, false) } - /// Pops an element from the container stack matching the given tag name. - /// If there are unclosed elements above the matching one, they are implicitly closed first. - /// - /// Returns the closed element node along with a boolean flag indicating whether any - /// implicitly-closed container above the matching one required an explicit end tag - /// (i.e. its tag definition does not have `closed_by_parent`, or it was a block). - /// Mirrors Angular's `_popContainer`, which surfaces this as an "Unexpected closing - /// tag" diagnostic on the closing tag itself. - fn pop_element_container( - &mut self, - tag_name: &str, - end_span: Option, - ) -> (Option>, bool) { - // Find the matching element in the stack and its element index - let mut match_stack_idx = None; - let mut match_elem_idx = None; - for i in (0..self.container_stack.len()).rev() { - if let ContainerIndex::Element(idx) = self.container_stack[i] { - if self.elements[idx].name.as_str() == tag_name { - match_stack_idx = Some(i); - match_elem_idx = Some(idx); - break; - } - } - } - - let Some(match_stack_idx) = match_stack_idx else { - return (None, false); - }; - let Some(match_elem_idx) = match_elem_idx else { - return (None, false); - }; - + /// Implicitly closes the containers above `container_stack[stack_idx]`, innermost + /// first, adding each to its parent. Returns whether one of them needed an explicit + /// end (an element whose end tag is not optional, or a block), which Angular's + /// `_popContainer` reports as an unexpected close. + fn close_containers_above(&mut self, stack_idx: usize) -> bool { let mut unexpected_close_detected = false; // Implicitly close all containers above the matching one (in reverse order) - while self.container_stack.len() > match_stack_idx + 1 { + while self.container_stack.len() > stack_idx + 1 { let Some(container) = self.container_stack.pop() else { break; // Should not happen, but handle gracefully }; @@ -463,6 +555,44 @@ impl<'a> HtmlParser<'a> { } } + unexpected_close_detected + } + + /// Pops an element from the container stack matching the given tag name. + /// If there are unclosed elements above the matching one, they are implicitly closed first. + /// + /// Returns the closed element node along with a boolean flag indicating whether any + /// implicitly-closed container above the matching one required an explicit end tag + /// (i.e. its tag definition does not have `closed_by_parent`, or it was a block). + /// Mirrors Angular's `_popContainer`, which surfaces this as an "Unexpected closing + /// tag" diagnostic on the closing tag itself. + fn pop_element_container( + &mut self, + tag_name: &str, + end_span: Option, + ) -> (Option>, bool) { + // Find the matching element in the stack and its element index + let mut match_stack_idx = None; + let mut match_elem_idx = None; + for i in (0..self.container_stack.len()).rev() { + if let ContainerIndex::Element(idx) = self.container_stack[i] + && self.elements[idx].name.as_str() == tag_name + { + match_stack_idx = Some(i); + match_elem_idx = Some(idx); + break; + } + } + + let Some(match_stack_idx) = match_stack_idx else { + return (None, false); + }; + let Some(match_elem_idx) = match_elem_idx else { + return (None, false); + }; + + let unexpected_close_detected = self.close_containers_above(match_stack_idx); + // Now pop the matching element from the stack self.container_stack.pop(); @@ -613,6 +743,9 @@ impl<'a> HtmlParser<'a> { self.add_to_parent(node); } } + HtmlTokenType::IncompleteTagOpen if !token.name().is_empty() => { + self.consume_element_start(); + } HtmlTokenType::IncompleteTagOpen => { // Handle incomplete tag (error recovery) if let Some(node) = self.parse_incomplete_tag() { @@ -636,7 +769,12 @@ impl<'a> HtmlParser<'a> { return; // No token to consume }; let start = start_token.start; + let start_token_end = start_token.end; let is_component = start_token.token_type == HtmlTokenType::ComponentOpenStart; + // A start tag the lexer could not finish (`
HtmlParser<'a> { if has_prefix { format!(":{}:{}", prefix, name) } else { name.to_string() }; (full_name, name.to_string(), has_prefix, None, None) }; + let incomplete_message = if is_incomplete { + let prefix = if has_ns_prefix { split_ns_name(&tag_name).0.unwrap_or("") } else { "" }; + Some(format!( + "Opening tag \"{}\" not terminated.", + self.angular_full_name(prefix, &local_name) + )) + } else { + None + }; // Check if we need to auto-close the current element (HTML5 optional end tags) self.auto_close_element_if_needed(&tag_name); @@ -689,8 +836,9 @@ impl<'a> HtmlParser<'a> { || tag_def.implicit_namespace_prefix.is_some() || self.inherits_namespace(); if !(is_component || tag_def.can_self_close || is_foreign || tag_def.is_void) { - let err = self.make_error( + let err = self.make_span_error( start, + start_token_end, format!( "Only void, custom and foreign elements can be self closed \"{}\"", local_name @@ -725,6 +873,11 @@ impl<'a> HtmlParser<'a> { let end_span = if is_self_closing { Some(start_span) } else { None }; let is_void = self.is_html_void(&local_name, has_ns_prefix); + if let Some(message) = incomplete_message { + let err = self.make_span_error(start, end, message); + self.errors.push(err); + } + let element = HtmlElement { name: Ident::from_in(tag_name.clone(), &self.allocator), component_prefix: component_prefix.map(|p| Ident::from_in(p, &self.allocator)), @@ -740,7 +893,7 @@ impl<'a> HtmlParser<'a> { is_void, }; - if is_self_closing || is_void { + if is_self_closing || is_void || is_incomplete { // Self-closing elements are complete immediately self.add_to_parent(HtmlNode::Element(Box::new_in(element, &self.allocator))); } else { @@ -758,30 +911,51 @@ impl<'a> HtmlParser<'a> { let end = token.end; // TagClose has parts [prefix, name] // ComponentClose has parts [component_name, prefix, tag_name] - let (tag_name, local_name) = if token.token_type == HtmlTokenType::ComponentClose { + let is_component = token.token_type == HtmlTokenType::ComponentClose; + let (tag_name, local_name) = if is_component { let name = token.value().to_string(); (name.clone(), name) } else { // For regular tags, include the namespace prefix if present // Angular uses :prefix:name format for namespaced elements let prefix = token.prefix(); - let name = token.name(); + let name = token.name().to_string(); let full_name = - if prefix.is_empty() { name.to_string() } else { format!(":{}:{}", prefix, name) }; - (full_name, name.to_string()) + if prefix.is_empty() { name.clone() } else { format!(":{prefix}:{name}") }; + (full_name, name) + }; + // The namespace Angular's `_getElementFullName` gives a tag without a prefix + // here, read before the pop changes the open elements. The message itself is + // built only for an error. + let message_prefix = if is_component || tag_name.starts_with(':') { + None + } else { + get_html_tag_definition(&local_name) + .implicit_namespace_prefix + .or_else(|| self.inherited_prefix(self.container_stack.len())) }; let end_span = self.make_span(start, end); // Void elements don't have end tags. The open elements pass their namespace down, as to // the start tag. if self.is_html_void(&local_name, tag_name.starts_with(':')) { - let err = self.make_error( + let err = self.make_span_error( start, + end, format!("Void elements do not have end tags \"{}\"", local_name), ); self.errors.push(err); return; } + let unexpected_message = || { + let name = match message_prefix { + Some(prefix) => format!(":{prefix}:{local_name}"), + None => tag_name.clone(), + }; + format!( + "Unexpected closing tag \"{name}\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags" + ) + }; // Pop the matching element from the stack let (node, unexpected_close) = self.pop_element_container(&tag_name, Some(end_span)); @@ -790,19 +964,13 @@ impl<'a> HtmlParser<'a> { // Matching open tag exists, but at least one still-open container above it // had to be implicitly closed. Mirrors Angular's reference parser, which // attaches the diagnostic to the closing tag itself. - let err = self.make_error( - start, - format!("Unexpected closing tag \"{}\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", tag_name), - ); + let err = self.make_span_error(start, end, unexpected_message()); self.errors.push(err); } self.add_to_parent(node); } else { // No matching element - report error for stray closing tag - let err = self.make_error( - start, - format!("Unexpected closing tag \"{}\". It may happen when the tag has already been closed by another tag.", tag_name), - ); + let err = self.make_span_error(start, end, unexpected_message()); self.errors.push(err); } } @@ -844,6 +1012,13 @@ impl<'a> HtmlParser<'a> { }; let name_start = name_token.start; let name_end = name_token.end; + if prefix.is_empty() && base_name.starts_with(':') { + let msg = format!( + "Invalid attribute name '{base_name}'. Attribute names cannot start with a colon." + ); + let err = self.make_span_error(name_start, name_end, msg); + self.errors.push(err); + } // Track the end of the entire attribute (including closing quote) let mut attr_end = name_end; @@ -970,6 +1145,22 @@ impl<'a> HtmlParser<'a> { tok_span, )); } + HtmlTokenType::EncodedEntity => { + // Encoded entity parts: [decodedValue, originalEntity] + let decoded = val_tok.parts.first().cloned().unwrap_or_default(); + let encoded = val_tok.parts.get(1).cloned().unwrap_or_default(); + let tok_start = val_tok.start; + let tok_end = val_tok.end; + value_text.push_str(&decoded); + value_end = tok_end; + self.advance(); + let tok_span = self.make_span(tok_start, tok_end); + tokens.push(( + InterpolatedTokenType::EncodedEntity, + vec![decoded, encoded], + tok_span, + )); + } _ => break, } } @@ -1334,18 +1525,24 @@ impl<'a> HtmlParser<'a> { let name_start = start_end - name.len() as u32; let name_span = self.make_span(name_start, start_end); - // Get value expression - let (value_text, value_span) = if let Some(tok) = self.peek() { - if tok.token_type == HtmlTokenType::LetValue { + // Get value expression. Without one, Angular's `_consumeLet` reports the + // declaration over its start (`@let x`) and drops it. + let (value_text, value_span) = match self.peek() { + Some(tok) if tok.token_type == HtmlTokenType::LetValue => { let v = tok.value().to_string(); let vs = self.make_span(tok.start, tok.end); self.advance(); (v, vs) - } else { - (String::new(), self.make_span(start_end, start_end)) } - } else { - (String::new(), self.make_span(start_end, start_end)) + _ => { + let err = self.make_span_error( + start, + start_end, + format!("Invalid @let declaration \"{name}\". Declaration must have a value."), + ); + self.errors.push(err); + return None; + } }; // Skip LetEnd or IncompleteLet token. @@ -1395,10 +1592,10 @@ impl<'a> HtmlParser<'a> { let name = token.value().to_string(); let name_string = if name.is_empty() { String::new() } else { format!(" \"{name}\"") }; - // Upstream reports on the token's full sourceSpan; `make_error` gives a - // zero-width span at `start` (pre-existing). - let err = self.make_error( + // Reported over the whole token, as Angular's `_consumeIncompleteLet`. + let err = self.make_span_error( start, + end, format!( "Incomplete @let declaration{name_string}. @let declarations must be written as `@let = ;`" ), @@ -1426,10 +1623,27 @@ impl<'a> HtmlParser<'a> { Some(HtmlNode::LetDeclaration(Box::new_in(let_decl, &self.allocator))) } - /// Parses an ICU expansion form. + /// Parses an ICU expansion form. ICUs are parsed recursively, so this bounds + /// the recursion: an ICU and each of its cases are a level each, and past + /// `max_depth`, the rest of the input is skipped. fn parse_expansion(&mut self) -> Option> { + if self.icu_depth * 2 >= self.max_depth { + let start = self.peek()?.start; + self.too_deep.get_or_insert(start); + self.errors_before_skip.get_or_insert(self.errors.len()); + self.index = self.tokens.len(); + return None; + } + self.icu_depth += 1; + let node = self.parse_expansion_form(); + self.icu_depth -= 1; + node + } + + fn parse_expansion_form(&mut self) -> Option> { let start_token = self.advance()?; // consume ExpansionFormStart let start = start_token.start; + self.check_depth(start); // Get switch value (RawText) let (switch_value, switch_value_span) = if let Some(tok) = self.peek() { @@ -1458,34 +1672,26 @@ impl<'a> HtmlParser<'a> { String::new() }; - // Parse cases + // Parse cases. As Angular's `_consumeExpansion`, a case with an error drops + // the whole expansion, and anything but its `}` after the cases is an error. let mut cases = Vec::new_in(&self.allocator); - while let Some(tok) = self.peek() { - if tok.token_type == HtmlTokenType::ExpansionFormEnd { - break; - } - - if tok.token_type == HtmlTokenType::ExpansionCaseValue { - if let Some(case) = self.parse_expansion_case() { - cases.push(case); - } - } else { - // Skip unexpected tokens - self.advance(); - } + while self.peek().is_some_and(|tok| tok.token_type == HtmlTokenType::ExpansionCaseValue) { + cases.push(self.parse_expansion_case()?); } // Consume ExpansionFormEnd - let end = if let Some(tok) = self.peek() { - if tok.token_type == HtmlTokenType::ExpansionFormEnd { + let end = match self.peek() { + Some(tok) if tok.token_type == HtmlTokenType::ExpansionFormEnd => { let e = tok.end; self.advance(); e - } else { - self.peek().map(|t| t.start).unwrap_or(start) } - } else { - start + tok => { + let (at, at_end) = tok.map_or((start, start), |t| (t.start, t.end)); + let err = self.make_span_error(at, at_end, "Invalid ICU message. Missing '}'."); + self.errors.push(err); + return None; + } }; let span = self.make_span(start, end); @@ -1515,17 +1721,34 @@ impl<'a> HtmlParser<'a> { let value_span = self.make_span(value_start, value_end); // Consume ExpansionCaseExpStart - let exp_start = if let Some(tok) = self.peek() { - if tok.token_type == HtmlTokenType::ExpansionCaseExpStart { - let s = tok.end; - self.advance(); - s - } else { - value_end + let (brace_start, exp_start) = match self.peek() { + Some(tok) if tok.token_type == HtmlTokenType::ExpansionCaseExpStart => { + (tok.start, tok.end) + } + tok => { + let (at, at_end) = tok.map_or((value_end, value_end), |t| (t.start, t.end)); + let err = self.make_span_error(at, at_end, "Invalid ICU message. Missing '{'."); + self.errors.push(err); + return None; + } + }; + // As Angular's `_collectExpansionExpTokens`, find the case's `}` first. A case + // without it is reported at its `{` and its tokens are dropped unparsed. + let case_end = match self.collect_expansion_case(self.index) { + Ok(end) => end, + Err(stop) => { + self.index = stop; + let err = self.make_span_error( + brace_start, + exp_start, + "Invalid ICU message. Missing '}'.", + ); + self.errors.push(err); + return None; } - } else { - value_end }; + self.advance(); + let errors_before = self.errors.len(); // Parse expansion content in isolation // Following Angular's approach: save current state, parse content, restore state @@ -1533,19 +1756,30 @@ impl<'a> HtmlParser<'a> { let saved_root_nodes = std::mem::take(&mut self.root_nodes); let saved_container_stack = std::mem::take(&mut self.container_stack); let saved_elements = std::mem::take(&mut self.elements); + let saved_element_ns = std::mem::take(&mut self.element_ns); let saved_blocks = std::mem::take(&mut self.blocks); + let saved_block_ns = std::mem::take(&mut self.block_ns); + // The case's nodes are inside the set-aside containers, the ICU and the case. + let saved_outer_depth = self.outer_depth; + self.outer_depth += saved_container_stack.len() + 2; + + // Parse content until the case's `}`. Angular runs a full `_TreeBuilder` + // over the case body, so blocks, @let declarations and comments get real + // nodes — and an `IncompleteBlockOpen` produces its "Incomplete block" + // diagnostic instead of being skipped silently. The tokens a nested ICU + // with an error leaves unread are read here as that builder reads them. + while self.index < case_end { + self.parse_and_add_node(); + } - // Parse content until ExpansionCaseExpEnd. Angular runs a full - // `_TreeBuilder` over the case body, so blocks, @let declarations and - // comments get real nodes — and an `IncompleteBlockOpen` produces its - // "Incomplete block" diagnostic instead of being skipped silently. - while let Some(tok) = self.peek() { - match tok.token_type { - HtmlTokenType::ExpansionCaseExpEnd | HtmlTokenType::ExpansionFormEnd => break, - _ => self.parse_and_add_node(), + // A block left open at the case's `}` is unclosed, same as at EOF in the + // main loop (Angular builds the case with its own `_TreeBuilder`). + for container in &self.container_stack { + if let ContainerIndex::Block(idx) = *container { + let err = self.unclosed_block_error(&self.blocks[idx]); + self.errors.push(err); } } - // Close any unclosed elements within this expansion case while let Some(container) = self.container_stack.pop() { match container { @@ -1570,14 +1804,6 @@ impl<'a> HtmlParser<'a> { self.add_to_parent(HtmlNode::Element(Box::new_in(element, &self.allocator))); } ContainerIndex::Block(idx) => { - // A block left open at the case's `}` is unclosed, same as - // at EOF in the main loop. - let block = &self.blocks[idx]; - let err = self.make_error( - block.span.start, - format!("Unclosed block \"@{}\"", block.name), - ); - self.errors.push(err); let block = std::mem::replace( &mut self.blocks[idx], HtmlBlock { @@ -1600,7 +1826,10 @@ impl<'a> HtmlParser<'a> { let expansion_nodes = std::mem::replace(&mut self.root_nodes, saved_root_nodes); self.container_stack = saved_container_stack; self.elements = saved_elements; + self.element_ns = saved_element_ns; self.blocks = saved_blocks; + self.block_ns = saved_block_ns; + self.outer_depth = saved_outer_depth; // Convert to allocator vec let mut expansion = Vec::new_in(&self.allocator); @@ -1608,18 +1837,13 @@ impl<'a> HtmlParser<'a> { expansion.push(node); } - // Consume ExpansionCaseExpEnd - let exp_end = if let Some(tok) = self.peek() { - if tok.token_type == HtmlTokenType::ExpansionCaseExpEnd { - let e = tok.end; - self.advance(); - e - } else { - self.peek().map(|t| t.start).unwrap_or(exp_start) - } - } else { - exp_start - }; + // Consume ExpansionCaseExpEnd. A case whose content has an error drops the + // expansion, as Angular's `_parseExpansionCase`. + self.index = case_end; + let exp_end = self.advance().map_or(exp_start, |tok| tok.end); + if self.errors.len() > errors_before { + return None; + } let span = self.make_span(case_start, exp_end); let expansion_span = self.make_span(exp_start, exp_end); @@ -1633,6 +1857,47 @@ impl<'a> HtmlParser<'a> { }) } + /// Angular's `_collectExpansionExpTokens`: the index of the `ExpansionCaseExpEnd` + /// that closes the case opened at `start` (an `ExpansionCaseExpStart`), or the + /// index where the case breaks off (a `}` closing something else, or EOF). + /// + /// The ends of the cases nested inside are stored on the way, so a nested case + /// (which cannot break off when its parent did not) is not scanned again. + fn collect_expansion_case(&mut self, start: usize) -> Result { + if let Some(&end) = self.case_ends.get(&start) { + return Ok(end); + } + let mut stack = vec![(HtmlTokenType::ExpansionCaseExpStart, start)]; + let mut i = start + 1; + loop { + let Some(tok) = self.tokens.get(i) else { return Err(i.min(self.tokens.len())) }; + match tok.token_type { + HtmlTokenType::ExpansionFormStart | HtmlTokenType::ExpansionCaseExpStart => { + stack.push((tok.token_type, i)); + } + HtmlTokenType::ExpansionCaseExpEnd => match stack.last() { + Some(&(HtmlTokenType::ExpansionCaseExpStart, open)) => { + stack.pop(); + self.case_ends.insert(open, i); + if stack.is_empty() { + return Ok(i); + } + } + _ => return Err(i), + }, + HtmlTokenType::ExpansionFormEnd => match stack.last() { + Some(&(HtmlTokenType::ExpansionFormStart, _)) => { + stack.pop(); + } + _ => return Err(i), + }, + HtmlTokenType::Eof => return Err(i), + _ => {} + } + i += 1; + } + } + /// Consumes a block open (@if, @for, etc.) and pushes it onto the container stack. fn read_block_open(&mut self) -> HtmlBlock<'a> { // Callers dispatch on a peeked token, so there is always one to consume. @@ -1659,7 +1924,7 @@ impl<'a> HtmlParser<'a> { "loading" => BlockType::Loading, "boundary" => BlockType::Boundary, "error" => BlockType::Error, - _ => BlockType::If, // Default + _ => BlockType::Unknown, }; // Collect block parameters @@ -1865,16 +2130,33 @@ impl<'a> HtmlParser<'a> { let end = token.end; let end_span = self.make_span(start, end); + // The innermost open element, which Angular names when the `}` closes it. + let top_element = match self.container_stack.last() { + Some(&ContainerIndex::Element(idx)) => { + Some(self.open_element_full_name(self.container_stack.len() - 1, idx)) + } + _ => None, + }; + // Pop the block from the stack and add it to the parent - if let Some(node) = self.pop_block_container(Some(end_span)) { + let (node, unexpected_close) = self.pop_block_container(Some(end_span)); + let found = node.is_some(); + let forgotten = if unexpected_close { top_element } else { None }; + if let Some(node) = node { self.add_to_parent(node); - } else { - // No matching block - report error - let err = self.make_error( + } + if !found || unexpected_close { + let hint = forgotten + .map(|name| format!("Did you forget to close the <{name}> element? ")) + .unwrap_or_default(); + let err = self.make_span_error( start, - "Unexpected closing block. The block may have been closed earlier. \ - If you meant to write the } character, you should use the \"}\" \ - HTML entity instead.", + end, + format!( + "Unexpected closing block. The block may have been closed earlier. \ + {hint}If you meant to write the `}}` character, you should use the \ + \"}\" HTML entity instead." + ), ); self.errors.push(err); } diff --git a/crates/oxc_angular_compiler/src/parser/mod.rs b/crates/oxc_angular_compiler/src/parser/mod.rs index e1e49835f..84da39d9b 100644 --- a/crates/oxc_angular_compiler/src/parser/mod.rs +++ b/crates/oxc_angular_compiler/src/parser/mod.rs @@ -8,6 +8,99 @@ pub mod expression; pub mod html; +/// How deep an expression may nest. +/// +/// The depth is that of its tree: `(a)` is 3 deep (the parentheses, the read of `a`, +/// and the implicit receiver `a` is read from), and a chain such as `a + b + c` is +/// as deep as its nested form `(a + b) + c`. A deeper expression is not compiled: it +/// is reported with [`MAX_CALL_STACK_ERROR`]. +/// +/// The compiler walks expressions recursively, so a limit keeps any input from +/// overflowing the call stack. ngc (on Node's default stack) overflows its own +/// stack on expressions about 370 to 950 deep, depending on their shape, so every +/// expression ngc compiles is below this limit. +/// +/// An expression at the limit needs a large stack (see [`MAX_TEMPLATE_DEPTH`]). +pub const MAX_EXPRESSION_DEPTH: usize = 2000; + +/// How deep a template may nest. +/// +/// Elements, blocks, ICUs and ICU cases inside each other count, and so do the +/// branches of one `@if` / `@else if` chain and the cases of one `@switch`, which +/// compile to nested conditional expressions. A deeper template is not compiled: it +/// is reported with [`MAX_CALL_STACK_ERROR`]. +/// +/// ngc overflows its stack on templates about 670 to 900 deep, and on chains of a +/// few thousand `@else if` or `@case` branches. +/// +/// Compiling a template or expression near these limits needs a larger stack than +/// a thread's default (2 MiB for Rust threads, 8 MiB for most main threads): up to +/// about 20 MiB in an optimized build. A Rust caller that may get such input can do +/// as the NAPI binding does: compile with lower limits ([`with_depth_limits`]), and +/// only when the input nests deeper, again on a thread with a large stack. +pub const MAX_TEMPLATE_DEPTH: usize = 2000; + +/// The error for an expression or template nested deeper than +/// [`MAX_EXPRESSION_DEPTH`] or [`MAX_TEMPLATE_DEPTH`]: the text of the error ngc +/// reports when its stack overflows on one. +pub const MAX_CALL_STACK_ERROR: &str = "RangeError: Maximum call stack size exceeded"; + +/// How deep templates and expressions may nest on a thread (see +/// [`with_depth_limits`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DepthLimits { + /// How deep a template may nest: [`MAX_TEMPLATE_DEPTH`] or less. + pub template: usize, + /// How deep an expression may nest: [`MAX_EXPRESSION_DEPTH`] or less. + pub expression: usize, +} + +impl DepthLimits { + /// The limits outside [`with_depth_limits`]. + pub const MAX: Self = Self { template: MAX_TEMPLATE_DEPTH, expression: MAX_EXPRESSION_DEPTH }; +} + +thread_local! { + static DEPTH_LIMITS: std::cell::Cell = const { std::cell::Cell::new(DepthLimits::MAX) }; + static DEPTH_LIMIT_REACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The depth limits in force on this thread. +pub(crate) fn depth_limits() -> DepthLimits { + DEPTH_LIMITS.get() +} + +/// Records that the input nests deeper than a limit of [`depth_limits`]. +pub(crate) fn depth_limit_reached() { + DEPTH_LIMIT_REACHED.set(true); +} + +/// Runs `f` (a compilation) with lower depth limits, so that it needs little stack. +/// +/// The stack a compilation needs grows with how deep its input nests, and at +/// [`DepthLimits::MAX`] it is more than most threads have. With lower limits, a +/// compilation can run on any thread: `Ok` is its result when the input nests no +/// deeper than `limits`. `Err` is its result when the input nests deeper (it reports +/// the input as too deep): run `f` again on a thread with a large stack, without +/// these limits, for the real result. +/// +/// # Errors +/// +/// `Err` holds `f`'s result when the input nests deeper than `limits`. +pub fn with_depth_limits(limits: DepthLimits, f: impl FnOnce() -> T) -> Result { + /// Puts the thread's limits back, even if `f` panics. + struct Restore(DepthLimits, bool); + impl Drop for Restore { + fn drop(&mut self) { + DEPTH_LIMITS.set(self.0); + DEPTH_LIMIT_REACHED.set(self.1); + } + } + let _restore = Restore(DEPTH_LIMITS.replace(limits), DEPTH_LIMIT_REACHED.replace(false)); + let value = f(); + if DEPTH_LIMIT_REACHED.get() { Err(value) } else { Ok(value) } +} + /// Template parsing options. /// /// These options control how the template parser processes HTML templates. diff --git a/crates/oxc_angular_compiler/src/pipeline/ingest.rs b/crates/oxc_angular_compiler/src/pipeline/ingest.rs index 67610b7b0..4d0592aac 100644 --- a/crates/oxc_angular_compiler/src/pipeline/ingest.rs +++ b/crates/oxc_angular_compiler/src/pipeline/ingest.rs @@ -1354,10 +1354,14 @@ fn ingest_element<'a>( // Start i18n block if element has i18n Message metadata AND has children. // Skip i18n for elements with no content (e.g., self-closing elements with i18n attr). + // An ngNonBindable element is the exception: its message comes from its HTML + // children, and its ICU children are dropped from the R3 children + // (`NonBindableVisitor.visitExpansion`), so Angular still starts the block for it. // Ported from Angular's ingest.ts lines 300-307 let i18n_block_id = if let Some(I18nMeta::Message(ref message)) = element.i18n { - // Only create i18n block if there are children to translate - if element.children.is_empty() { + let non_bindable_with_message = !message.message_string.is_empty() + && element.attributes.iter().any(|attr| attr.name.as_str() == "ngNonBindable"); + if element.children.is_empty() && !non_bindable_with_message { None } else { let i18n_xref = job.allocate_xref_id(); diff --git a/crates/oxc_angular_compiler/src/pipeline/phases/i18n_closure.rs b/crates/oxc_angular_compiler/src/pipeline/phases/i18n_closure.rs index c8f86f6b1..869ea6d2a 100644 --- a/crates/oxc_angular_compiler/src/pipeline/phases/i18n_closure.rs +++ b/crates/oxc_angular_compiler/src/pipeline/phases/i18n_closure.rs @@ -455,7 +455,14 @@ pub fn generate_closure_var_name( /// /// Replaces non-alphanumeric characters with underscores. fn sanitize_identifier(s: &str) -> String { - s.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect() + use crate::util::lone_surrogate::{Piece, pieces}; + // A stored lone surrogate (`util::lone_surrogate`) is one code unit. + pieces(s) + .map(|piece| match piece { + Piece::Char(c) if c.is_ascii_alphanumeric() => c, + _ => '_', + }) + .collect() } /// Generates a file-based i18n suffix from a file path. diff --git a/crates/oxc_angular_compiler/src/pipeline/phases/naming.rs b/crates/oxc_angular_compiler/src/pipeline/phases/naming.rs index 27b9ca4a9..813c7b7eb 100644 --- a/crates/oxc_angular_compiler/src/pipeline/phases/naming.rs +++ b/crates/oxc_angular_compiler/src/pipeline/phases/naming.rs @@ -31,7 +31,15 @@ use crate::pipeline::phases::parse_extracted_styles::hyphenate; /// `is_ascii_alphanumeric()` and not Rust's `is_alphanumeric()` (which accepts /// Unicode letters/digits and would diverge for non-ASCII trigger names). fn sanitize_identifier(name: &str) -> String { - name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect() + use crate::util::lone_surrogate::{Piece, pieces}; + // A stored lone surrogate (`util::lone_surrogate`) is the one code unit + // Angular's `/\W/g` replaces. + pieces(name) + .map(|piece| match piece { + Piece::Char(c) if c.is_ascii_alphanumeric() || c == '_' => c, + _ => '_', + }) + .collect() } /// State for generating unique variable names. diff --git a/crates/oxc_angular_compiler/src/transform/control_flow.rs b/crates/oxc_angular_compiler/src/transform/control_flow.rs index 4172943e8..420317923 100644 --- a/crates/oxc_angular_compiler/src/transform/control_flow.rs +++ b/crates/oxc_angular_compiler/src/transform/control_flow.rs @@ -102,8 +102,9 @@ fn parse_for_of_expression(s: &str) -> Option<(&str, &str)> { return None; // No whitespace after "of" } + // As `match[2].trim().length === 0` in Angular's `parseForLoopParameters`. let expression = after_of.trim_start(); - if expression.is_empty() { + if expression.trim_end().is_empty() { return None; } @@ -144,9 +145,9 @@ fn parse_let_expression(s: &str) -> Option<&str> { } /// Parse time value pattern: `^\d+\.?\d*(ms|s)?$` -/// Returns true if the string is a valid time value. +/// Returns true if the string is a valid time value. Like Angular's `TIME_PATTERN`, it +/// allows no whitespace around the value. fn is_valid_time_pattern(s: &str) -> bool { - let s = s.trim(); if s.is_empty() { return false; } @@ -361,21 +362,11 @@ pub fn parse_for_loop_parameters<'a>( // Parse "item of items" let expr_str = expression_param.expression.as_str(); - let Some(stripped) = strip_optional_parentheses(expr_str, expression_param.span, &mut errors) + let stripped = strip_optional_parentheses(expr_str, expression_param.span, &mut errors); + // Pattern: "item of items". Unclosed parentheses (reported above) do not match + // either, as in Angular's `parseForLoopParameters`. + let Some((item_name_str, raw_expression_str)) = stripped.and_then(parse_for_of_expression) else { - // Unclosed parentheses error was added in strip_optional_parentheses - return ForLoopParams { - item: create_empty_variable(allocator, block_start_span), - expression: create_empty_ast_with_source(allocator, block_start_span), - track_by: None, - context_variables: create_default_context_variables(allocator, block_start_span), - errors, - expression_parse_failed: true, - }; - }; - - // Pattern: "item of items" - let Some((item_name_str, raw_expression_str)) = parse_for_of_expression(&stripped) else { errors.push(BlockParamError::new( expression_param.span, "Cannot parse expression. @for loop expression must match the pattern \" of \"", @@ -728,24 +719,22 @@ fn parse_expression_to_ast_with_source<'a>( } } -/// Strips ALL optional parentheses from a for loop expression. -/// E.g., "(item of items)" -> "item of items" -/// E.g., "(( (item of items) ))" -> "item of items" +/// Strips ALL optional parentheses from a for loop expression, as Angular's +/// `stripOptionalParentheses`: "(item of items)" -> "item of items". The text inside +/// is kept as written, and without leading `(` the expression is returned unchanged. /// /// Returns `None` if there are unclosed parentheses (error added to `errors`, at `span`). -fn strip_optional_parentheses( - expr: &str, +fn strip_optional_parentheses<'s>( + expr: &'s str, span: Span, errors: &mut std::vec::Vec, -) -> Option { - let trimmed = expr.trim(); - let chars: std::vec::Vec = trimmed.chars().collect(); +) -> Option<&'s str> { let mut open_parens = 0; let mut start = 0; - let mut end = chars.len(); + let mut end = expr.len().saturating_sub(1); // Count leading parens - for (i, &c) in chars.iter().enumerate() { + for (i, c) in expr.char_indices() { if c == '(' { open_parens += 1; start = i + 1; @@ -755,18 +744,18 @@ fn strip_optional_parentheses( } if open_parens == 0 { - return Some(trimmed.to_string()); + return Some(expr); } // Find matching closing parens - for i in (0..chars.len()).rev() { - if chars[i] == ')' { + for (i, c) in expr.char_indices().rev() { + if c == ')' { open_parens -= 1; end = i; if open_parens == 0 { break; } - } else if !chars[i].is_whitespace() { + } else if !c.is_whitespace() { break; } } @@ -777,9 +766,7 @@ fn strip_optional_parentheses( return None; } - // Collect and trim the inner content - let inner: String = chars[start..end].iter().collect(); - Some(inner.trim().to_string()) + Some(expr.get(start..end).unwrap_or("")) } /// Checks if an expression contains a pipe (full recursive traversal matching Angular's visitor). @@ -866,26 +853,22 @@ impl DeferTriggerError { } // Pattern matching functions for Angular's r3_deferred_blocks.ts -// These handle whitespace/newlines between keywords correctly. -// -// The HTML lexer trims block parameters, while Angular matches its patterns -// against the untrimmed text. `has_trailing_ws` restores the trimmed trailing -// whitespace, so that e.g. `on ` matches `^on\s` but `on` does not. +// These handle whitespace/newlines between keywords correctly. Block parameters +// keep their text as written, so e.g. `on ` matches `^on\s` but `on` does not. /// Pattern `^keyword\s`. -fn starts_with_keyword(s: &str, keyword: &str, has_trailing_ws: bool) -> bool { - s.strip_prefix(keyword) - .is_some_and(|rest| rest.chars().next().map_or(has_trailing_ws, char::is_whitespace)) +fn starts_with_keyword(s: &str, keyword: &str) -> bool { + s.strip_prefix(keyword).is_some_and(|rest| rest.starts_with(char::is_whitespace)) } /// Pattern `^first\s+second\s`. -fn starts_with_keyword_pair(s: &str, first: &str, second: &str, has_trailing_ws: bool) -> bool { +fn starts_with_keyword_pair(s: &str, first: &str, second: &str) -> bool { let Some(after_first) = s.strip_prefix(first) else { return false; }; let trimmed = after_first.trim_start(); // Must have at least one whitespace after the first keyword - trimmed.len() != after_first.len() && starts_with_keyword(trimmed, second, has_trailing_ws) + trimmed.len() != after_first.len() && starts_with_keyword(trimmed, second) } /// Pattern to identify a `hydrate never` trigger: `^hydrate\s+never(\s*)$`. @@ -946,27 +929,25 @@ pub fn parse_defer_triggers<'a>( for param in parameters { let expr = param.expression.as_str(); let span = param.span; - // The parameter span still covers the whitespace trimmed off the expression. - let has_trailing_ws = span.size() as usize > expr.len(); let param = TriggerParameter { expression: expr, span }; // Match against patterns in the same order as Angular's TypeScript implementation // Reference: r3_deferred_blocks.ts parsePrimaryTriggers - if starts_with_keyword(expr, "when", has_trailing_ws) { + if starts_with_keyword(expr, "when") { parse_when_trigger(¶m, binding_parser, &mut triggers, &mut errors); - } else if starts_with_keyword(expr, "on", has_trailing_ws) { + } else if starts_with_keyword(expr, "on") { on_trigger(¶m, &mut triggers, &mut errors); - } else if starts_with_keyword_pair(expr, "prefetch", "when", has_trailing_ws) { + } else if starts_with_keyword_pair(expr, "prefetch", "when") { parse_when_trigger(¶m, binding_parser, &mut prefetch_triggers, &mut errors); - } else if starts_with_keyword_pair(expr, "prefetch", "on", has_trailing_ws) { + } else if starts_with_keyword_pair(expr, "prefetch", "on") { on_trigger(¶m, &mut prefetch_triggers, &mut errors); - } else if starts_with_keyword_pair(expr, "hydrate", "when", has_trailing_ws) { + } else if starts_with_keyword_pair(expr, "hydrate", "when") { parse_when_trigger(¶m, binding_parser, &mut hydrate_triggers, &mut errors); - } else if starts_with_keyword_pair(expr, "hydrate", "on", has_trailing_ws) { + } else if starts_with_keyword_pair(expr, "hydrate", "on") { on_trigger(¶m, &mut hydrate_triggers, &mut errors); } else if is_hydrate_never_pattern(expr) { parse_never_trigger(¶m, &mut hydrate_triggers, &mut errors); - } else if supports_name && starts_with_keyword(expr, "name", has_trailing_ws) { + } else if supports_name && starts_with_keyword(expr, "name") { // `NAME_PARAMETER_PATTERN` (`/^name\s+/`) in r3_deferred_blocks.ts. if defined_name.is_some() { errors @@ -1023,9 +1004,9 @@ fn has_other_hydrate_triggers(triggers: &R3DeferredBlockTriggers<'_>) -> bool { /// A `@defer` block parameter holding a trigger. struct TriggerParameter<'a> { - /// The (trimmed) parameter text. + /// The parameter text. expression: &'a str, - /// The parameter span, including trimmed trailing whitespace. + /// The parameter span. span: Span, } @@ -1235,16 +1216,11 @@ fn comma_delimited_closer(token: &Token<'_>) -> Option { } } -/// Angular's `Token.toString()`, used in "Unexpected token" errors. +/// Angular's `Token.toString()`, used in "Unexpected token" errors: a number's JavaScript +/// text (`1e+21`), else the token's text (a template literal part's too, a string token in +/// Angular). fn token_text(token: &Token<'_>) -> String { - match token.token_type { - TokenType::Number => token.num_value.to_string(), - TokenType::NoSubstitutionTemplate - | TokenType::TemplateHead - | TokenType::TemplateMiddle - | TokenType::TemplateTail => "null".to_string(), - _ => token.str_value.to_string(), - } + token.message_text() } impl<'a> OnTriggerParser<'_, 'a> { @@ -1707,8 +1683,6 @@ fn angular_ast_class_name(expr: &AngularExpression<'_>) -> &'static str { /// Parses a time value like "500ms" or "1.5s" to milliseconds. /// Returns f64 to preserve fractional precision (matching Angular's parseFloat behavior). fn parse_deferred_time(value: &str) -> Option { - let value = value.trim(); - if !is_valid_time_pattern(value) { return None; } @@ -1766,15 +1740,20 @@ mod tests { let mut errors = std::vec::Vec::new(); assert_eq!( strip_optional_parentheses("item of items", Span::default(), &mut errors), - Some("item of items".to_string()) + Some("item of items") ); assert_eq!( strip_optional_parentheses("(item of items)", Span::default(), &mut errors), - Some("item of items".to_string()) + Some("item of items") ); + // As Angular's `stripOptionalParentheses`, the text inside is kept as written. assert_eq!( strip_optional_parentheses(" ( item of items ) ", Span::default(), &mut errors), - Some("item of items".to_string()) + Some(" item of items ") + ); + assert_eq!( + strip_optional_parentheses("(x of a) ", Span::default(), &mut errors), + Some("x of a") ); assert!(errors.is_empty()); @@ -1806,8 +1785,10 @@ mod tests { // No unit defaults to ms assert_eq!(parse_deferred_time("500"), Some(500.0)); - // With whitespace - assert_eq!(parse_deferred_time(" 500ms "), Some(500.0)); + // Angular's `TIME_PATTERN` allows no whitespace (a parameter is the text of its + // tokens, so it only has some after a lexer error, as in `timer(~ 1)`) + assert_eq!(parse_deferred_time(" 500ms "), None); + assert_eq!(parse_deferred_time(" 1"), None); // Invalid assert_eq!(parse_deferred_time("abc"), None); diff --git a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs index 54cb55562..e7ce20a6c 100644 --- a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs +++ b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs @@ -35,6 +35,7 @@ use crate::parser::expression::{ BindingParser, blank_interpolation_error, comment_only_interpolation_error, is_comment_only, }; use crate::parser::html::{decode_entities_in_string, get_html_tag_definition, split_ns_name}; +use crate::parser::{MAX_CALL_STACK_ERROR, depth_limit_reached, depth_limits}; use crate::schema::{ element_security_context_for, is_known_element, is_trusted_types_sink_at, strips_namespaced_svg_script, strips_namespaced_svg_style, uses_namespaced_schema, @@ -344,6 +345,9 @@ pub struct HtmlToR3Transform<'a> { /// Parse errors. /// Uses std::vec::Vec since ParseError contains Drop types (Arc, String). errors: std::vec::Vec, + /// The start of the first `@switch` with more cases than the template depth + /// limit: it is left out, and reported if the template has no other errors. + too_many_cases: Option, styles: Vec<'a, Ident<'a>>, style_urls: Vec<'a, Ident<'a>>, ng_content_selectors: Vec<'a, Ident<'a>>, @@ -508,6 +512,7 @@ impl<'a> HtmlToR3Transform<'a> { source_text, binding_parser: BindingParser::new(allocator), errors: std::vec::Vec::new(), + too_many_cases: None, styles: Vec::new_in(&allocator), style_urls: Vec::new_in(&allocator), ng_content_selectors: Vec::new_in(&allocator), @@ -605,6 +610,14 @@ impl<'a> HtmlToR3Transform<'a> { pub fn transform(mut self, html_nodes: &[HtmlNode<'a>]) -> R3ParseResult<'a> { let nodes = self.visit_siblings(html_nodes); + // ngc's stack overflows on such a `@switch` only when it prints the compiled + // output, which it does only for a template without errors. + if let Some(start) = self.too_many_cases + && self.errors.is_empty() + { + self.report_error(MAX_CALL_STACK_ERROR, Span::new(start, start)); + } + R3ParseResult { nodes, errors: self.errors, @@ -688,6 +701,8 @@ impl<'a> HtmlToR3Transform<'a> { } self.visit_let_declaration(decl) } + // Angular's `NonBindableVisitor.visitExpansion` drops an ICU (and its errors). + HtmlNode::Expansion(_) if self.non_bindable_depth > 0 => None, HtmlNode::Expansion(expansion) => self.visit_expansion(expansion), HtmlNode::ExpansionCase(_) => { // Expansion cases are handled within visit_expansion @@ -879,8 +894,12 @@ impl<'a> HtmlToR3Transform<'a> { (String::new(), Vec::new_in(&self.allocator), Ident::from("")) }; - // Now create the i18n metadata with the generated message string - let i18n_meta = if let Some(attr) = i18n_attr { + // Now create the i18n metadata with the generated message string. An element + // inside an ngNonBindable element has none: Angular's `NonBindableVisitor` + // builds it without its i18n. + let i18n_meta = if self.non_bindable_depth > 0 { + None + } else if let Some(attr) = i18n_attr { // Element has its own i18n attribute - parse it as a Message with message string let instance_id = self.allocate_i18n_message_instance_id(); let mut meta = parse_i18n_meta_with_message( @@ -2531,8 +2550,9 @@ impl<'a> HtmlToR3Transform<'a> { ))) } BlockType::Switch => self.visit_switch_block(block), - BlockType::Case | BlockType::Default => { - // Standalone @case/@default outside @switch - emit error and create UnknownBlock + BlockType::Case | BlockType::Default | BlockType::Unknown => { + // Standalone @case/@default outside @switch, or a block with an unknown + // name - emit error and create UnknownBlock // Reference: r3_template_transform.ts:518 - falls through to "Unrecognized block" self.report_error(&format!("Unrecognized block @{}.", block.name), block.span); Some(R3Node::UnknownBlock(Box::new_in( @@ -2775,6 +2795,12 @@ impl<'a> HtmlToR3Transform<'a> { block: &HtmlBlock<'a>, connected_blocks: &[&HtmlBlock<'a>], ) -> Option> { + // The branches compile to nested conditional expressions. + if connected_blocks.len() >= depth_limits().template { + depth_limit_reached(); + self.report_error(MAX_CALL_STACK_ERROR, Span::new(block.span.start, block.span.start)); + return None; + } let mut branches = Vec::new_in(&self.allocator); // Parse the main @if branch parameters (condition and optional "as" alias) @@ -3084,6 +3110,20 @@ impl<'a> HtmlToR3Transform<'a> { use crate::ast::html::{BlockType, HtmlNode}; use crate::ast::r3::{R3SwitchBlockCase, R3SwitchBlockCaseGroup, R3SwitchExhaustiveCheck}; + // The cases compile to nested conditional expressions. + let case_count = block + .children + .iter() + .filter(|node| { + matches!(node, HtmlNode::Block(case) if matches!(case.block_type, BlockType::Case | BlockType::Default)) + }) + .count(); + let too_many_cases = case_count > depth_limits().template; + if too_many_cases { + depth_limit_reached(); + self.too_many_cases.get_or_insert(block.span.start); + } + // Validation: @switch must have exactly one parameter. // Match Angular's createSwitchBlock: always parse the first parameter when present // (even if there are extra parameters), only use empty when there are no parameters. @@ -3320,6 +3360,10 @@ impl<'a> HtmlToR3Transform<'a> { end_source_span: block.end_span, name_span: block.name_span, }; + // Left out, so that nothing compiles it (see `too_many_cases`). + if too_many_cases { + return None; + } Some(R3Node::SwitchBlock(Box::new_in(switch_block, &self.allocator))) } @@ -4674,6 +4718,16 @@ impl<'a> HtmlToR3Transform<'a> { let full_name = expr.key.source.as_str(); let binding_name_atom = Ident::from(self.allocator.alloc_str(full_name)); + // A key with no value (`else` in `*ngIf="c; else"`) is a literal + // attribute, which Angular lists before the bound ones. + if expr.value.is_none() { + attributes.push(Self::template_binding_literal_attr( + binding_name_atom, + Span::new(expr.key.span.start, expr.key.span.end), + )); + continue; + } + let source_span = Span::new(expr.source_span.start, expr.source_span.end); // Parse the expression value from source let expr_value = if let Some(v) = &expr.value { @@ -4763,6 +4817,22 @@ impl<'a> HtmlToR3Transform<'a> { R3Node::Template(Box::new_in(template, &self.allocator)) } + /// Angular's `parseLiteralAttr(key, null, keySpan, ...)` for a microsyntax key with + /// no value: a literal template attribute whose spans are the key's. + /// Reference: binding_parser.ts `parseInlineTemplateBinding`, and + /// r3_template_transform.ts, which puts the literal template attributes before the + /// bound ones (`attrs.literal` then `attrs.bound`). + fn template_binding_literal_attr(name: Ident<'a>, key_span: Span) -> R3TextAttribute<'a> { + R3TextAttribute { + name, + value: Ident::from(""), + source_span: key_span, + key_span: Some(key_span), + value_span: None, + i18n: None, + } + } + /// Wraps a component node in a template for structural directives. /// This is similar to `wrap_in_template` but uses component spans. fn wrap_component_in_template( @@ -4918,6 +4988,14 @@ impl<'a> HtmlToR3Transform<'a> { let full_name = expr.key.source.as_str(); let binding_name_atom = Ident::from(self.allocator.alloc_str(full_name)); + if expr.value.is_none() { + attributes.push(Self::template_binding_literal_attr( + binding_name_atom, + Span::new(expr.key.span.start, expr.key.span.end), + )); + continue; + } + let source_span = Span::new(expr.source_span.start, expr.source_span.end); let expr_value = if let Some(v) = &expr.value { if let Some(src) = &v.source { @@ -5349,115 +5427,93 @@ impl<'a> HtmlToR3Transform<'a> { } } - /// Parses interpolation from tokens, using token spans for correct source positions. - /// This handles the case where HTML entities affect span calculations. + /// Parses the interpolations of a text with an HTML entity, as Angular's + /// `parseInterpolation(text.value, ...)`: the strings and expressions come from the + /// text's value (entities decoded, and whitespace folded unless it was preserved), + /// while the tokens give each expression's template span and offset. fn parse_interpolation_from_tokens( &mut self, text: &HtmlText<'a>, ) -> Option> { use crate::ast::expression::Interpolation; + use crate::parser::expression::Parser; use crate::parser::html::NGSP_UNICODE; - let input = text.value.as_str(); + const START: &str = "{{"; + const END: &str = "}}"; + + let value = text.value.as_str(); + let input: &'a str = if value.contains(NGSP_UNICODE) { + self.allocator.alloc_str(&value.replace(NGSP_UNICODE, " ")) + } else { + value + }; let mut strings = Vec::new_in(&self.allocator); let mut expressions = Vec::new_in(&self.allocator); - - // Helper to accumulate text/entity content before committing to strings array. - // The invariant we maintain: strings.len() == expressions.len() after processing text/entity, - // and strings.len() == expressions.len() + 1 after processing interpolation. - // This ensures the final result has strings.len() == expressions.len() + 1. - let mut current_string = String::new(); - // UTF-16 length of the decoded input before `current_string`, for error columns. - let mut committed_len = 0; + // The interpolation tokens, in order: the `n`th gives the `n`th expression's span. + let mut interpolation_tokens = text.tokens.iter().filter(|token| { + token.token_type == InterpolatedTokenType::Interpolation && token.parts.len() >= 3 + }); let mut index_map: Option = None; + // `(byte offset, UTF-16 index)` in `input` of the last `{{` counted, so the + // columns are counted on from the previous one (linear in the text length). + let mut utf16_cursor = (0usize, 0usize); // Angular's `splitInterpolation` finds the blank `{{ }}`s before any expression is // parsed, so their errors come first; the others are reported in order after them. let mut blank_errors = std::vec::Vec::new(); let mut errors = std::vec::Vec::new(); - for token in &text.tokens { - match token.token_type { - InterpolatedTokenType::Text => { - // Add text part (possibly with ngsp replaced) - if let Some(text_value) = token.parts.first() { - let text_str = text_value.as_str(); - if text_str.contains(NGSP_UNICODE) { - current_string.push_str(&text_str.replace(NGSP_UNICODE, " ")); - } else { - current_string.push_str(text_str); - } - } - } - InterpolatedTokenType::Interpolation => { - // Interpolation token has parts = [startMarker, expression, endMarker] - if token.parts.len() >= 3 { - let start_marker = &token.parts[0]; - let expr_content = &token.parts[1]; - let end_marker = &token.parts[2]; - let column = committed_len + current_string.encode_utf16().count(); - - // Before adding an expression, commit the current string buffer - // (even if empty, we need a string before each expression) - strings.push(Ident::from_in(current_string.as_str(), &self.allocator)); - current_string.clear(); - - // Calculate the expression span from the token span - // Token span covers the whole interpolation: {{expr}} - // Expression span is token.span.start + start_marker.len() to - // token.span.end - end_marker.len() - let expr_start = token.span.start + start_marker.len() as u32; - let expr_end = token.span.end - end_marker.len() as u32; - let expr_span = Span::new(expr_start, expr_end); - - // For backward compatibility, decode HTML entities in interpolation - // expressions. This matches Angular's behavior where entities like - // × inside string literals in interpolations are decoded. - let decoded_expr = decode_entities_in_string(expr_content.as_str()); - committed_len = column - + start_marker.encode_utf16().count() - + decoded_expr.encode_utf16().count() - + end_marker.encode_utf16().count(); - // Angular's `splitInterpolation` reports `{{ }}` and still parses it; - // `parseInterpolation` reports an expression that is only a comment. - // Both are reported at the whole value. - if decoded_expr.trim().is_empty() { - blank_errors.push(ParseError::new( - crate::util::ParseSourceSpan::default(), - blank_interpolation_error(column, input), - )); - } - if is_comment_only(&decoded_expr) { - errors.push(( - vec![ParseError::new( - crate::util::ParseSourceSpan::default(), - comment_only_interpolation_error(column, input), - )], - text.span, - )); - } - let expr_str = self.allocator.alloc_str(&decoded_expr); - let offset = index_map - .get_or_insert_with(|| TemplateIndexMap::new(&text.tokens)) - .get(column) - + start_marker.as_str().encode_utf16().count(); - let parse_result = self - .binding_parser - .parse_interpolation_part(expr_str, expr_span, offset); - let at = - interpolation_error_span(&text.tokens, expressions.len(), text.span); - errors.push((parse_result.errors, at)); - expressions.push(parse_result.ast); - } - } - InterpolatedTokenType::EncodedEntity => { - // Encoded entity token has parts = [decoded, encoded] - // Append the decoded value to the current string buffer - if let Some(decoded) = token.parts.first() { - current_string.push_str(decoded.as_str()); - } - } + // Angular's `splitInterpolation`: a `{{` with no `}}` after it is text. + let mut pos = 0; + while let Some(found) = input[pos..].find(START) { + let full_start = pos + found; + let expr_start = full_start + START.len(); + let Some(expr_len) = Parser::find_interpolation_end(&input[expr_start..], END) else { + break; + }; + let expr_end = expr_start + expr_len; + strings.push(Ident::from_in(&input[pos..full_start], self.allocator)); + pos = expr_end + END.len(); + + utf16_cursor.1 += input[utf16_cursor.0..full_start].encode_utf16().count(); + utf16_cursor.0 = full_start; + let column = utf16_cursor.1; + + let expr_text = &input[expr_start..expr_end]; + // Angular's `splitInterpolation` reports `{{ }}` and still parses it; + // `parseInterpolation` reports an expression that is only a comment. + // Both are reported at the whole value. + if expr_text.trim().is_empty() { + blank_errors.push(ParseError::new( + crate::util::ParseSourceSpan::default(), + blank_interpolation_error(column, input), + )); + } + if is_comment_only(expr_text) { + errors.push(( + vec![ParseError::new( + crate::util::ParseSourceSpan::default(), + comment_only_interpolation_error(column, input), + )], + text.span, + )); } + + // The expression's template span, inside the interpolation token's markers. + let expr_span = interpolation_tokens.next().map_or(text.span, |token| { + let start = token.span.start + token.parts[0].len() as u32; + let end = token.span.end.saturating_sub(token.parts[2].len() as u32); + Span::new(start, end.max(start)) + }); + let offset = + index_map.get_or_insert_with(|| TemplateIndexMap::new(&text.tokens)).get(column) + + START.len(); + let parse_result = + self.binding_parser.parse_interpolation_part(expr_text, expr_span, offset); + let at = interpolation_error_span(&text.tokens, expressions.len(), text.span); + errors.push((parse_result.errors, at)); + expressions.push(parse_result.ast); } self.report_expression_errors(blank_errors, text.span); @@ -5469,8 +5525,8 @@ impl<'a> HtmlToR3Transform<'a> { return None; } - // Commit the trailing string (after the last expression) - strings.push(Ident::from_in(current_string.as_str(), &self.allocator)); + // The text after the last expression (with any unclosed `{{`). + strings.push(Ident::from_in(&input[pos..], self.allocator)); // Create the Interpolation expression let span = ParseSpan::new(0, text.span.end - text.span.start); diff --git a/crates/oxc_angular_compiler/src/util/chars.rs b/crates/oxc_angular_compiler/src/util/chars.rs index b9add654d..351d86f30 100644 --- a/crates/oxc_angular_compiler/src/util/chars.rs +++ b/crates/oxc_angular_compiler/src/util/chars.rs @@ -94,18 +94,6 @@ pub fn is_digit(ch: char) -> bool { ch.is_ascii_digit() } -/// Checks if a character is a hexadecimal digit (0-9, a-f, A-F). -#[inline] -pub fn is_ascii_hex_digit(ch: char) -> bool { - ch.is_ascii_hexdigit() -} - -/// Checks if a character is an octal digit (0-7). -#[inline] -pub fn is_octal_digit(ch: char) -> bool { - matches!(ch, '0'..='7') -} - /// Checks if a character can start an identifier. #[inline] pub fn is_identifier_start(ch: char) -> bool { diff --git a/crates/oxc_angular_compiler/src/util/deferred_time.rs b/crates/oxc_angular_compiler/src/util/deferred_time.rs index 8ec3c9906..0d9fef048 100644 --- a/crates/oxc_angular_compiler/src/util/deferred_time.rs +++ b/crates/oxc_angular_compiler/src/util/deferred_time.rs @@ -23,9 +23,10 @@ /// assert_eq!(parse_deferred_time("100"), Some(100)); // default to ms /// assert_eq!(parse_deferred_time("invalid"), None); /// ``` +/// +/// As Angular's `TIME_PATTERN` (`/^\d+\.?\d*(ms|s)?$/`), whitespace around the +/// value does not match: `@placeholder (minimum 1s )` is an error. pub fn parse_deferred_time(value: &str) -> Option { - let value = value.trim(); - if value.is_empty() { return None; } @@ -114,7 +115,8 @@ mod tests { #[test] fn test_parse_deferred_time_with_whitespace() { - assert_eq!(parse_deferred_time(" 500ms "), Some(500)); - assert_eq!(parse_deferred_time(" 1s "), Some(1000)); + // Angular's `TIME_PATTERN` is anchored at both ends. + assert_eq!(parse_deferred_time(" 500ms "), None); + assert_eq!(parse_deferred_time("1s "), None); } } diff --git a/crates/oxc_angular_compiler/src/util/lone_surrogate.rs b/crates/oxc_angular_compiler/src/util/lone_surrogate.rs index 6099a85cb..8c608c5b6 100644 --- a/crates/oxc_angular_compiler/src/util/lone_surrogate.rs +++ b/crates/oxc_angular_compiler/src/util/lone_surrogate.rs @@ -40,6 +40,12 @@ pub(crate) fn js_str_to_str(value: JSStr<'_>) -> Cow<'_, str> { Cow::Owned(out) } +/// Lone surrogate code unit `unit` as it is stored in a `&str`. +pub fn stored(unit: u16) -> String { + let offset = u32::from(unit).saturating_sub(0xD800); + [MARK, char::from_u32(BASE + offset).unwrap_or(MARK)].into_iter().collect() +} + /// [`js_str_to_str`] as an [`Ident`]. pub(crate) fn js_str_to_ident<'a>(value: JSStr<'a>, allocator: &'a Allocator) -> Ident<'a> { match js_str_to_str(value) { @@ -77,7 +83,9 @@ pub(crate) fn has_lone_surrogate(s: &str) -> bool { } /// The UTF-16 code units of `s`, with each stored lone surrogate as its unit. -pub(crate) fn encode_utf16(s: &str) -> impl Iterator + '_ { +/// +/// The NAPI binding uses it to hand such a string to JavaScript as it is. +pub fn encode_utf16(s: &str) -> impl Iterator + '_ { pieces(s) .flat_map(|piece| match piece { Piece::Lone(unit) => [Some(unit), None], @@ -90,6 +98,40 @@ pub(crate) fn encode_utf16(s: &str) -> impl Iterator + '_ { .flatten() } +/// Adds the lone surrogate `unit` (`0xD800..=0xDFFF`) to `out`, stored as described above. +pub fn push_lone_surrogate(out: &mut String, unit: u16) { + out.push(MARK); + out.push(char::from_u32(BASE + u32::from(unit.saturating_sub(0xD800))).unwrap_or(MARK)); +} + +/// The length of `s` in UTF-16 code units, a stored lone surrogate counting +/// as the one unit it stands for (as JavaScript's `length`). +pub fn utf16_len(s: &str) -> usize { + if s.contains(MARK) { encode_utf16(s).count() } else { s.encode_utf16().count() } +} + +/// Whether `first` followed by `second` is a stored lone surrogate. +pub fn is_stored(first: char, second: char) -> bool { + first == MARK && stored_unit(second).is_some() +} + +/// `s` with each stored lone surrogate as U+FFFD, the character a lone +/// surrogate turns into when JavaScript writes the string as UTF-8 (as +/// `TextEncoder` and a terminal do). +pub fn lossy(s: &str) -> Cow<'_, str> { + if !has_lone_surrogate(s) { + return Cow::Borrowed(s); + } + Cow::Owned( + pieces(s) + .map(|piece| match piece { + Piece::Char(c) => c, + Piece::Lone(_) => char::REPLACEMENT_CHARACTER, + }) + .collect(), + ) +} + /// The lone code unit the second character `c` of a stored one stands for. fn stored_unit(c: char) -> Option { // `BASE + 0x7FF` is `U+10FFFF`, the last code point. @@ -115,6 +157,18 @@ mod tests { assert_eq!(encode_utf16(&text).collect::>(), [0x78, 0x2D, 0xD800, 0x2D, 0xDFFF]); } + #[test] + fn counts_and_prints_a_lone_surrogate_as_one_unit() { + let text = format!("a{}😀", stored(0xD83D)); + assert_eq!(utf16_len(&text), 4); + assert_eq!(lossy(&text), "a\u{FFFD}😀"); + let mut chars = text.chars().skip(1); + assert!(is_stored(chars.next().unwrap(), chars.next().unwrap())); + assert!(!is_stored(MARK, 'a')); + assert_eq!(utf16_len("a😀"), 3); + assert!(matches!(lossy("\u{FDD0}a"), Cow::Borrowed("\u{FDD0}a"))); + } + #[test] fn leaves_other_strings_alone() { assert!(matches!(js_str_to_str(JSStr::from("a😀\u{FFFD}")), Cow::Borrowed("a😀\u{FFFD}"))); diff --git a/crates/oxc_angular_compiler/tests/deep_nesting_test.rs b/crates/oxc_angular_compiler/tests/deep_nesting_test.rs new file mode 100644 index 000000000..6cd0af0c3 --- /dev/null +++ b/crates/oxc_angular_compiler/tests/deep_nesting_test.rs @@ -0,0 +1,461 @@ +//! Deeply nested templates and expressions. +//! +//! The compiler recurses over templates and expressions, so a deep enough one used +//! to overflow the stack and abort the process. Now a template or expression nested +//! deeper than `MAX_TEMPLATE_DEPTH` / `MAX_EXPRESSION_DEPTH` is reported with the +//! error ngc reports when its own stack overflows (`RangeError: Maximum call stack +//! size exceeded`), and everything below the limits compiles, which covers all that +//! ngc compiles (ngc overflows below 1000 levels). +//! +//! Compiling near the limits needs a large stack (unoptimized test builds use very +//! large frames), so those tests run on a thread with one, as the NAPI binding does. + +use std::collections::HashMap; +use std::fmt::Write; + +use oxc_allocator::Allocator; +use oxc_angular_compiler::parser::expression::{BindingParser, Lexer}; +use oxc_angular_compiler::parser::html::HtmlParser; +use oxc_angular_compiler::parser::{ + DepthLimits, MAX_CALL_STACK_ERROR, MAX_EXPRESSION_DEPTH, MAX_TEMPLATE_DEPTH, with_depth_limits, +}; +use oxc_angular_compiler::{ + AngularExpression, ResolvedResources, TransformOptions, transform_angular_file, +}; +use oxc_span::Span; + +/// Runs `f` on a thread with a stack of `size` bytes. +fn on_stack(size: usize, f: impl FnOnce() -> T + Send) -> T { + std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(size) + .spawn_scoped(scope, f) + .expect("thread starts") + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + }) +} + +/// The NAPI binding's stack size for unoptimized builds. +const LARGE_STACK: usize = 1 << 30; + +/// A Rust thread's default stack size. +const DEFAULT_STACK: usize = 2 << 20; + +/// `(message, labelled text)` of each diagnostic of a component with `template` +/// inline, and the output code. +fn compile_inline(template: &str) -> (Vec<(String, Vec)>, String) { + let source = format!( + "import {{ Component }} from '@angular/core';\n\ + @Component({{ selector: 'x-cut', template: `{template}` }})\n\ + export class Cut {{ a: any; b: any; f(x: any) {{ return x; }} }}\n" + ); + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let result = transform_angular_file(&allocator, "/x/cut.ts", &source, Some(&options), None); + let diagnostics = result + .diagnostics + .iter() + .map(|d| { + let labels = d + .labels + .iter() + .map(|label| { + let start = label.offset() as usize; + source[start..start + label.len() as usize].to_string() + }) + .collect(); + (d.message.to_string(), labels) + }) + .collect(); + (diagnostics, result.code) +} + +/// The messages of the diagnostics of a component with `template` in a +/// `templateUrl` file. +fn compile_url(template: &str) -> Vec { + let source = "import { Component } from '@angular/core';\n\ + @Component({ selector: 'x-cut', templateUrl: './cut.html' })\n\ + export class Cut { a: any; b: any; f(x: any) { return x; } }\n"; + let resources = ResolvedResources { + templates: HashMap::from([("./cut.html".to_string(), template.to_string())]), + styles: HashMap::new(), + }; + let allocator = Allocator::default(); + let options = TransformOptions::default(); + transform_angular_file(&allocator, "/x/cut.ts", source, Some(&options), Some(&resources)) + .diagnostics + .iter() + .map(|d| d.message.to_string()) + .collect() +} + +/// `@switch (a) { @case (0) {x} … }` with `n` cases. +fn switch(n: usize) -> String { + let mut template = "@switch (a) {".to_string(); + for i in 0..n { + write!(template, "@case ({i}) {{x}}").expect("writes to a string"); + } + template + "}" +} + +fn len(s: &str) -> u32 { + u32::try_from(s.len()).expect("a short text") +} + +fn parens(n: usize) -> String { + format!("{}a{}", "(".repeat(n), ")".repeat(n)) +} + +fn chain(n: usize, term: &str, op: &str) -> String { + vec![term; n].join(op) +} + +fn nested(n: usize, open: &str, inner: &str, close: &str) -> String { + format!("{}{inner}{}", open.repeat(n), close.repeat(n)) +} + +/// The binding that used to abort the process (500 terms), and nested templates and +/// expressions as deep as ngc compiles (each a little deeper than ngc's limit on +/// Node's default stack). +#[test] +fn templates_ngc_compiles_compile() { + let templates = [ + format!(r#"

"#, chain(500, "a.b", " + ")), + format!(r#"

"#, chain(1000, "a", " || ")), + format!("

{{{{ {} }}}}

", chain(700, "a", " ?? ")), + format!(r#"

"#, "a ? b : ".repeat(500)), + format!(r#"

"#, parens(450)), + format!(r#"

"#, ".b".repeat(1000)), + format!(r#"

"#, "?.b".repeat(400)), + format!(r#"

"#, "[0]".repeat(1000)), + format!(r#"

"#, nested(400, "[", "a", "]")), + format!(r#"

"#, nested(400, "{k: ", "a", "}")), + format!(r#"

"#, nested(400, "f(", "a", ")")), + format!(r#"

"#, "!".repeat(700)), + format!(r#"

"#, chain(700, "a", " + ")), + nested(950, "
", "x", "
"), + nested(800, "@if (a) {", "x", "}"), + nested(800, r#"
"#, "x", "
"), + nested(700, "{a, select, x {", "y", "}}"), + format!("@if (a) {{x}}{}", " @else if (b) {x}".repeat(1500)), + switch(1500), + ]; + on_stack(LARGE_STACK, || { + for template in &templates { + let errors = compile_url(template); + assert!(errors.is_empty(), "{}...: {errors:?}", &template[..40]); + } + }); +} + +/// At the limits, a template or expression compiles; one level deeper, it is +/// reported. +#[test] +fn limits_are_exact() { + // `(…(a)…)`: the parentheses, the read of `a` and its implicit receiver. + let expression = |depth: usize| format!(r#"

"#, parens(depth - 2)); + let elements = |depth: usize| nested(depth, "
", "", "
"); + on_stack(LARGE_STACK, || { + assert_eq!(compile_url(&expression(MAX_EXPRESSION_DEPTH)), Vec::::new()); + assert_eq!(compile_url(&expression(MAX_EXPRESSION_DEPTH + 1)), [MAX_CALL_STACK_ERROR]); + assert_eq!(compile_url(&elements(MAX_TEMPLATE_DEPTH)), Vec::::new()); + assert_eq!(compile_url(&elements(MAX_TEMPLATE_DEPTH + 1)), [MAX_CALL_STACK_ERROR]); + let branches = |n: usize| format!("@if (a) {{x}}{}", " @else if (b) {x}".repeat(n - 1)); + assert_eq!(compile_url(&branches(MAX_TEMPLATE_DEPTH)), Vec::::new()); + assert_eq!(compile_url(&branches(MAX_TEMPLATE_DEPTH + 1)), [MAX_CALL_STACK_ERROR]); + assert_eq!(compile_url(&switch(MAX_TEMPLATE_DEPTH)), Vec::::new()); + assert_eq!(compile_url(&switch(MAX_TEMPLATE_DEPTH + 1)), [MAX_CALL_STACK_ERROR]); + }); +} + +/// Too deep an expression is reported as ngc's binding parser reports a parse that +/// overflows its stack: only `RangeError: …` (no error of the parse itself), where +/// that binding's parse errors go. Other bindings keep their errors. ngc 22.3.0 +/// reports the same for these templates. +#[test] +fn too_deep_expressions_are_reported_at_their_binding() { + let deep = parens(3000); + on_stack(LARGE_STACK, || { + // ngc: `cut.html` 12 (length 6001), the value. + let (errors, code) = compile_inline(&format!(r#"

"#)); + assert_eq!(errors, [(MAX_CALL_STACK_ERROR.to_string(), vec![deep.clone()])]); + assert!(!code.contains("ɵɵdefineComponent"), "not compiled"); + // ngc: 14 (6001), past the leading spaces. + let (errors, _) = compile_inline(&format!(r#"

"#)); + assert_eq!(errors, [(MAX_CALL_STACK_ERROR.to_string(), vec![deep.clone()])]); + // ngc: 12 (6001). + let (errors, _) = compile_inline(&format!(r#"

"#)); + assert_eq!(errors, [(MAX_CALL_STACK_ERROR.to_string(), vec![deep.clone()])]); + // ngc: 3 (6009), the attribute. + let (errors, _) = compile_inline(&format!(r#"

"#)); + assert_eq!( + errors, + [(MAX_CALL_STACK_ERROR.to_string(), vec![format!(r#"*ngIf="{deep}""#)])] + ); + // ngc: 14 (6001), twice: the property and the event. + let (errors, _) = compile_inline(&format!(r#"

"#)); + let error = (MAX_CALL_STACK_ERROR.to_string(), vec![deep.clone()]); + assert_eq!(errors, [error.clone(), error.clone()]); + // ngc: 12 (6001), then the other binding's error. + let (errors, _) = compile_inline(&format!(r#"

"#)); + assert_eq!( + errors, + [error, ("Unexpected token 'b' at column 3 in [a b]".to_string(), vec!["a b".into()])] + ); + }); +} + +/// A long chain is parsed by a loop, but nests as deep: `a + a + a` is +/// `(a + a) + a`. Too long a chain is reported without walking the deep tree it +/// parses to, so it is reported even on a default stack. +#[test] +fn too_long_chains_are_reported_on_a_default_stack() { + let templates = [ + format!(r#"

"#, chain(50_000, "a.b", " + ")), + format!("

{{{{ {} }}}}

", chain(50_000, "a", " || ")), + format!(r#"

"#, ".b".repeat(50_000)), + format!(r#"

"#, " | json".repeat(50_000)), + ]; + on_stack(DEFAULT_STACK, || { + for template in &templates { + assert_eq!(compile_url(template), [MAX_CALL_STACK_ERROR], "{}...", &template[..40]); + } + }); +} + +/// The template parser keeps its open elements and blocks in a list, not on the +/// call stack, so too deep a template is reported even on a default stack, at the +/// first node too deep (ngc throws, with no position). (ICUs are parsed +/// recursively: see `icu_cases_count_as_levels`.) +#[test] +fn too_deep_templates_are_reported_on_a_default_stack() { + on_stack(DEFAULT_STACK, || { + let allocator = Allocator::default(); + let template = nested(100_000, "
", "x", "
"); + let result = HtmlParser::new(&allocator, &template, "cut.html").parse(); + let messages: Vec<_> = result.errors.iter().map(|e| e.msg.as_str()).collect(); + assert_eq!(messages, [MAX_CALL_STACK_ERROR]); + assert_eq!( + result.errors[0].span.start.offset, + 5 * u32::try_from(MAX_TEMPLATE_DEPTH).unwrap() + ); + + for template in [ + nested(50_000, "
", "x", "
"), + nested(50_000, "@if (a) {", "x", "}"), + nested(50_000, "", "x", ""), + format!("
{}
", nested(50_000, "", "y", "")), + format!("@if (a) {{x}}{}", " @else if (b) {x}".repeat(50_000)), + switch(50_000), + ] { + assert_eq!(compile_url(&template), [MAX_CALL_STACK_ERROR], "{}...", &template[..40]); + } + }); +} + +/// The template's other errors are reported instead (ngc 22.3.0 reports the same): +/// ngc parses the whole template (its tree builder keeps the open elements in a list +/// too) and stops at its errors, before the step that overflows on a deep template. +#[test] +fn errors_of_deep_templates_are_reported() { + // `Unexpected closing tag "{tag}". It may happen when the tag has already been + // closed by another tag. …`, and nothing else. + let assert_unexpected = |template: &str, tag: &str| { + let errors = compile_url(template); + let start = format!("Unexpected closing tag \"{tag}\". It may happen when the tag"); + assert!( + errors.len() == 1 && errors[0].starts_with(&start), + "{}...: {errors:?}", + &template[..40] + ); + }; + on_stack(DEFAULT_STACK, || { + for n in [2_100, 50_000] { + // Before, inside and after the deep part. + for template in [ + format!("

{}", nested(n, "
", "x", "
")), + format!("

{}", nested(n, "@if (a) {", "x", "}")), + nested(n, "
", "x", "
"), + format!("{}

", nested(n, "
", "x", "
")), + ] { + assert_unexpected(&template, "span"); + } + } + assert_unexpected(&nested(2_100, "
", "", "
"), "div"); + }); + // Before too deep ICUs (they are parsed recursively, and the rest is skipped). + on_stack(LARGE_STACK, || { + let icus = nested(1_100, "{a, select, x {", "y", "}}"); + assert_unexpected(&format!("

{icus}"), "span"); + let icus = nested(50_000, "{a, select, x {", "y", "}}"); + assert_unexpected(&format!("

@if (a) {{{icus}"), "span"); + }); +} + +/// A `@switch` with too many cases is reported only for a template without other +/// errors (ngc overflows only when it prints the compiled output): the errors in +/// its cases and around it are reported instead, as ngc 22.3.0 reports them. +#[test] +fn errors_around_too_many_cases_are_reported() { + let cases = |n: usize| { + (1..=n).fold(String::new(), |mut cases, i| { + write!(cases, "@case ({i}) {{x}}").expect("writes to a string"); + cases + }) + }; + let error = "Unexpected token 'b' at column 4 in [ a b ]"; + on_stack(LARGE_STACK, || { + // ngc: `cut.html:1:25`. + let template = format!("@switch (a) {{@case (0) {{{{{{ a b }}}}}}{}}}", cases(2_100)); + assert_eq!(compile_url(&template), [error]); + // ngc: `1:32511`. + assert_eq!(compile_url(&format!("{}

{{{{ a b }}}}

", switch(2_100))), [error]); + // ngc: `1:4`. + assert_eq!(compile_url(&format!("

{{{{ a b }}}}

{}", switch(2_100))), [error]); + }); +} + +/// The parser's recursion is bounded on every path: a conditional's branches and +/// the right side of `**` nest without an operand around them. +#[test] +fn too_deep_conditionals_and_powers_are_reported() { + let templates = [ + format!(r#"

"#, "a ? b : ".repeat(300_000)), + format!(r#"

"#, "a ? ".repeat(300_000), " : c".repeat(300_000)), + format!("

{{{{ {}c }}}}

", "a ? b : ".repeat(300_000)), + format!("@if ({}c) {{x}}", "a ? b : ".repeat(300_000)), + format!(r#"

"#, chain(1_000_000, "a", " ** ")), + ]; + on_stack(LARGE_STACK, || { + for template in &templates { + assert_eq!(compile_url(template), [MAX_CALL_STACK_ERROR], "{}...", &template[..40]); + } + // As deep as ngc compiles them, and more. + let conditionals = + format!(r#"

"#, "a ? ".repeat(900), " : c".repeat(900)); + assert_eq!(compile_url(&conditionals), Vec::::new()); + let powers = format!(r#"

"#, chain(1_500, "a", " ** ")); + assert_eq!(compile_url(&powers), Vec::::new()); + }); +} + +/// The expression lexer keeps the template literals nested in substitutions in a +/// list, not on the call stack, so any number of them, or of substitutions, is +/// lexed even on a default stack. +#[test] +fn template_literals_are_lexed_on_a_default_stack() { + let nested = format!("`{}a{}`", "${`".repeat(100_000), "`}".repeat(100_000)); + let flat = format!("`{}`", "${a}".repeat(100_000)); + on_stack(DEFAULT_STACK, || { + let allocator = Allocator::default(); + // A head and `${` per level, the innermost template (`a`), then a `}` and a + // tail per level. + assert_eq!(Lexer::new(&allocator, &nested).tokenize().len(), 4 * 100_000 + 1); + // A head, then `${`, `a`, `}` and a middle (or the tail) per substitution. + assert_eq!(Lexer::new(&allocator, &flat).tokenize().len(), 4 * 100_000 + 1); + }); + on_stack(LARGE_STACK, || { + let template = format!(r#"

"#); + assert_eq!(compile_url(&template), [MAX_CALL_STACK_ERROR]); + }); +} + +/// With lower limits (as the NAPI binding first compiles), a compilation needs a +/// small stack: one that nests deeper is cut short and told apart, whatever its +/// shape, and one that does not is compiled as without them. +#[test] +fn lower_limits_need_a_small_stack() { + // The NAPI binding's limits for unoptimized builds (very large stack frames). + let (t, e) = (8, 8); + let limits = DepthLimits { template: t, expression: e }; + let deep = [ + nested(t + 1, "
", "x", "
"), + nested(t / 2 + 1, "{a, select, x {", "y", "}}"), + format!("@if (a) {{x}}{}", " @else if (b) {x}".repeat(t)), + switch(t + 1), + // `e + 1` deep. + format!(r#"

"#, parens(e - 1)), + format!(r#"

"#, chain(e, "a", " + ")), + format!(r#"

"#, "a ? b : ".repeat(e - 1)), + format!(r#"

"#, "a ? ".repeat(e - 1), " : c".repeat(e - 1)), + format!(r#"

"#, chain(e, "a", " ** ")), + // The parse is cut short: the errors after are not found. + format!("

{}", nested(t / 2 + 1, "{a, select, x {", "y", "}}")), + // Too deep even without the lower limits. + nested(100_000, "
", "x", "
"), + format!(r#"

"#, "a ? b : ".repeat(300_000)), + format!(r#"

"#, parens(100_000)), + format!(r#"

"#, chain(100_000, "a.b", " + ")), + ]; + let shallow = [ + nested(t, "
", "x", "
"), + nested(t / 2, "{a, select, x {", "y", "}}"), + format!("@if (a) {{x}}{}", " @else if (b) {x}".repeat(t - 1)), + switch(t), + format!(r#"

"#, parens(e - 2)), + format!(r#"

"#, chain(e - 1, "a", " + ")), + format!(r#"

"#, "a ? b : ".repeat(e - 2)), + format!(r#"

"#, chain(e - 1, "a", " ** ")), + "

".to_string(), + // The errors are all found, and nothing compiles the deep part. + format!("

{}", nested(t + 1, "
", "x", "
")), + format!("{}", nested(10 * t, "@if (a) {", "x", "}")), + ]; + on_stack(DEFAULT_STACK, || { + for template in &deep { + let result = with_depth_limits(limits, || compile_url(template)); + assert!(result.is_err(), "{}...: {result:?}", &template[..30]); + } + for template in &shallow { + let result = with_depth_limits(limits, || compile_url(template)); + assert_eq!(result, Ok(compile_url(template)), "{}...", &template[..30]); + } + // The limits apply only inside. + assert_eq!(compile_url(&deep[0]), Vec::::new()); + }); +} + +/// An ICU and each of its cases are a level each. +#[test] +fn icu_cases_count_as_levels() { + let icus = |n: usize| nested(n, "{a, select, x {", "y", "}}"); + on_stack(LARGE_STACK, || { + assert_eq!(compile_url(&icus(MAX_TEMPLATE_DEPTH / 2)), Vec::::new()); + assert_eq!(compile_url(&icus(MAX_TEMPLATE_DEPTH / 2 + 1)), [MAX_CALL_STACK_ERROR]); + assert_eq!(compile_url(&icus(50_000)), [MAX_CALL_STACK_ERROR]); + }); +} + +/// The expression parser gives Angular's result for a parse that overflows: an +/// `'ERROR'` literal, and only the error; microsyntax gives no bindings. +#[test] +fn too_deep_parse_results() { + on_stack(LARGE_STACK, || { + let allocator = Allocator::default(); + let parser = BindingParser::new(&allocator); + let deep = parens(MAX_EXPRESSION_DEPTH); + + let result = parser.parse_binding(&deep, Span::new(0, len(&deep))); + let messages: Vec<_> = result.errors.iter().map(|e| e.msg.as_str()).collect(); + assert_eq!(messages, [MAX_CALL_STACK_ERROR]); + assert!(matches!(&result.ast, AngularExpression::LiteralPrimitive(_))); + + let result = parser.parse_event(&deep, Span::new(0, len(&deep))); + let messages: Vec<_> = result.errors.iter().map(|e| e.msg.as_str()).collect(); + assert_eq!(messages, [MAX_CALL_STACK_ERROR]); + + // The blank interpolation's error is not reported either. + let text = format!("{{{{ }}}} {{{{ {deep} }}}}"); + let result = parser + .parse_default_interpolation(&text, Span::new(0, len(&text)), vec![]) + .expect("an interpolation"); + let messages: Vec<_> = result.errors.iter().map(|e| e.msg.as_str()).collect(); + assert_eq!(messages, [MAX_CALL_STACK_ERROR]); + + let span = Span::new(0, len(&deep)); + let result = parser.parse_template_bindings("ngIf", &deep, Span::new(0, 4), span); + assert!(result.bindings.is_empty()); + assert_eq!(result.errors, [MAX_CALL_STACK_ERROR]); + }); +} diff --git a/crates/oxc_angular_compiler/tests/expression_lexer_error_text_test.rs b/crates/oxc_angular_compiler/tests/expression_lexer_error_text_test.rs new file mode 100644 index 000000000..360897360 --- /dev/null +++ b/crates/oxc_angular_compiler/tests/expression_lexer_error_text_test.rs @@ -0,0 +1,1001 @@ +//! The expression lexer works as Angular's: its errors are error tokens with Angular's +//! text (`Lexer Error: ... at column N in expression [input]`, N in UTF-16 units), and +//! the parser reports each one when it reaches it, as Angular's does (so the count and +//! the order follow the parse). Numbers and strings read as Angular reads them. + +use std::collections::HashMap; + +use oxc_allocator::Allocator; +use oxc_angular_compiler::parser::expression::{Lexer, TokenType}; +use oxc_angular_compiler::{ResolvedResources, TransformOptions, transform_angular_file}; + +/// A template and each error it gives: the message (without Angular's `Parser Error: ` +/// prefix and ` in file@line:col` suffix) and the `line:column` in the `templateUrl` file. +type Case = (&'static str, &'static [(&'static str, &'static str)]); + +/// Each error, in order, `parseTemplate` from `@angular/compiler` 22.3.0 gives for the +/// template. +const ANGULAR_ERRORS: &[Case] = &[ + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b]' at column 4 in [a ~ b]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:9", + ), + ], + ), + ( + "{{ a ~ b }}", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 4 in expression [ a ~ b ]' at column 5 in [ a ~ b ]", + "1:1", + ), + ( + "Lexer Error: Unexpected character [~] at column 4 in expression [ a ~ b ] at the end of the expression [ a ~ b ]", + "1:1", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b]' at column 4 in [a ~ b]", + "1:13", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:13", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b], expected identifier, keyword, or string at column 4 in [a ~ b]", + "1:4", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:4", + ), + ], + ), + ( + "@if (a ~ b) {x}", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b]' at column 4 in [a ~ b]", + "1:6", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:6", + ), + ], + ), + ( + "{a ~ b, plural, =0 {x}}", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b]' at column 4 in [a ~ b]", + "1:2", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:2", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid character [#] at column 4 in expression [a + #] at column 5 in [a + #]", + "1:9", + ), + ( + "Lexer Error: Invalid character [#] at column 4 in expression [a + #] at the end of the expression [a + #]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid character [#] at column 0 in expression [#] at column 1 in [#]", + "1:9", + ), + ( + "Lexer Error: Invalid character [#] at column 0 in expression [#] at column 1 in [#]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid numeric separator at column 1 in expression [1_] at column 2 in [1_]", + "1:9", + ), + ( + "Lexer Error: Invalid numeric separator at column 1 in expression [1_] at column 2 in [1_]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid numeric separator at column 1 in expression [1__0] at column 2 in [1__0]", + "1:9", + ), + ( + "Lexer Error: Invalid numeric separator at column 1 in expression [1__0] at column 2 in [1__0]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid numeric separator at column 2 in expression [1._5] at column 3 in [1._5]", + "1:9", + ), + ( + "Lexer Error: Invalid numeric separator at column 2 in expression [1._5] at the end of the expression [1._5]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated quote at column 4 in expression ['abc] at column 5 in ['abc]", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 4 in expression ['abc] at the end of the expression ['abc]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated quote at column 4 in expression [\"abc] at column 5 in [\"abc]", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 4 in expression [\"abc] at the end of the expression [\"abc]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid unicode escape [\\u12'] at column 2 in expression ['\\u12'] at column 3 in ['\\u12']", + "1:9", + ), + ( + "Lexer Error: Invalid unicode escape [\\u12'] at column 2 in expression ['\\u12'] at column 7 in ['\\u12']", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 6 in expression ['\\u12'] at the end of the expression ['\\u12']", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid unicode escape [\\u{41}] at column 2 in expression ['\\u{41}'] at column 3 in ['\\u{41}']", + "1:9", + ), + ( + "Lexer Error: Invalid unicode escape [\\u{41}] at column 2 in expression ['\\u{41}'] at column 4 in ['\\u{41}']", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 8 in expression ['\\u{41}'] at the end of the expression ['\\u{41}']", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid unicode escape [\\u'] at column 2 in expression ['\\u'] at column 3 in ['\\u']", + "1:9", + ), + ( + "Lexer Error: Invalid unicode escape [\\u'] at column 2 in expression ['\\u'] at column 5 in ['\\u']", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 4 in expression ['\\u'] at the end of the expression ['\\u']", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated quote at column 4 in expression ['a\\] at column 5 in ['a\\]", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 4 in expression ['a\\] at the end of the expression ['a\\]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [\u{e9}] at column 1 in expression [\u{e9} +] at column 2 in [\u{e9} +]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{e9}] at column 1 in expression [\u{e9} +] at column 3 in [\u{e9} +]", + "1:9", + ), + ], + ), + ( + "{\u{e9} +, plural, =0 {x}}", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [\u{e9}] at column 1 in expression [\u{e9} +] at column 2 in [\u{e9} +]", + "1:2", + ), + ( + "Lexer Error: Unexpected character [\u{e9}] at column 1 in expression [\u{e9} +] at column 3 in [\u{e9} +]", + "1:2", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [\u{e9}] at column 3 in expression [a.\u{e9}], expected identifier or keyword at column 4 in [a.\u{e9}]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{e9}] at column 3 in expression [a.\u{e9}] at the end of the expression [a.\u{e9}]", + "1:9", + ), + ("Expected identifier for property access at column 2 in [a.\u{e9}]", "1:9"), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [\u{65e5}] at column 1 in expression [\u{65e5}\u{672c}] at column 2 in [\u{65e5}\u{672c}]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{65e5}] at column 1 in expression [\u{65e5}\u{672c}] at column 3 in [\u{65e5}\u{672c}]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{672c}] at column 2 in expression [\u{65e5}\u{672c}] at the end of the expression [\u{65e5}\u{672c}]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ("Missing expected } at column 6 in [`${a b`]", "1:9"), + ( + "Lexer Error: Unterminated template literal at column 7 in expression [`${a b`] at the end of the expression [`${a b`]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated template literal at column 2 in expression [`a] at column 3 in [`a]", + "1:9", + ), + ( + "Lexer Error: Unterminated template literal at column 2 in expression [`a] at the end of the expression [`a]", + "1:9", + ), + ], + ), + ( + "

", + &[( + "Lexer Error: Unterminated template literal at column 5 in expression [`${a}] at column 6 in [`${a}]", + "1:9", + )], + ), + ( + "

", + &[ + ("Missing expected } at column 7 in [`${a ~}b`]", "1:9"), + ( + "Lexer Error: Unexpected character [~] at column 6 in expression [`${a ~}b`] at the end of the expression [`${a ~}b`]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid exponent at column 2 in expression [1.e] at column 3 in [1.e]", + "1:9", + ), + ( + "Lexer Error: Invalid exponent at column 2 in expression [1.e] at the end of the expression [1.e]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid exponent at column 1 in expression [1e] at column 2 in [1e]", + "1:9", + ), + ( + "Lexer Error: Invalid exponent at column 1 in expression [1e] at the end of the expression [1e]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid exponent at column 2 in expression [1e+] at column 3 in [1e+]", + "1:9", + ), + ( + "Lexer Error: Invalid exponent at column 2 in expression [1e+] at the end of the expression [1e+]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid exponent at column 1 in expression [1ex] at column 2 in [1ex]", + "1:9", + ), + ( + "Lexer Error: Invalid exponent at column 1 in expression [1ex] at column 3 in [1ex]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [.] at column 2 in expression [..] at column 3 in [..]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [.] at column 2 in expression [..] at the end of the expression [..]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [.] at column 3 in expression [a..b]' at column 4 in [a..b]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [.] at column 3 in expression [a..b] at the end of the expression [a..b]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [@] at column 1 in expression [@] at column 2 in [@]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [@] at column 1 in expression [@] at the end of the expression [@]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [\\] at column 1 in expression [\\\\] at column 2 in [\\\\]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\\] at column 1 in expression [\\\\] at column 3 in [\\\\]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\\] at column 2 in expression [\\\\] at the end of the expression [\\\\]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b ~ c]' at column 4 in [a ~ b ~ c]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b ~ c] at column 8 in [a ~ b ~ c]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 7 in expression [a ~ b ~ c] at the end of the expression [a ~ b ~ c]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b; c ~ d]' at column 4 in [a ~ b; c ~ d]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b; c ~ d] at column 6 in [a ~ b; c ~ d]", + "1:9", + ), + ("Unexpected token ; at column 6 in [a ~ b; c ~ d]", "1:9"), + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 10 in expression [a ~ b; c ~ d]' at column 11 in [a ~ b; c ~ d]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 10 in expression [a ~ b; c ~ d] at the end of the expression [a ~ b; c ~ d]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [~] at column 6 in expression [f(a, ~, b)] at column 7 in [f(a, ~, b)]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 6 in expression [f(a, ~, b)] at column 9 in [f(a, ~, b)]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b ]' at column 4 in [a ~ b // c]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b ] at the end of the expression [a ~ b // c]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid numeric separator at column 5 in expression [a = 1_; b ~] at column 6 in [a = 1_; b ~]", + "1:13", + ), + ( + "Lexer Error: Invalid numeric separator at column 5 in expression [a = 1_; b ~] at column 9 in [a = 1_; b ~]", + "1:13", + ), + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 11 in expression [a = 1_; b ~]' at column 12 in [a = 1_; b ~]", + "1:13", + ), + ( + "Lexer Error: Unexpected character [~] at column 11 in expression [a = 1_; b ~] at the end of the expression [a = 1_; b ~]", + "1:13", + ), + ], + ), + ("

", &[("Unexpected token 'x10' at column 2 in [0x10]", "1:9")]), + ("

", &[("Unexpected token 'b11' at column 2 in [0b11]", "1:9")]), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated regular expression at column 4 in expression [/abc] at column 5 in [/abc]", + "1:9", + ), + ( + "Lexer Error: Unterminated regular expression at column 4 in expression [/abc] at the end of the expression [/abc]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unsupported regular expression flag \"x\". The supported flags are: \"d\", \"g\", \"i\", \"m\", \"s\", \"u\", \"v\", \"y\" at the end of the expression [/a/xq]", + "1:9", + ), + ( + "Unsupported regular expression flag \"q\". The supported flags are: \"d\", \"g\", \"i\", \"m\", \"s\", \"u\", \"v\", \"y\" at the end of the expression [/a/xq]", + "1:9", + ), + ], + ), + ( + "

", + &[("Duplicate regular expression flag \"g\" at the end of the expression [/a/gg]", "1:9")], + ), + ("

", &[("Unexpected token / at column 8 in [typeof /a/]", "1:9")]), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ (b]' at column 4 in [a ~ (b]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ (b] at column 6 in [a ~ (b]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a\u{a0}~]' at column 4 in [a\u{a0}~]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a\u{a0}~] at the end of the expression [a\u{a0}~]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [\u{2028}] at column 2 in expression [a\u{2028}b]' at column 3 in [a\u{2028}b]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{2028}] at column 2 in expression [a\u{2028}b] at column 3 in [a\u{2028}b]", + "1:9", + ), + ], + ), + ( + "@defer (on ~) {x}", + &[( + "Unexpected token \"Lexer Error: Unexpected character [~] at column 1 in expression [~]\"", + "1:13", + )], + ), + ("@defer (on 1e21) {x}", &[("Unexpected token \"1e+21\"", "1:12")]), + ("@defer (on 100000000000000000000000) {x}", &[("Unexpected token \"1e+23\"", "1:12")]), + ("@defer (on `abc`) {x}", &[("Unexpected token \"abc\"", "1:12")]), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [~] at column 12 in expression [let x of a ~ b], expected identifier, keyword, or string at column 13 in [let x of a ~ b]", + "1:4", + ), + ( + "Lexer Error: Unexpected character [~] at column 12 in expression [let x of a ~ b] at the end of the expression [let x of a ~ b]", + "1:4", + ), + ], + ), + ( + "@let v = a ~ b;", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b]' at column 4 in [a ~ b]", + "1:10", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:10", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token 'Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b]' at column 4 in [a ~ b]", + "1:7", + ), + ( + "Lexer Error: Unexpected character [~] at column 3 in expression [a ~ b] at the end of the expression [a ~ b]", + "1:7", + ), + ], + ), + // `\u` with fewer than four digits at the end still reads, and the lexer moves on + // five places, past the end of the input. + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated quote at column 7 in expression ['\\u41] at column 8 in ['\\u41]", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 7 in expression ['\\u41] at the end of the expression ['\\u41]", + "1:9", + ), + ], + ), + // A lexer error token is a parameter's first token, so the parameter's text starts + // with the space after the bad character, which Angular's `TIME_PATTERN` rejects. + ("@defer (on timer(~ 1)) {x}", &[("Could not parse time value of trigger \"timer\"", "1:12")]), + ("@defer (on timer(é 1)) {x}", &[("Could not parse time value of trigger \"timer\"", "1:12")]), + ("@defer (on idle(~ 1)) {x}", &[("Could not parse time value of trigger \"idle\"", "1:12")]), +]; + +/// Templates where ours knowingly differs from Angular 22.3.0, with what ours reports. +const KNOWN_DIFFERENCES: &[Case] = &[ + // Angular reads the halves of `😀` one at a time, and prints each as a lone + // surrogate (which a terminal shows as U+FFFD); a Rust string holds U+FFFD. + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unexpected character [\u{fffd}] at column 5 in expression [a + \u{1f600}] at column 6 in [a + \u{1f600}]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{fffd}] at column 5 in expression [a + \u{1f600}] at the end of the expression [a + \u{1f600}]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{fffd}] at column 6 in expression [a + \u{1f600}] at the end of the expression [a + \u{1f600}]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Invalid unicode escape [\\u12\u{1f600}] at column 2 in expression ['\\u12\u{1f600}'] at column 3 in ['\\u12\u{1f600}']", + "1:9", + ), + ( + "Lexer Error: Invalid unicode escape [\\u12\u{1f600}] at column 2 in expression ['\\u12\u{1f600}'] at column 7 in ['\\u12\u{1f600}']", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{fffd}] at column 6 in expression ['\\u12\u{1f600}'] at the end of the expression ['\\u12\u{1f600}']", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{fffd}] at column 7 in expression ['\\u12\u{1f600}'] at the end of the expression ['\\u12\u{1f600}']", + "1:9", + ), + ( + "Lexer Error: Unterminated quote at column 8 in expression ['\\u12\u{1f600}'] at the end of the expression ['\\u12\u{1f600}']", + "1:9", + ), + ], + ), + // A token holding a lone surrogate: Angular's message holds the code unit, which + // ngc's UTF-8 output prints as U+FFFD; a Rust string holds U+FFFD, as above. + ( + "@let v = 1'\\uD83D';", + &[("Unexpected token '\u{fffd}' at column 2 in [1'\\uD83D']", "1:10")], + ), + ( + "@if (?? |'\\uD83D' '\\u12') {x}", + &[ + ("Unexpected token ?? at column 1 in [?? |'\\uD83D' '\\u12']", "1:6"), + ( + "Unexpected token \u{fffd}, expected identifier or keyword at column 5 in [?? |'\\uD83D' '\\u12']", + "1:6", + ), + ( + "Lexer Error: Invalid unicode escape [\\u12'] at column 15 in expression [?? |'\\uD83D' '\\u12'] at the end of the expression [?? |'\\uD83D' '\\u12']", + "1:6", + ), + ( + "Lexer Error: Unterminated quote at column 19 in expression [?? |'\\uD83D' '\\u12'] at the end of the expression [?? |'\\uD83D' '\\u12']", + "1:6", + ), + ], + ), + ( + "@defer (on b'\\uD83D') {x}", + &[("Unexpected token \"\u{fffd}\"", "1:13"), ("Unexpected token \"\u{fffd}\"", "1:13")], + ), + ("@defer (on '\\uD83D'+) {x}", &[("Unexpected token \"\u{fffd}\"", "1:12")]), + // Angular's parser does not check that `u` and `v` go together; ours keeps the + // error it reported before. + ( + "

", + &[( + "Regular expression flags 'u' and 'v' cannot be used together at column 4 in [/a/uv]", + "1:9", + )], + ), + ( + "

", + &[( + "Regular expression flags 'u' and 'v' cannot be used together at column 4 in [/a/uv + b]", + "1:9", + )], + ), + // Angular reads a line break inside a regex as part of it, and ngc then emits + // invalid JavaScript (`/a\nb/`) with no error. We report the regex as unterminated, + // as we did before. The HTML parser turns CRLF into LF first. + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated regular expression at column 2 in expression [/a\nb/] at column 3 in [/a\nb/]", + "1:9", + ), + ( + "Lexer Error: Unterminated regular expression at column 2 in expression [/a\nb/] at column 5 in [/a\nb/]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated regular expression at column 3 in expression [/a\\\nb/] at column 4 in [/a\\\nb/]", + "1:9", + ), + ( + "Lexer Error: Unterminated regular expression at column 3 in expression [/a\\\nb/] at the end of the expression [/a\\\nb/]", + "1:9", + ), + ], + ), + ( + "

", + &[ + ( + "Unexpected token Lexer Error: Unterminated regular expression at column 3 in expression [/[a\u{2028}]/] at column 4 in [/[a\u{2028}]/]", + "1:9", + ), + ( + "Lexer Error: Unterminated regular expression at column 3 in expression [/[a\u{2028}]/] at column 6 in [/[a\u{2028}]/]", + "1:9", + ), + ( + "Lexer Error: Unexpected character [\u{2028}] at column 4 in expression [/[a\u{2028}]/] at the end of the expression [/[a\u{2028}]/]", + "1:9", + ), + ], + ), +]; + +/// Each error `template` gives through a `templateUrl`: its message and `line:column`. +fn errors(template: &str) -> Vec<(String, String)> { + let source = "import { Component } from '@angular/core'; +@Component({ selector: 'x-cut', templateUrl: './cut.html' }) +export class Cut { value = 1 } +"; + let mut templates = HashMap::new(); + templates.insert("./cut.html".to_string(), template.to_string()); + let resources = ResolvedResources { templates, styles: HashMap::new() }; + let allocator = Allocator::default(); + let options = TransformOptions::default(); + transform_angular_file(&allocator, "/x/cut.ts", source, Some(&options), Some(&resources)) + .diagnostics + .iter() + .map(|diagnostic| { + let help = diagnostic.help.as_deref().unwrap_or_default(); + let position = help.strip_prefix("./cut.html:").unwrap_or(help); + (diagnostic.message.to_string(), position.to_string()) + }) + .collect() +} + +fn mismatches(cases: &[Case]) -> Vec { + cases + .iter() + .filter_map(|(template, expected)| { + let expected: Vec<(String, String)> = + expected.iter().map(|(m, at)| (m.to_string(), at.to_string())).collect(); + let actual = errors(template); + (actual != expected) + .then(|| format!("{template:?}\n expected: {expected:?}\n actual: {actual:?}")) + }) + .collect() +} + +#[test] +fn lexer_errors_match_angular() { + let mismatches = mismatches(ANGULAR_ERRORS); + assert!( + mismatches.is_empty(), + "{} of {}:\n{}", + mismatches.len(), + ANGULAR_ERRORS.len(), + mismatches.join("\n") + ); +} + +#[test] +fn lexer_errors_that_knowingly_differ_from_angular() { + let mismatches = mismatches(KNOWN_DIFFERENCES); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +/// The value of the only token of `text`, which must be a number. +fn number(text: &str) -> f64 { + let allocator = Allocator::default(); + let tokens = Lexer::new(&allocator, text).tokenize(); + let [token] = tokens.as_slice() else { panic!("{text:?}: {} tokens", tokens.len()) }; + assert_eq!(token.token_type, TokenType::Number, "{text:?}"); + assert_eq!((token.index, token.end), (0, u32::try_from(text.len()).unwrap()), "{text:?}"); + token.num_value +} + +/// Numbers read as Angular's `parseInt` / `parseFloat` read them. +#[test] +fn numbers_read_like_javascript() { + for (text, value) in [ + ("100000000000000000000000", 1e23), + ("123456789012345678901234567890", 1.234_567_890_123_456_8e29), + ("9007199254740993", 9_007_199_254_740_992.0), + ("007", 7.0), + ("1_000", 1000.0), + ("1_000.5_5", 1000.55), + ("0.1", 0.1), + (".5", 0.5), + ("1.", 1.0), + ("1e21", 1e21), + ("1e400", f64::INFINITY), + ("5e-324", 5e-324), + // `parseFloat` reads the longest prefix that is a number. + ("1.2.3", 1.2), + ("1e5e5", 1e5), + ("1e5.5", 1e5), + ("1.e5", 1e5), + ] { + assert_eq!(number(text), value, "{text:?}"); + } +} + +/// Angular has no hexadecimal, octal or binary numbers: `0x10` is `0`, then `x10`. +#[test] +fn no_radix_prefixes() { + let allocator = Allocator::default(); + for (text, rest) in [("0x10", "x10"), ("0b11", "b11"), ("0o7", "o7")] { + let tokens = Lexer::new(&allocator, text).tokenize(); + assert_eq!(tokens.len(), 2, "{text:?}"); + assert_eq!((tokens[0].token_type, tokens[0].num_value), (TokenType::Number, 0.0)); + assert_eq!( + (tokens[1].token_type, tokens[1].str_value.as_str()), + (TokenType::Identifier, rest) + ); + } +} + +/// The text of the only token of `text`, a string. +fn string(text: &str) -> String { + let allocator = Allocator::default(); + let tokens = Lexer::new(&allocator, text).tokenize(); + let [token] = tokens.as_slice() else { panic!("{text:?}: {} tokens", tokens.len()) }; + assert_eq!(token.token_type, TokenType::String, "{text:?}"); + token.str_value.to_string() +} + +/// Only `\n`, `\f`, `\r`, `\t`, `\v` and `\uXXXX` are escapes in Angular; any other +/// character after a backslash stands for itself. +#[test] +fn string_escapes_like_angular() { + for (text, value) in [ + (r"'\x41'", "x41"), + (r"'\b\0'", "b0"), + (r"'\q\\\''", "q\\'"), + (r"'\n\f\r\t\v'", "\n\u{c}\r\t\u{b}"), + (r"'\u0041'", "A"), + (r"'\uD83D\uDE00'", "\u{1F600}"), + ("'\\\u{1F600}'", "\u{1F600}"), + ] { + assert_eq!(string(text), value, "{text:?}"); + } +} + +/// The compiled code of a component whose `templateUrl` is `template`. +fn compiled(template: &str) -> String { + let source = "import { Component } from '@angular/core'; +@Component({ selector: 'x-cut', templateUrl: './cut.html' }) +export class Cut { a = 1 } +"; + let mut templates = HashMap::new(); + templates.insert("./cut.html".to_string(), template.to_string()); + let resources = ResolvedResources { templates, styles: HashMap::new() }; + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let result = + transform_angular_file(&allocator, "/x/cut.ts", source, Some(&options), Some(&resources)); + assert!(result.diagnostics.is_empty(), "{template:?}: {:?}", result.diagnostics); + result.code +} + +/// Number and string literals compile to what `ngc` 22.3.0 emits for them (its +/// `ɵɵdomProperty("x", value)`, spaces aside). +#[test] +fn literals_compile_like_ngc() { + for (expression, value) in [ + ("100000000000000000000000", "1e+23"), + ("123456789012345678901234567890", "1.2345678901234568e+29"), + ("1.2.3", "1.2"), + ("1e5e5", "100000"), + ("1_000.5_5", "1000.55"), + (r"'\x41'", "\"x41\""), + (r"'\b\0'", "\"b0\""), + (r"'\uD83D\uDE00'", r#""\uD83D\uDE00""#), + (r"'\uD83D'", r#""\uD83D""#), + (r"`a\x41${a}\u0041`", "`ax41${ctx.a}A`"), + // A lone surrogate in a template literal part: the TypeScript printer writes the + // raw text as is, and its UTF-8 output turns the lone code unit into U+FFFD. + (r"`\uD83D`", "`\u{fffd}`"), + (r"`a\uD83D${a}b`", "`a\u{fffd}${ctx.a}b`"), + (r"`${a}\uD83D${a}`", "`${ctx.a}\u{fffd}${ctx.a}`"), + (r"`A${a}\uD83D`", "`A${ctx.a}\u{fffd}`"), + (r"a`\uD83D`", "ctx.a`\u{fffd}`"), + (r"a`a${a}\uD83D`", "ctx.a`a${ctx.a}\u{fffd}`"), + ("a ? /x/ : 1", "(ctx.a? /x/: 1)"), + ] { + let code = compiled(&format!("

")); + let expected = format!("\u{275}\u{275}domProperty(\"x\",{value})"); + assert!(code.contains(&expected), "{expression}: expected {expected} in\n{code}"); + } +} diff --git a/crates/oxc_angular_compiler/tests/html_parser_angular_errors_test.rs b/crates/oxc_angular_compiler/tests/html_parser_angular_errors_test.rs new file mode 100644 index 000000000..c69dbc551 --- /dev/null +++ b/crates/oxc_angular_compiler/tests/html_parser_angular_errors_test.rs @@ -0,0 +1,388 @@ +//! HTML lexer and parser errors carry Angular's message, count, order and span, and +//! block parameters keep their text as written. Every expected message and labelled +//! text below is what `ngc` from `@angular/compiler-cli` 22.3.0 reports for the same +//! inline template. An empty Angular span is widened to one character, as `ngc` does. + +use oxc_allocator::Allocator; +use oxc_angular_compiler::{TransformOptions, compile_template_to_js, transform_angular_file}; + +fn inline_source(template: &str) -> String { + format!( + "import {{ Component }} from '@angular/core';\n@Component({{ selector: 'x-cut', \ + template: `{template}` }})\nexport class Cut {{ value = 1 }}\n" + ) +} + +/// Each error of the inline `template` as `(message, labelled text)`. +fn errors(template: &str) -> Vec<(String, String)> { + let source = inline_source(template); + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let result = transform_angular_file(&allocator, "/x/cut.ts", &source, Some(&options), None); + result + .diagnostics + .iter() + .map(|d| { + let label = d.labels.first().unwrap_or_else(|| panic!("expected a label: {d:?}")); + let start = label.offset() as usize; + let text = &source[start..start + label.len() as usize]; + (d.message.to_string(), text.to_string()) + }) + .collect() +} + +/// `(template, [(message, labelled text)])`. +const CASES: &[(&str, &[(&str, &str)])] = &[ + ( + "
", + &[( + "Unexpected closing tag \"span\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + )], + ), + ( + "", + &[( + "Unexpected closing tag \":svg:svg\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + )], + ), + ("", &[("Void elements do not have end tags \"input\"", "")]), + ("@if (a) {", &[("Unclosed block \"if\"", "@if (a) {")]), + ( + "@if (a) {@for (x of y; track x) {", + &[ + ("Unclosed block \"if\"", "@if (a) {"), + ("Unclosed block \"for\"", "@for (x of y; track x) {"), + ], + ), + ("

", &[("Opening tag \"div\" not terminated.", "
", &[("Only void, custom and foreign elements can be self closed \"div\"", " = ;`", + "@let x = 1", + )], + ), + ( + "@let x;", + &[( + "Incomplete @let declaration \"x\". @let declarations must be written as `@let = ;`", + "@let x", + )], + ), + ("{a, select, b {c}", &[("Invalid ICU message. Missing '}'.", "`")]), + ( + "{a, select, b c}}", + &[ + ( + "Unexpected character \"EOF\" (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)", + "`", + ), + ("Invalid ICU message. Missing '}'.", "`"), + ], + ), + ( + "
}", + &[( + "Unexpected closing block. The block may have been closed earlier. If you meant to write the `}` character, you should use the \"}\" HTML entity instead.", + "}", + )], + ), + ("
@if (a) {

}

", &[]), + ("
@if (a) {

x}

", &[]), + ( + "&unknown;", + &[( + "Unknown entity \"unknown\" - use the \"&#;\" or \"&#x;\" syntax", + "&unknown;", + )], + ), + ("&#;", &[("Unknown entity \"&#;\" - use the \"&#;\" or \"&#x;\" syntax", "`")]), + ( + "&#x;", + &[("Unknown entity \"&#x;\" - use the \"&#;\" or \"&#x;\" syntax", "`")], + ), + ( + "�", + &[( + "Unknown entity \"�\" - use the \"&#;\" or \"&#x;\" syntax", + "`", + )], + ), + ("&;", &[("Unknown entity \"\" - use the \"&#;\" or \"&#x;\" syntax", "&;")]), + ("a", &[("Unexpected character \"EOF\"", "`")]), + ("@iffy (a) {x}", &[("Unrecognized block @iffy.", "@iffy (a) {x}")]), + ("@ifx {x}", &[("Unrecognized block @ifx.", "@ifx {x}")]), + ( + "
", + &[("Invalid attribute name ':a'. Attribute names cannot start with a colon.", ":a")], + ), + (" of \"", + "(x of a", + ), + ], + ), + ( + "@defer {x} @placeholder (minimum 1s ) {y}", + &[("Could not parse time value of parameter \"minimum\"", "@placeholder (minimum 1s ) {")], + ), + ("

ac

", &[]), + ( + "@if (a) {}", + &[( + "Unexpected closing block. The block may have been closed earlier. Did you forget to close the <:svg:g> element? If you meant to write the `}` character, you should use the \"}\" HTML entity instead.", + "}", + )], + ), + // `@` in an ICU case is text (Angular's `_isTextEnd`); a nested ICU with an error + // drops its case only; `@content` is lexed as a block; `a@letter` is an + // incomplete `@let`; a tag's namespace is read through the blocks around it. + ("{n, plural, =1 {write to me@forum.com} other {x}}", &[]), + ("{n, plural, other {see a@iffy}}", &[]), + ("

{n, select, x {user@elsewhere.org}}

", &[]), + ("{a, select, x {ab@iffy}}", &[]), + ("{a, select, x {a@error.com}}", &[]), + ("{a, select, x {a@letter}}", &[]), + ( + "{a, select, x {{b, select, y {}}}}", + &[( + "Unexpected closing tag \"i\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + )], + ), + ( + "

{a, select, x {{b, select, y {

}}}}

", + &[("Void elements do not have end tags \"br\"", "
")], + ), + ( + "{a, select, x {{b select}}}", + &[ + ( + "Unexpected character \"EOF\" (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)", + "`", + ), + ("Invalid ICU message. Missing '}'.", "{"), + ], + ), + ( + "{a, select, x {} y {
}}", + &[ + ( + "Unexpected closing tag \"i\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + ), + ( + "Unexpected closing tag \"b\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + ), + ], + ), + ("
", &[]), + ( + "

@contentChild

", + &[( + "Incomplete block \"contentChild\". If you meant to write the @ character, you should use the \"@\" HTML entity instead.", + "@contentChild", + )], + ), + ("@contents {x}", &[("Unrecognized block @contents.", "@contents {x}")]), + ( + "

a@letter

", + &[( + "Incomplete @let declaration \"@let\". @let declarations must be written as `@let = ;`", + "@let", + )], + ), + ( + "a@let", + &[( + "Incomplete @let declaration \"@let\". @let declarations must be written as `@let = ;`", + "@let", + )], + ), + ( + "@if (a) {@if (b) {
}}", + &[( + "Unexpected closing tag \":svg:a\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + )], + ), + ( + "@for (x of y; track x) {}", + &[ + ( + "Unexpected closing tag \":math:b\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "", + ), + ( + "Unexpected closing block. The block may have been closed earlier. Did you forget to close the <:math:mi> element? If you meant to write the `}` character, you should use the \"}\" HTML entity instead.", + "}", + ), + ], + ), +]; + +/// An entity error in an attribute value stops the tag, as Angular's +/// `_consumeTagOpen` does: the "Opening tag not terminated" and "Unexpected closing +/// tag" errors are what `ngc` reports. The entity error before them is ours only +/// (Angular swallows it); it is kept. +const ATTRIBUTE_ENTITY_CASES: &[(&str, &[(&str, &str)])] = &[ + ( + "
", + &[ + ("Unknown entity \"foo\" - use the \"&#;\" or \"&#x;\" syntax", "&foo;"), + ("Opening tag \"div\" not terminated.", "
", + ), + ], + ), + ( + "
", + &[ + ( + "Unable to parse entity \" >\" - decimal character reference entities must end with \";\"", + "<", + ), + ("Opening tag \"div\" not terminated.", "
"), + ( + "Unexpected closing tag \"div\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags", + "
", + ), + ], + ), + ( + "", + &[ + ("Unknown entity \"foo\" - use the \"&#;\" or \"&#x;\" syntax", "&foo;"), + ("Opening tag \":svg:g\" not terminated.", "", + ), + ], + ), + ( + "", + &[ + ("Unknown entity \"foo\" - use the \"&#;\" or \"&#x;\" syntax", "&foo;"), + ("Opening tag \"img\" not terminated.", " = + expected.iter().map(|(m, text)| (m.to_string(), text.to_string())).collect(); + let actual = errors(template); + if actual != expected { + mismatches + .push(format!("{template:?}\n expected {expected:?}\n actual {actual:?}")); + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn html_errors_are_reported_like_angular() { + check(CASES); +} + +#[test] +fn attribute_entity_errors_stop_the_tag_like_angular() { + check(ATTRIBUTE_ENTITY_CASES); +} + +/// Entities in an unquoted attribute value are decoded, as Angular's +/// `_consumeWithInterpolation` does: `ngc` emits `"title", "a&b"` and `"aAb"`. +#[test] +fn unquoted_attribute_values_decode_entities() { + let source = inline_source("

"); + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let js = transform_angular_file(&allocator, "/x/cut.ts", &source, Some(&options), None).code; + let compact: String = js.chars().filter(|c| !c.is_whitespace()).collect(); + assert!(compact.contains("consts:[[\"title\",\"a&b\"],[\"title\",\"aAb\"]]"), "{js}"); +} + +fn compile(template: &str) -> String { + let allocator = Allocator::default(); + compile_template_to_js(&allocator, template, "Cut", "/x/cut.html") + .unwrap_or_else(|d| panic!("{template:?} should compile: {d:?}")) +} + +/// The body of the generated template function `name`. +fn function_body<'s>(js: &'s str, name: &str) -> &'s str { + let start = js.find(&format!("function {name}(")).unwrap_or_else(|| panic!("no {name}: {js}")); + let rest = &js[start..]; + &rest[..rest.find("\n}").unwrap_or(rest.len())] +} + +/// A `}` closes the block and every element still open inside it, as Angular's tree +/// builder does: the `` is a sibling of the `@if`, not a child of the `

`. +#[test] +fn block_close_closes_the_elements_left_open_inside_it() { + let js = compile("@if (a) {

}x"); + let conditional = function_body(&js, "Cut_Conditional_0_Template"); + assert!(conditional.contains("\"p\""), "{js}"); + assert!(!conditional.contains("span"), "{js}"); + assert!(function_body(&js, "Cut_Template").contains("\"span\""), "{js}"); +} + +/// `` is a processing instruction: it splits the text and is not emitted. +#[test] +fn processing_instruction_splits_the_text() { + let js = compile("

ac

"); + let template = function_body(&js, "Cut_Template"); + assert!(template.contains("ɵɵtext(1,\"a\")"), "{js}"); + assert!(template.contains("ɵɵtext(2,\"c\")"), "{js}"); + assert!(!js.contains("?b?"), "{js}"); +} + +/// Block parameters keep their trailing whitespace, so `@if (a )` and `@if (a)` are +/// different i18n placeholders, as Angular names them. +#[test] +fn block_parameters_keep_trailing_whitespace_in_i18n_placeholders() { + let source = inline_source("
@if (a ) {x} @if (a) {y}
"); + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let js = transform_angular_file(&allocator, "/x/cut.ts", &source, Some(&options), None).code; + assert!( + js.contains("{$startBlockIf}x{$closeBlockIf}{$startBlockIf_1}y{$closeBlockIf}"), + "{js}" + ); +} diff --git a/crates/oxc_angular_compiler/tests/html_parser_test.rs b/crates/oxc_angular_compiler/tests/html_parser_test.rs index 9c362cc56..854472755 100644 --- a/crates/oxc_angular_compiler/tests/html_parser_test.rs +++ b/crates/oxc_angular_compiler/tests/html_parser_test.rs @@ -957,8 +957,8 @@ mod incomplete_blocks { "@if (cond {a}

(b)

) c", &[(incomplete("if"), 0, 27)], &[ - // Angular keeps the parameter's trailing space; this lexer trims parameters. - "Block \"if\" params=[\"cond {a}

(b)

\"] [0,27]", + // The parameter keeps its trailing space, as in Angular. + "Block \"if\" params=[\"cond {a}

(b)

\"] [0,27]", "Element \"i\" [27,35]", " Text \"c\" [30,31]", ], @@ -1027,8 +1027,8 @@ mod incomplete_blocks { "Element \"p\" [0,8]", " Text \"a\" [3,4]", "Text \"\\n \" [8,11]", - // Angular keeps the parameter's trailing newline; this lexer trims parameters. - "Block \"if\" params=[\"cond {\"] [11,23]", + // The parameter keeps its trailing newline, as in Angular. + "Block \"if\" params=[\"cond {\\n\"] [11,23]", ], ); } @@ -1038,9 +1038,8 @@ mod incomplete_blocks { // The outer block never sees its `}`, so it is reported as unclosed too. check( "@if (a) {

x

@if (cond {y}}", - // Angular words the second error `Unclosed block "if"` and spans it [0,9]. That - // error predates this test and is left as this parser reports it. - &[(incomplete("if"), 17, 31), ("Unclosed block \"@if\"".to_string(), 0, 0)], + // Reported over the block start, as Angular's `Unclosed block "if"`. + &[(incomplete("if"), 17, 31), ("Unclosed block \"if\"".to_string(), 0, 9)], &[ "Block \"if\" params=[\"a\"] [0,9]", " Element \"p\" [9,17]", @@ -2369,13 +2368,15 @@ mod expansion_forms { ) .parse(); // The case's `}` lands inside the block, so the block is unclosed and - // the expansion's own `}` is consumed as the case terminator. + // the expansion's own `}` is consumed as the case terminator. As in + // Angular, the expansion is then missing its `}`. assert_eq!( result.errors.iter().map(|e| e.msg.as_str()).collect::>(), [ "Unexpected character \"EOF\" (Do you have an unescaped \"{\" in your template? \ Use \"{{ '{' }}\") to escape it.)", - "Unclosed block \"@if\"", + "Unclosed block \"if\"", + "Invalid ICU message. Missing '}'.", ] ); } @@ -3269,7 +3270,7 @@ mod foreign_void_elements { assert_eq!( errors, vec![ - "Unexpected closing tag \"svg\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags".to_string() + "Unexpected closing tag \":svg:svg\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags".to_string() ] ); } diff --git a/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs b/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs new file mode 100644 index 000000000..9e08476f5 --- /dev/null +++ b/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs @@ -0,0 +1,215 @@ +//! An inline template written as one string or template literal is parsed by ngtsc +//! from the literal's raw text with Angular's `EscapedCharacterCursor`, so what +//! Angular compiles is what that cursor reads. It is the literal's value except for +//! a few escapes the cursor reads another way (`\400`, line continuations), and a +//! lone surrogate (`\uD83D`) is a template character like any other. +//! +//! Every expected value is what ngtsc 22.3.0 emits or reports for the same file +//! (full mode, with whitespace removed from the output). + +use oxc_allocator::Allocator; +use oxc_angular_compiler::{TransformOptions, transform_angular_file}; + +fn source(literal: &str) -> String { + format!( + "import {{ Component }} from '@angular/core';\n@Component({{\n selector: 'x-cut',\n \ + template: {literal},\n}})\nexport class Cut {{ a = 1 }}\n" + ) +} + +/// The output without whitespace, and the diagnostics (message first line, help). +fn compile_with(literal: &str, options: &TransformOptions) -> (String, Vec) { + let allocator = Allocator::default(); + let source = source(literal); + let result = transform_angular_file(&allocator, "/w/cut.ts", &source, Some(options), None); + let code = result.code.chars().filter(|c| !c.is_whitespace()).collect(); + let diagnostics = result + .diagnostics + .iter() + .map(|d| { + let message = d.message.lines().next().unwrap_or_default(); + format!("{message} @{}", d.help.as_deref().unwrap_or_default()) + }) + .collect(); + (code, diagnostics) +} + +fn compile(literal: &str) -> String { + let (code, diagnostics) = compile_with(literal, &TransformOptions::default()); + assert!(diagnostics.is_empty(), "{literal:?}: {diagnostics:?}"); + code +} + +/// The `ɵɵtext(1, ...)` call of the template `

a{escape}b

`. +fn text_of(escape: &str, quote: char) -> String { + let code = compile(&format!("{quote}

a{escape}b

{quote}")); + let start = code.find("ɵɵtext(1,").unwrap_or_else(|| panic!("{escape:?}: no text in {code}")); + let end = start + code[start..].find(");").unwrap(); + code[start..end + 2].to_string() +} + +#[test] +fn escapes_angular_reads_another_way_than_javascript() { + for (escape, quote, expected) in [ + // Three octal digits: JavaScript reads `\40` then `0`. + (r"\400", '\'', r#"ɵɵtext(1,"a\u0100b");"#), + (r"\777", '\'', r#"ɵɵtext(1,"a\u01FFb");"#), + // A line continuation skips one character: the LF of a CR LF stays, and so do + // U+2028 and U+2029. + ("\\\r\n", '\'', r#"ɵɵtext(1,"a\nb");"#), + ("\\\r\n", '`', r#"ɵɵtext(1,"a\nb");"#), + ("\\\u{2028}", '\'', r#"ɵɵtext(1,"a\u2028b");"#), + ("\\\u{2029}", '`', r#"ɵɵtext(1,"a\u2029b");"#), + // After `\` LF or `\` CR, the next character is read as written. + ("\\\n\\n", '\'', r#"ɵɵtext(1,"a\\nb");"#), + ("\\\r\\n", '\'', r#"ɵɵtext(1,"a\\nb");"#), + ("\\\n\\n", '`', r#"ɵɵtext(1,"a\\nb");"#), + ("\\\n\\\n", '\'', r#"ɵɵtext(1,"a\\\nb");"#), + // Where both read the same. + ("\\\n", '\'', r#"ɵɵtext(1,"ab");"#), + ("\\\r", '\'', r#"ɵɵtext(1,"ab");"#), + (r"\101", '\'', r#"ɵɵtext(1,"aAb");"#), + (r"\3777", '\'', r#"ɵɵtext(1,"a\u00FF7b");"#), + (r"\8", '\'', r#"ɵɵtext(1,"a8b");"#), + ] { + assert_eq!(text_of(escape, quote), expected, "{quote}{escape:?}{quote}"); + } +} + +/// A template with a lone surrogate used to be left uncompiled, with no error. +#[test] +fn lone_surrogates() { + for (escape, expected) in [ + (r"\uD83D", r#"ɵɵtext(1,"a\uD83Db");"#), + (r"\uDE00", r#"ɵɵtext(1,"a\uDE00b");"#), + (r"\u{D83D}", r#"ɵɵtext(1,"a\uD83Db");"#), + (r"\uDE00\uD83D", r#"ɵɵtext(1,"a\uDE00\uD83Db");"#), + (r"\uD83D\uD83D", r#"ɵɵtext(1,"a\uD83D\uD83Db");"#), + (r"\uD83D\u{DE00}", r#"ɵɵtext(1,"a\uD83D\uDE00b");"#), + ] { + assert_eq!(text_of(escape, '\''), expected, "{escape:?}"); + assert_eq!(text_of(escape, '`'), expected, "{escape:?}"); + } + let code = compile(r#"'

a

'"#); + assert!(code.contains(r#"consts:[["title","x\uD83Dy"]]"#), "{code}"); +} + +/// The message ids hash the text Angular reads; `TextEncoder` writes a lone surrogate +/// as U+FFFD. +#[test] +fn i18n_message_ids() { + for (literal, id) in [ + ("'

a\\\r\nb

'", "7644962709890836549"), + (r"'

a\400b

'", "2735989238855312684"), + (r"'

a\uD83Db

'", "3477124521808493947"), + ("'

{a, select, x {X\\\r\ny}}

'", "7292333455433783452"), + ] { + let code = compile(literal); + assert!(code.contains(&format!("MSG_EXTERNAL_{id}$$")), "{literal:?}: {code}"); + } +} + +#[test] +fn source_locations() { + let options = TransformOptions { + enable_template_source_locations: true, + root_dirs: Some(vec!["/w".to_string()]), + ..Default::default() + }; + for (escape, expected) in [ + ("\\uD83D\\uDE00".to_string(), "[[0,90,3,13],[2,111,3,34]]"), + (r"\uD83D".to_string(), "[[0,90,3,13],[2,105,3,28]]"), + (r"\uDE00\uD83D".to_string(), "[[0,90,3,13],[2,111,3,34]]"), + (r"\101".to_string(), "[[0,90,3,13],[2,103,3,26]]"), + (r"\400".to_string(), "[[0,90,3,13],[2,103,3,26]]"), + (r"\777".to_string(), "[[0,90,3,13],[2,103,3,26]]"), + (r"\8".to_string(), "[[0,90,3,13],[2,101,3,24]]"), + // NUL ends Angular's template: only the `

` is left. + (r"\00".to_string(), "[[0,90,3,13]]"), + ("\\\n\\n".to_string(), "[[0,90,3,13],[2,103,4,7]]"), + ("\\\u{2028}".to_string(), "[[0,90,3,13],[2,101,3,24]]"), + ("\\\r\n".to_string(), "[[0,90,3,13],[2,102,4,5]]"), + ] { + let literal = format!("'

a{escape}b

x'"); + let (code, diagnostics) = compile_with(&literal, &options); + assert!(diagnostics.is_empty(), "{literal:?}: {diagnostics:?}"); + let call = format!(r#"attachSourceLocations("cut.ts",{expected});"#); + assert!(code.contains(&call), "{literal:?}: {code}"); + } +} + +/// An octal escape is a syntax error in a template literal. oxc reports it, and +/// like ngtsc (which reports TS1487) the template is still compiled, as Angular's +/// cursor reads it. +#[test] +fn octal_escape_in_a_template_literal() { + let (code, diagnostics) = compile_with("`

a\\101b

`", &TransformOptions::default()); + assert!(code.contains(r#"ɵɵtext(1,"aAb");"#), "{code}"); + assert_eq!(diagnostics, ["Bad escape sequence in untagged template literal @"]); + + let (_, diagnostics) = compile_with("`

\\101

{{ a + }}`", &TransformOptions::default()); + assert_eq!( + diagnostics, + [ + "Bad escape sequence in untagged template literal @", + "Unexpected end of expression: a + at the end of the expression [ a + ] @/w/cut.ts:4:25", + ] + ); +} + +/// ngc's message holds the lone code unit, which reads as U+FFFD once written out as +/// UTF-8; ours shows U+FFFD. A column counts the lone surrogate as one unit. +#[test] +fn lone_surrogate_in_error_messages() { + for (literal, expected) in [ + ( + r#"'

{{ "\uD83D" b }}

'"#, + "Unexpected token 'b' at column 6 in [ \"\u{FFFD}\" b ] @/w/cut.ts:4:17", + ), + ( + r#"'

{{ "\uD83D" }}{{ a b }}

'"#, + "Unexpected token 'b' at column 4 in [ a b ] @/w/cut.ts:4:31", + ), + ( + r#"'

x

'"#, + "Unexpected token 'b' at column 6 in ['\u{FFFD}\u{FFFD}' b] @/w/cut.ts:4:26", + ), + ( + r"'

\uD83D{{ a b }}

'", + "Unexpected token 'b' at column 4 in [ a b ] @/w/cut.ts:4:23", + ), + ( + r"'

x'", + "Unexpected closing tag \"q\u{FFFD}\". It may happen when the tag has already been \ + closed by another tag. For more info see \ + https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags \ + @/w/cut.ts:4:18", + ), + ] { + let (_, diagnostics) = compile_with(literal, &TransformOptions::default()); + assert_eq!(diagnostics, [expected], "{literal:?}"); + } + // A bare lone surrogate is an unexpected character to Angular's lexer, as `@` or + // `é` is: the parser reports the error token, then the lexer error itself. + let (_, diagnostics) = compile_with(r"'

{{ a \uD83D }}

'", &TransformOptions::default()); + assert_eq!( + diagnostics, + [ + "Unexpected token 'Lexer Error: Unexpected character [\u{FFFD}] at column 4 in \ + expression [ a \u{FFFD} ]' at column 5 in [ a \u{FFFD} ] @/w/cut.ts:4:17", + "Lexer Error: Unexpected character [\u{FFFD}] at column 4 in expression [ a \u{FFFD} ] \ + at the end of the expression [ a \u{FFFD} ] @/w/cut.ts:4:17", + ] + ); +} + +/// Angular's `sanitizeIdentifier` (`/\W/g`) writes one `_` for a lone code unit. +#[test] +fn lone_surrogate_in_names() { + let code = compile(r#"'

x

'"#); + assert!(code.contains("functionCut_Template_p_cl_k_0_listener()"), "{code}"); + let code = compile(r#"'x'"#); + assert!(code.contains("functionCut_p__0_Template(rf,ctx)"), "{code}"); + let code = compile(r#"'

x

'"#); + assert!(code.contains("MSG_EXTERNAL_a_b$$"), "{code}"); +} diff --git a/crates/oxc_angular_compiler/tests/partial_component_test.rs b/crates/oxc_angular_compiler/tests/partial_component_test.rs index 3f5849881..40120154f 100644 --- a/crates/oxc_angular_compiler/tests/partial_component_test.rs +++ b/crates/oxc_angular_compiler/tests/partial_component_test.rs @@ -102,7 +102,7 @@ export class BindingComponent {} transform_angular_file(&allocator, "broken.component.ts", source, Some(&options), None); let messages: Vec<_> = result.diagnostics.iter().map(|d| d.message.to_string()).collect(); assert!( - messages.iter().any(|m| m.contains("Unclosed block \"@if\"")), + messages.iter().any(|m| m.contains("Unclosed block \"if\"")), "expected the HTML parse error, got: {messages:?}" ); assert!( diff --git a/crates/oxc_angular_compiler/tests/r3_transform_ngc_parity_test.rs b/crates/oxc_angular_compiler/tests/r3_transform_ngc_parity_test.rs new file mode 100644 index 000000000..6b1604bd4 --- /dev/null +++ b/crates/oxc_angular_compiler/tests/r3_transform_ngc_parity_test.rs @@ -0,0 +1,564 @@ +//! The R3 transform like Angular 22.3.0's `r3_template_transform`: +//! +//! - A text with an HTML entity parses its interpolations from the text's value, with +//! whitespace folded (unless it is preserved), as Angular's `parseInterpolation` +//! does. Before, they came from the raw tokens: `&{{ a + }}` printed `[ a + ]` +//! where Angular prints `[ a + ]`, `&{{ // c }}` gave 'Unexpected token' +//! where Angular says the expression is only a comment, and `& {{ "a b" }}` +//! compiled to `"a b"` where ngc emits `"a b"`. +//! - An ICU inside ngNonBindable is dropped (`NonBindableVisitor.visitExpansion`), and an +//! element inside ngNonBindable has no i18n. An ngNonBindable element with `i18n` keeps +//! its message (built from its HTML children) even when its ICU child is dropped. +//! Before, the ICU still got an i18n message, `ɵɵi18nExp` and `ɵɵi18nPostprocess`. +//! - A microsyntax key with no value (`else` in `*ngIf="c; else"`) is a literal template +//! attribute, which Angular lists before the bound ones in the template's consts: +//! `[4, "ngIfElse", "ngIf"]`. Before, it was a bound one, in source order. +//! +//! The expected values are what ngc (`NgtscProgram`) and `parseTemplate` of Angular +//! 22.3.0 give for these templates. + +use std::collections::HashMap; + +use oxc_allocator::Allocator; +use oxc_angular_compiler::{ResolvedResources, TransformOptions, transform_angular_file}; + +/// Templates, and each error `parseTemplate` reports for them: its message (without the +/// `Parser Error: ` prefix and the ` in file@line:col` suffix) and its `line:column`. +const ERROR_CASES: &[(&str, &[(&str, &str)])] = &[ + ( + "&{{ a + }}", + &[("Unexpected end of expression: a + at the end of the expression [ a + ]", "1:1")], + ), + ( + "&{{ \u{3000}// c }}", + &[( + "Interpolation expression cannot only contain a comment at column 1 in [&{{ // c }}]", + "1:1", + )], + ), + ( + "&{{ \u{feff}// c }}", + &[( + "Interpolation expression cannot only contain a comment at column 1 in [&{{ // c }}]", + "1:1", + )], + ), + ("&{{ a \u{3000}+ b }}", &[]), + ( + "&{{ a + b }} {{ c + }}", + &[("Unexpected end of expression: c + at the end of the expression [ c + ]", "1:6")], + ), + ( + "&{{ a + b }} {{ }} {{ // x }}", + &[ + ( + "Blank expressions are not allowed in interpolated strings at column 13 in [&{{ a + b }} {{ }} {{ // x }}]", + "1:1", + ), + ( + "Interpolation expression cannot only contain a comment at column 19 in [&{{ a + b }} {{ }} {{ // x }}]", + "1:1", + ), + ], + ), + ( + " & {{ a + }} ", + &[("Unexpected end of expression: a + at the end of the expression [ a + ]", "1:3")], + ), + ( + "
&{{ a   + }}
", + &[("Unexpected end of expression: a + at the end of the expression [ a + ]", "1:6")], + ), + ( + "
&{{ a + }}
", + &[("Unexpected end of expression: a + at the end of the expression [ a + ]", "1:28")], + ), + ( + "&{{ \"a b\" + }}", + &[( + "Unexpected end of expression: \"a b\" + at the end of the expression [ \"a b\" + ]", + "1:1", + )], + ), + ( + "&{{a}}{{ b + }}<{{ c . + }}", + &[ + ("Unexpected end of expression: b + at the end of the expression [ b + ]", "1:6"), + ("Unexpected token +, expected identifier or keyword at column 6 in [ c . + ]", "1:11"), + ( + "Expected identifier for property access at the end of the expression [ c . + ]", + "1:11", + ), + ], + ), + ( + "a &ngsp; &{{ b + }}", + &[("Unexpected end of expression: b + at the end of the expression [ b + ]", "1:3")], + ), + ( + "{{ a + }}", + &[("Unexpected end of expression: a + at the end of the expression [ a + ]", "1:1")], + ), + ("
{a +, plural, =0 {x {{b +}}}}
", &[]), + ("
{a, select, x {{{q +}}}}
", &[]), + ("
{a +, plural, =0 {x}}
", &[]), + ("
", &[]), + ("
  • {{x}}
  • ", &[]), +]; + +/// Templates, and ngc's `ɵɵdefineComponent` fields from `decls` to the template function +/// (comments dropped, i18n message names written `MSG`), compared after [`normalize`]. +const OUTPUT_CASES: &[(&str, &str)] = &[ + ( + "& {{ \"a b\" }}", + r#"decls: 1, vars: 1, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵtext(0); + } if (rf & 2) { + i0.ɵɵtextInterpolate1("& ", "a b"); + } }"#, + ), + ( + "

    &{{ x ? \"a b\" : c }} and {{ d }}

    ", + r#"decls: 2, vars: 2, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "p"); + i0.ɵɵtext(1); + i0.ɵɵdomElementEnd(); + } if (rf & 2) { + i0.ɵɵadvance(); + i0.ɵɵtextInterpolate2("&", ctx.x ? "a b" : ctx.c, " and ", ctx.d); + } }"#, + ), + ( + "&ngsp;&{{ \"a b\" }}&ngsp;", + r#"decls: 1, vars: 1, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵtext(0); + } if (rf & 2) { + i0.ɵɵtextInterpolate1(" &", "a b", " "); + } }"#, + ), + ( + "
    & {{ \"a   b\" }}
    ", + r#"decls: 2, vars: 1, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "pre"); + i0.ɵɵtext(1); + i0.ɵɵdomElementEnd(); + } if (rf & 2) { + i0.ɵɵadvance(); + i0.ɵɵtextInterpolate1("& ", "a b"); + } }"#, + ), + ( + "& {{ \"a b\" }}", + r#"decls: 2, vars: 1, consts: () => { let i18n_0; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { + const MSG = + goog.getMsg("& {$interpolation}", { "interpolation": "\uFFFD0\uFFFD" }); + i18n_0 = MSG; + } + else { + i18n_0 = $localize `& ${"\uFFFD0\uFFFD"}:INTERPOLATION:`; + } return [i18n_0]; }, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "span"); + i0.ɵɵi18n(1, 0); + i0.ɵɵdomElementEnd(); + } if (rf & 2) { + i0.ɵɵadvance(); + i0.ɵɵi18nExp("a b"); + i0.ɵɵi18nApply(1); + } }"#, + ), + ( + "
    {a, plural, =0 {x}}
    ", + r#"decls: 1, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElement(0, "div"); + } }"#, + ), + ( + "
    {a, plural, =0 {x}}
    ", + r#"decls: 2, vars: 0, consts: () => { let i18n_0; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { + const MSG = + goog.getMsg("{VAR_PLURAL, plural, =0 {x}}"); + i18n_0 = MSG; + } + else { + i18n_0 = $localize `{VAR_PLURAL, plural, =0 {x}}`; + } return [i18n_0]; }, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "div"); + i0.ɵɵdisableBindings(); + i0.ɵɵi18n(1, 0); + i0.ɵɵenableBindings(); + i0.ɵɵdomElementEnd(); + } }"#, + ), + ( + "
    {a, plural, =0 {x}}
    ", + r#"decls: 2, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "div"); + i0.ɵɵdisableBindings(); + i0.ɵɵdomElement(1, "span"); + i0.ɵɵenableBindings(); + i0.ɵɵdomElementEnd(); + } }"#, + ), + ( + "
    {a, plural, =0 {x}}
    ", + r#"decls: 2, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "div"); + i0.ɵɵdisableBindings(); + i0.ɵɵdomElement(1, "span"); + i0.ɵɵenableBindings(); + i0.ɵɵdomElementEnd(); + } }"#, + ), + ( + "
    {a, plural, =0 {x {{b}}} other {y}}
    ", + r#"decls: 1, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElement(0, "div"); + } }"#, + ), + ( + "
    {a +, plural, =0 {x {{b +}}}}
    ", + r#"decls: 1, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElement(0, "div"); + } }"#, + ), + ( + "
    {a, select, x {{{q}}}}
    ", + r#"decls: 1, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElement(0, "div"); + } }"#, + ), + ( + "
    a{x, plural, =0 {y}}b
    ", + r#"decls: 3, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "div"); + i0.ɵɵdisableBindings(); + i0.ɵɵtext(1, "a"); + i0.ɵɵtext(2, "b"); + i0.ɵɵenableBindings(); + i0.ɵɵdomElementEnd(); + } }"#, + ), + ( + "
    hello
    ", + r#"decls: 3, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementStart(0, "div"); + i0.ɵɵdisableBindings(); + i0.ɵɵdomElementStart(1, "span"); + i0.ɵɵtext(2, "hello"); + i0.ɵɵdomElementEnd(); + i0.ɵɵenableBindings(); + i0.ɵɵdomElementEnd(); + } }"#, + ), + ( + "{a, plural, =0 {x}}", + r#"decls: 2, vars: 0, consts: () => { let i18n_0; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { + const MSG = + goog.getMsg("{VAR_PLURAL, plural, =0 {x}}"); + i18n_0 = MSG; + } + else { + i18n_0 = $localize `{VAR_PLURAL, plural, =0 {x}}`; + } return [i18n_0]; }, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElementContainerStart(0); + i0.ɵɵdisableBindings(); + i0.ɵɵi18n(1, 0); + i0.ɵɵenableBindings(); + i0.ɵɵdomElementContainerEnd(); + } }"#, + ), + ( + "{a, plural, =0 {x}}", + r#"decls: 1, vars: 0, consts: () => { let i18n_0; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { + const MSG = + goog.getMsg("{VAR_PLURAL, plural, =0 {x}}"); + i18n_0 = MSG; + } + else { + i18n_0 = $localize `{VAR_PLURAL, plural, =0 {x}}`; + } return [i18n_0]; }, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_ng_template_0_Template, 1, 0, "ng-template"); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElement(0, "div"); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 0, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomElement(0, "div"); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 1, consts: [[4, "ngIfElse", "ngIf"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 1, 0, "div", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("ngIf", ctx.cond); + } }"#, + ), + ( + "
  • {{x}}
  • ", + r#"decls: 1, vars: 1, consts: [[4, "ngFor", "ngForAs", "ngForOf"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_li_0_Template, 2, 1, "li", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("ngForOf", ctx.xs); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 1, consts: [[4, "dirC", "dir"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 1, 0, "div", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("dir", ctx.b); + } }"#, + ), + ( + "", + r#"decls: 1, vars: 1, consts: [[4, "dirB", "dir"], ["title", "t"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_0_Template, 1, 0, null, 0); + } if (rf & 2) { + i0.ɵɵdomProperty("dir", ctx.a); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 2, consts: [[4, "dirD", "dir", "dirB"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 1, 0, "div", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("dir", ctx.a)("dirB", ctx.c); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 1, consts: [[4, "dirC", "dir"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 1, 0, "div", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("dir", ctx.a); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 0, consts: [[4, "dir", "dirB"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 1, 0, "div", 0); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 1, consts: () => { let i18n_0; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { + const MSG = + goog.getMsg("hello"); + i18n_0 = MSG; + } + else { + i18n_0 = $localize `hello`; + } return [["ref", ""], ["title", i18n_0, "class", "k", 3, "id", "click", 4, "dirB", "dir"], ["title", i18n_0, 1, "k", 3, "click", "id"]]; }, template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 2, 1, "div", 1); + } if (rf & 2) { + i0.ɵɵdomProperty("dir", ctx.a); + } }"#, + ), + ( + "
    ", + r#"decls: 1, vars: 1, consts: [[4, "ngIfElse", "ngIf"], [4, "ngIfThen", "ngIf"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 2, 1, "div", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("ngIf", ctx.a); + } }"#, + ), + ( + "
    ", + r#"decls: 5, vars: 3, consts: [["t", ""], ["e", ""], [4, "ngIf", "ngIfThen", "ngIfElse"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_div_0_Template, 1, 0, "div", 2)(1, Cut_ng_template_1_Template, 0, 0, "ng-template", null, 0, i0.ɵɵtemplateRefExtractor)(3, Cut_ng_template_3_Template, 0, 0, "ng-template", null, 1, i0.ɵɵtemplateRefExtractor); + } if (rf & 2) { + const t_r1 = i0.ɵɵreference(2); + const e_r2 = i0.ɵɵreference(4); + i0.ɵɵdomProperty("ngIf", ctx.cond)("ngIfThen", t_r1)("ngIfElse", e_r2); + } }"#, + ), + ( + "
  • {{x}}
  • ", + r#"decls: 1, vars: 2, consts: [[4, "ngFor", "ngForOf", "ngForTrackBy"]], template: function Cut_Template(rf, ctx) { if (rf & 1) { + i0.ɵɵdomTemplate(0, Cut_li_0_Template, 2, 1, "li", 0); + } if (rf & 2) { + i0.ɵɵdomProperty("ngForOf", ctx.xs)("ngForTrackBy", ctx.tb); + } }"#, + ), +]; + +fn compile(template: &str) -> (String, Vec<(String, String)>) { + let source = "import { Component } from '@angular/core'; +@Component({ selector: 'x-cut', templateUrl: './cut.html' }) +export class Cut {} +"; + let mut templates = HashMap::new(); + templates.insert("./cut.html".to_string(), template.to_string()); + let resources = ResolvedResources { templates, styles: HashMap::new() }; + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let result = + transform_angular_file(&allocator, "/x/cut.ts", source, Some(&options), Some(&resources)); + let errors = result + .diagnostics + .iter() + .map(|diagnostic| { + let message = diagnostic.message.to_string(); + let message = message.strip_prefix("Parser Error: ").unwrap_or(&message); + let message = message.rsplit_once(" in ./cut.html@").map_or(message, |(m, _)| m); + let help = diagnostic.help.as_deref().unwrap_or_default(); + let position = help.strip_prefix("./cut.html:").unwrap_or(help); + (message.to_string(), position.to_string()) + }) + .collect(); + (result.code, errors) +} + +/// The `ɵɵdefineComponent` fields from `decls` up to the first field after the template +/// function. +fn component_fields(code: &str) -> &str { + let code = code.find("ɵɵdefineComponent(").map_or(code, |at| &code[at..]); + let code = code.find("decls:").map_or(code, |at| &code[at..]); + let end = + ["encapsulation:", "dependencies:", "styles:", "changeDetection:", "ɵsetClassMetadata"] + .iter() + .filter_map(|key| code.find(key)) + .min() + .unwrap_or(code.len()); + &code[..end] +} + +/// Drops what only differs in formatting: comments, `i0.`, the i18n message names, +/// whitespace and parentheses outside string literals, the quote style of string +/// literals and trailing separators. +fn normalize(code: &str) -> String { + let mut text = String::new(); + let mut rest = code; + while let Some(start) = rest.find("/*") { + text.push_str(&rest[..start]); + rest = rest[start..].find("*/").map_or("", |end| &rest[start + end + 2..]); + } + text.push_str(rest); + let text = text.replace("i0.", ""); + let mut no_names = String::new(); + let mut rest = text.as_str(); + while let Some(start) = rest.find("MSG_") { + no_names.push_str(&rest[..start]); + no_names.push_str("MSG"); + let name = &rest[start + 4..]; + let len = name + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + .unwrap_or(name.len()); + rest = &name[len..]; + } + no_names.push_str(rest); + + let mut out = String::new(); + let mut chars = no_names.chars(); + while let Some(c) = chars.next() { + if matches!(c, '"' | '\'' | '`') { + let mut literal = String::new(); + while let Some(next) = chars.next() { + if next == '\\' { + let escaped = chars.next().unwrap_or_default(); + if escaped == '"' { + literal.push('"'); + } else { + literal.push('\\'); + literal.push(escaped); + } + } else if next == c { + break; + } else if next == '\'' { + literal.push_str("\\'"); + } else { + literal.push(next); + } + } + out.push('\''); + out.push_str(&literal); + out.push('\''); + } else if !c.is_whitespace() && c != '(' && c != ')' { + out.push(c); + } + } + let out = out.trim_end_matches([',', ';', '}']); + out.replace(",]", "]").replace(",}", "}").replace(";}", "}") +} + +#[test] +fn errors_are_angulars() { + let mut mismatches = Vec::new(); + for (template, expected) in ERROR_CASES { + let expected: Vec<(String, String)> = + expected.iter().map(|(m, p)| ((*m).to_string(), (*p).to_string())).collect(); + let (_, actual) = compile(template); + if actual != expected { + mismatches + .push(format!("{template:?}\n expected: {expected:?}\n actual: {actual:?}")); + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn output_is_ngcs() { + let mut mismatches = Vec::new(); + for (template, expected) in OUTPUT_CASES { + let (code, errors) = compile(template); + let actual = normalize(component_fields(&code)); + let expected = normalize(expected); + if !errors.is_empty() || actual != expected { + mismatches.push(format!( + "{template:?}\n expected: {expected}\n actual: {actual}\n errors: {errors:?}" + )); + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +/// Only an ngNonBindable element starts an i18n block when its R3 children are empty. +/// An `i18n` element whose only HTML children are dropped from the R3 children +/// (`
    ", + "
    ", + "
    ", + "
    @let x = 1;
    ", + "@let y = 2;", + ] { + let mut templates = HashMap::new(); + templates.insert("./cut.html".to_string(), template.to_string()); + let mut styles = HashMap::new(); + styles.insert("a.css".to_string(), vec!["x{}".to_string()]); + let resources = ResolvedResources { templates, styles }; + let allocator = Allocator::default(); + let options = TransformOptions::default(); + let result = transform_angular_file( + &allocator, + "/x/cut.ts", + source, + Some(&options), + Some(&resources), + ); + let errors: Vec = + result.diagnostics.iter().map(|diagnostic| diagnostic.message.to_string()).collect(); + assert!(errors.is_empty(), "{template:?}: {errors:?}"); + assert!(result.code.contains("ɵɵdefineComponent("), "{template:?}: {}", result.code); + if template.contains("@let") { + // Same output as before this change: the i18n block still wraps the @let. + assert!(result.code.contains("ɵɵi18nStart("), "{template:?}: {}", result.code); + assert!(result.code.contains("ɵɵdeclareLet("), "{template:?}: {}", result.code); + } + } +} diff --git a/crates/oxc_angular_compiler/tests/template_parse_error_position_test.rs b/crates/oxc_angular_compiler/tests/template_parse_error_position_test.rs index 3e6c4f538..013d74a31 100644 --- a/crates/oxc_angular_compiler/tests/template_parse_error_position_test.rs +++ b/crates/oxc_angular_compiler/tests/template_parse_error_position_test.rs @@ -189,12 +189,12 @@ export class Cut {} panic!("expected one diagnostic, got {diagnostics:?}"); }; assert_eq!(diagnostic.message, "Unexpected character \"x\""); - // Zero-length label at the `x`. + // An empty span widened to the `x`, as ngc widens one. let [label] = diagnostic.labels.as_slice() else { panic!("expected one label, got {diagnostic:?}"); }; assert_eq!(label.offset() as usize, source.find(" (String, Vec<&str>) { // template but several of the file. ngc parses the file text as written, so its // positions are in the file, and so are ours. The expected `line:column` and labelled // text are what `ngc` 22.3.0 reports for the same files (the label length is its -// `length`). An unexpected closing tag gets an empty label (ngc's covers the tag), as it -// does without escapes. +// `length`). An unexpected closing tag's label covers the tag, as ngc's does. const LITERAL_ERRORS: &[(&str, &str, &str, Option<&str>)] = &[ // Multi-line template literals in CRLF and CR files. - ("`
    \n {{ value }}
    \n`", "\r\n", "/x/cut.ts:5:20", Some("")), - ("`
    \n ok\n \n
    `", "\r\n", "/x/cut.ts:6:3", Some("")), - ("`
    \n {{ value }}
    \n`", "\r", "/x/cut.ts:5:20", Some("")), + ("`
    \n {{ value }}
    \n`", "\r\n", "/x/cut.ts:5:20", Some("
    ")), + ("`
    \n ok\n \n
    `", "\r\n", "/x/cut.ts:6:3", Some("")), + ("`
    \n {{ value }}
    \n`", "\r", "/x/cut.ts:5:20", Some("
    ")), ("`
    \n {{ a + }}\n
    `", "\r\n", "/x/cut.ts:5:3", Some("{{ a + }}")), ( "`
    \n \n
    `", @@ -814,17 +813,27 @@ const LITERAL_ERRORS: &[(&str, &str, &str, Option<&str>)] = &[ // Non-ASCII text before the error: the map is per byte, columns are UTF-16. ("`

    \u{e9}\n \u{fc} {{ a + }}

    `", "\r\n", "/x/cut.ts:5:5", Some("{{ a + }}")), // A line continuation in a quoted string of a CRLF file adds nothing to the template. - ("'
    \\\n {{ value }}
    '", "\r\n", "/x/cut.ts:5:20", Some("")), + ("'
    \\\n {{ value }}
    '", "\r\n", "/x/cut.ts:5:20", Some("
    ")), // Escapes in an LF file. - ("'

    x

    \\x3c/i>'", "\n", "/x/cut.ts:4:22", Some("")), - ("`
    \\r\\n {{ value }}
    `", "\n", "/x/cut.ts:4:42", Some("")), - ("`
    \\n {{ value }}
    `", "\n", "/x/cut.ts:4:40", Some("")), - ("`
    \\u{41}\n {{ value }}
    `", "\n", "/x/cut.ts:5:20", Some("")), - ("`
    \\`\n {{ value }}
    `", "\n", "/x/cut.ts:5:20", Some("")), - // `cook_literal` does not map a `\u` surrogate pair or a legacy octal escape, so - // these keep a position within the template (ngc: 4:35 and 4:27). - ("'

    \\uD83D\\uDE00

    \\n'", "\n", "line 2, column 1 of the template", None), - ("'

    \\101

    \\n'", "\n", "line 2, column 1 of the template", None), + ("'

    x

    \\x3c/i>'", "\n", "/x/cut.ts:4:22", Some("\\x3c/i>")), + ("`
    \\r\\n {{ value }}
    `", "\n", "/x/cut.ts:4:42", Some("
    ")), + ("`
    \\n {{ value }}
    `", "\n", "/x/cut.ts:4:40", Some("
    ")), + ("`
    \\u{41}\n {{ value }}
    `", "\n", "/x/cut.ts:5:20", Some("")), + ("`
    \\`\n {{ value }}
    `", "\n", "/x/cut.ts:5:20", Some("")), + // Escapes Angular's `EscapedCharacterCursor` maps like any other: surrogates (a pair, + // lone ones), legacy octal (three digits for `\400`), `\8`, and line continuations + // (after `\` LF the next character is read as written). + ("'

    \\uD83D\\uDE00

    \\n'", "\n", "/x/cut.ts:4:35", Some("")), + ("'

    \\101

    \\n'", "\n", "/x/cut.ts:4:27", Some("")), + ("'

    \\uD83D\\uDE00

    {{ a + }}'", "\n", "/x/cut.ts:4:33", Some("{{ a + }}")), + ("'

    \\uD83D

    {{ a + }}'", "\n", "/x/cut.ts:4:27", Some("{{ a + }}")), + ("'

    \\uDE00\\uD83D

    {{ a + }}'", "\n", "/x/cut.ts:4:33", Some("{{ a + }}")), + ("'

    \\u{D83D}

    {{ a + }}'", "\n", "/x/cut.ts:4:29", Some("{{ a + }}")), + ("'

    \\101

    {{ a + }}'", "\n", "/x/cut.ts:4:25", Some("{{ a + }}")), + ("'

    \\400

    {{ a + }}'", "\n", "/x/cut.ts:4:25", Some("{{ a + }}")), + ("'

    \\8

    {{ a + }}'", "\n", "/x/cut.ts:4:23", Some("{{ a + }}")), + ("'

    \\\n\\n

    {{ a + }}'", "\n", "/x/cut.ts:5:7", Some("{{ a + }}")), + ("'

    \\\u{2028}

    {{ a + }}'", "\n", "/x/cut.ts:5:5", Some("{{ a + }}")), ]; #[test] diff --git a/napi/angular-compiler/index.d.ts b/napi/angular-compiler/index.d.ts index 3156c83db..2dde75fad 100644 --- a/napi/angular-compiler/index.d.ts +++ b/napi/angular-compiler/index.d.ts @@ -531,7 +531,12 @@ export interface ExtractedComponentMetadata { spanEnd: number /** The CSS selector. */ selector?: string - /** Inline template string. */ + /** + * Inline template string: the text Angular compiles, which for a literal + * written with escapes is what Angular's `EscapedCharacterCursor` reads + * from its raw text (`'\400'` is `"Ā"`, `\` CR LF keeps the LF). A lone + * surrogate (`'\uD83D'`) is kept as that one code unit. + */ template?: string /** URL to an external template file. */ templateUrl?: string diff --git a/napi/angular-compiler/src/lib.rs b/napi/angular-compiler/src/lib.rs index 17ac0a285..1de71240d 100644 --- a/napi/angular-compiler/src/lib.rs +++ b/napi/angular-compiler/src/lib.rs @@ -14,10 +14,14 @@ static ALLOC: mimalloc_safe::MiMalloc = mimalloc_safe::MiMalloc; use std::collections::HashMap; -use napi::{Task, bindgen_prelude::AsyncTask}; +use napi::{ + Task, + bindgen_prelude::{AsyncTask, Utf16String}, +}; use napi_derive::napi; use oxc_allocator::Allocator; +use oxc_angular_compiler::parser::{DepthLimits, with_depth_limits}; use oxc_angular_compiler::{ AngularVersion as RustAngularVersion, ChangeDetectionStrategy as RustChangeDetectionStrategy, HmrTemplateFields, HmrUpdateModuleOptions, HostMetadataInput as RustHostMetadataInput, @@ -34,6 +38,53 @@ use oxc_angular_compiler::{ use oxc_diagnostics::OxcDiagnostic; use oxc_napi::OxcError; +/// The depth limits a compilation first runs with, on the calling thread. At these +/// limits it needs at most about 1 MiB of stack more than a flat template (about +/// 10 KiB per template level and 2 KiB per expression level in an optimized build, +/// 30 KiB and 120 KiB in an unoptimized one), which any thread that calls the +/// binding has. Real templates rarely nest deeper. +const INLINE_DEPTH_LIMITS: DepthLimits = if cfg!(debug_assertions) { + DepthLimits { template: 8, expression: 8 } +} else { + DepthLimits { template: 32, expression: 64 } +}; + +/// The stack size of the thread a compilation runs on when its input nests deeper +/// than `INLINE_DEPTH_LIMITS`: enough for one nested as deep as the compiler allows +/// (`MAX_TEMPLATE_DEPTH`, `MAX_EXPRESSION_DEPTH`; deeper ones are reported, not +/// compiled). At those limits an optimized build uses up to about 20 MiB, an +/// unoptimized one up to about 500 MiB. Only the part of the stack used is backed +/// by memory. +const COMPILE_STACK_SIZE: usize = if cfg!(debug_assertions) { 1 << 30 } else { 64 << 20 }; + +/// Runs `compile` (a compilation of Angular templates) so that a deep template or +/// expression cannot overflow the stack and abort the process. +/// +/// The compiler recurses over templates and expressions, and the stack of the +/// thread that calls the binding is not ours to size (Node's main thread, a libuv +/// worker, another runtime's thread). So `compile` first runs here with low depth +/// limits (`INLINE_DEPTH_LIMITS`), which costs nothing. Only when its input nests +/// deeper does it run again, on a new thread with a large stack and the compiler's +/// own limits. (Handing every compilation to another thread made a compilation up +/// to almost 3 times as slow on a busy machine.) If that thread cannot start, the +/// input is reported as too deep. +fn compile_guarded(compile: impl Fn() -> T + Sync) -> T { + let shallow = match with_depth_limits(INLINE_DEPTH_LIMITS, &compile) { + Ok(value) => return value, + Err(shallow) => shallow, + }; + std::thread::scope(|scope| { + let thread = std::thread::Builder::new() + .name("oxc-angular-compile".to_string()) + .stack_size(COMPILE_STACK_SIZE) + .spawn_scoped(scope, &compile); + match thread { + Ok(thread) => thread.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)), + Err(_) => shallow, + } + }) +} + /// Angular version for version-conditional behavior. #[derive(Default, Clone)] #[napi(object)] @@ -742,16 +793,17 @@ pub fn compile_template_sync( file_path: String, options: Option, ) -> TemplateCompileResult { - let allocator = Allocator::default(); let opts: RustTransformOptions = options.unwrap_or_default().into(); - match compile_template_to_js_with_options( - &allocator, - &template, - &component_name, - &file_path, - &opts, - ) { + match compile_guarded(|| { + compile_template_to_js_with_options( + &Allocator::default(), + &template, + &component_name, + &file_path, + &opts, + ) + }) { Ok(output) => { // Convert source map to JSON string if present let map = output.map.map(|m| m.to_json_string()); @@ -905,14 +957,21 @@ pub fn compile_for_hmr_sync( styles: Option>, options: Option, ) -> HmrCompileResult { - let allocator = Allocator::default(); let opts: RustTransformOptions = options.unwrap_or_default().into(); // Generate component ID let component_id = format!("{file_path}@{component_name}"); // Compile template for HMR (returns template function, declarations, and template styles) - match compile_template_for_hmr(&allocator, &template, &component_name, &file_path, &opts) { + match compile_guarded(|| { + compile_template_for_hmr( + &Allocator::default(), + &template, + &component_name, + &file_path, + &opts, + ) + }) { Ok(output) => { let template_js = output.template_js; let declarations_js = if output.declarations_js.is_empty() { @@ -1159,7 +1218,6 @@ impl Task for CompileComponentHmrUpdateTask { compile_component_hmr_update, }; - let allocator = Allocator::default(); let rust_options: RustTransformOptions = self.options.take().unwrap_or_default().into(); let rust_resources = self .resolved_resources @@ -1176,14 +1234,16 @@ impl Task for CompileComponentHmrUpdateTask { compiled_class_names: compiled_class_names.as_deref(), }; - let update = compile_component_hmr_update( - &allocator, - &self.filename, - &self.source, - &input, - Some(&rust_options), - rust_resources.as_ref(), - ); + let update = compile_guarded(|| { + compile_component_hmr_update( + &Allocator::default(), + &self.filename, + &self.source, + &input, + Some(&rust_options), + rust_resources.as_ref(), + ) + }); Ok(ComponentHmrUpdateResult { hmr_module: update.module.unwrap_or_default(), @@ -1713,7 +1773,6 @@ impl Task for TransformAngularFileTask { ResolvedResources as RustResolvedResources, transform_angular_file, }; - let allocator = Allocator::default(); let rust_options: RustTransformOptions = self.options.take().unwrap_or_default().into(); // Convert resolved resources to Rust types @@ -1722,13 +1781,15 @@ impl Task for TransformAngularFileTask { .take() .map(|r| RustResolvedResources { templates: r.templates, styles: r.styles }); - let result = transform_angular_file( - &allocator, - &self.filename, - &self.source, - Some(&rust_options), - rust_resources.as_ref(), - ); + let result = compile_guarded(|| { + transform_angular_file( + &Allocator::default(), + &self.filename, + &self.source, + Some(&rust_options), + rust_resources.as_ref(), + ) + }); // Convert diagnostics to errors (for simplicity, all diagnostics become // errors — a warning-severity diagnostic would be promoted, and @@ -2107,8 +2168,11 @@ pub struct ExtractedComponentMetadata { pub span_end: u32, /// The CSS selector. pub selector: Option, - /// Inline template string. - pub template: Option, + /// Inline template string: the text Angular compiles, which for a literal + /// written with escapes is what Angular's `EscapedCharacterCursor` reads + /// from its raw text (`'\400'` is `"Ā"`, `\` CR LF keeps the LF). A lone + /// surrogate (`'\uD83D'`) is kept as that one code unit. + pub template: Option, /// URL to an external template file. pub template_url: Option, /// Inline styles array. @@ -2408,7 +2472,11 @@ pub fn extract_component_metadata_sync( span_start: metadata.class_span.start, span_end: metadata.class_span.end, selector: metadata.selector.as_ref().map(std::string::ToString::to_string), - template: metadata.template.as_ref().map(std::string::ToString::to_string), + template: metadata.template.as_ref().map(|template| { + Utf16String::from( + oxc_angular_compiler::encode_utf16(template).collect::>(), + ) + }), template_url: metadata .template_url .as_ref() @@ -3458,13 +3526,14 @@ pub fn link_angular_package_sync( ) -> LinkResult { use oxc_angular_compiler::linker::{LinkOptions as RustLinkOptions, link_with_options}; - let allocator = Allocator::default(); let options = options.unwrap_or_default(); let rust_options = RustLinkOptions { angular_version: options.angular_version.map(Into::into), sourcemap: options.sourcemap.unwrap_or(false), }; - let result = link_with_options(&allocator, &code, &filename, &rust_options); + let result = compile_guarded(|| { + link_with_options(&Allocator::default(), &code, &filename, &rust_options) + }); let errors = js_errors(&filename, Source::File(&code), result.errors); LinkResult { code: result.code, map: result.map, linked: result.linked, errors } diff --git a/napi/angular-compiler/test/deep-nesting.test.ts b/napi/angular-compiler/test/deep-nesting.test.ts new file mode 100644 index 000000000..c7a57f9e4 --- /dev/null +++ b/napi/angular-compiler/test/deep-nesting.test.ts @@ -0,0 +1,130 @@ +import { describe, it, expect } from 'vitest' + +import { + compileComponentHmrUpdate, + compileComponentHmrUpdateSync, + compileTemplate, + linkAngularPackage, + linkAngularPackageSync, + transformAngularFile, + transformAngularFileSync, +} from '../index.js' + +// Deep templates and expressions used to overflow the calling thread's stack and +// kill the process. A call now compiles a deep one again on a thread with a large +// stack, and a template or expression nested deeper than the compiler's limit +// (2000 levels; ngc overflows below 1000) is reported with the error ngc reports +// when its stack overflows. + +const RANGE_ERROR = 'RangeError: Maximum call stack size exceeded' + +const source = `import { Component } from '@angular/core'; +@Component({ selector: 'x-cut', templateUrl: './cut.html' }) +export class Cut { a: any; b: any }` + +const resources = (template: string) => ({ templates: { './cut.html': template }, styles: {} }) + +const repeat = (s: string, n: number) => s.repeat(n) + +/** Compiles (as deep as ngc compiles, and more). */ +const compiles = { + // The binding that killed the process. + chain: `

    `, + parens: `

    `, + elements: `${repeat('
    ', 1500)}x${repeat('
    ', 1500)}`, + branches: `@if (a) {x}${repeat(' @else if (b) {x}', 1500)}`, + conditionals: `

    `, + powers: `

    `, +} + +/** Too deep: reported. */ +const tooDeep = { + chain: `

    `, + parens: `

    `, + elements: `${repeat('
    ', 5_000)}x${repeat('
    ', 5_000)}`, + icus: `${repeat('{a, select, x {', 5_000)}y${repeat('}}', 5_000)}`, + branches: `@if (a) {x}${repeat(' @else if (b) {x}', 5_000)}`, + conditionals: `

    `, + nestedConditionals: `

    `, + powers: `

    `, +} + +describe('deeply nested templates', () => { + for (const [name, template] of Object.entries(compiles)) { + it(`compiles ${name}`, async () => { + const sync = transformAngularFileSync(source, '/x/cut.ts', {}, resources(template)) + expect(sync.errors).toEqual([]) + expect(sync.code).toContain('ɵɵdefineComponent') + const async = await transformAngularFile(source, '/x/cut.ts', {}, resources(template)) + expect(async.code).toBe(sync.code) + }, 60_000) + } + + for (const [name, template] of Object.entries(tooDeep)) { + it(`reports too deep ${name} from every entry point`, async () => { + const messages = (r: { errors: { message: string }[] }) => r.errors.map((e) => e.message) + expect( + messages(transformAngularFileSync(source, '/x/cut.ts', {}, resources(template))), + ).toEqual([RANGE_ERROR]) + expect( + messages(await transformAngularFile(source, '/x/cut.ts', {}, resources(template))), + ).toEqual([RANGE_ERROR]) + expect(messages(await compileTemplate(template, 'Cut', '/x/cut.ts', {}))).toEqual([ + RANGE_ERROR, + ]) + expect( + messages( + compileComponentHmrUpdateSync(source, '/x/cut.ts', 'Cut', {}, resources(template)), + ), + ).toEqual([RANGE_ERROR]) + expect( + messages( + await compileComponentHmrUpdate(source, '/x/cut.ts', 'Cut', {}, resources(template)), + ), + ).toEqual([RANGE_ERROR]) + + const partial = `import * as i0 from '@angular/core'; +export class Cut {} +Cut.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: '14.0.0', version: '22.3.0', ngImport: i0, type: Cut, selector: 'x-cut', template: ${JSON.stringify(template)}, isInline: true });` + for (const linked of [ + linkAngularPackageSync(partial, '/x/cut.mjs', {}), + await linkAngularPackage(partial, '/x/cut.mjs', {}), + ]) { + expect(linked.errors).toHaveLength(1) + expect(linked.errors[0].message).toContain(RANGE_ERROR) + } + }, 60_000) + } + + // ngc 22.3.0 reports these errors, and nothing else: it stops at them, before the + // step that overflows on the deep part. + const unexpectedSpan = expect.stringMatching(/^Unexpected closing tag "span"\. It may happen/) + const deepTemplatesWithErrors = { + beforeElements: [`

    ${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

    ') + }) +})