{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 [
+ ("'
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 + }}`", &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",
+ ]
+ );
+}
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 3e6c4f5380..56ccd9e5ed 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
@@ -821,10 +821,20 @@ const LITERAL_ERRORS: &[(&str, &str, &str, Option<&str>)] = &[
("`
\\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),
+ // 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]
From 5d1b0ab8c477f255e80966894df37d75120f42d9 Mon Sep 17 00:00:00 2001
From: LongYinan
Date: Thu, 3 Dec 2026 12:00:01 +0800
Subject: [PATCH 04/12] fix(compiler): show a lone surrogate in inline
templates as one code unit
A template with a lone surrogate (`'\uD83D'`) now compiles, so its stored
form (U+FDD0 + U+10F8xx) could leak:
- Template error messages show it as U+FFFD (what ngc's message reads as
once written out as UTF-8), and expression error columns count it as one
UTF-16 unit, like Angular. The expression lexer reads it as one character.
- Function names built from it get one `_`, like Angular's
`sanitizeIdentifier` (`Cut_Template_p_cl_k_0_listener`, `Cut_p__0_Template`).
- `extractComponentMetadataSync` returns the template with the lone code
unit itself (as a UTF-16 JS string) instead of the stored characters.
Co-Authored-By: Claude Opus 5.5
---
.../src/component/transform.rs | 5 +-
.../oxc_angular_compiler/src/i18n/digest.rs | 13 +----
crates/oxc_angular_compiler/src/lib.rs | 4 ++
.../src/parser/expression/lexer.rs | 24 +++++++-
.../src/parser/expression/parser.rs | 8 ++-
.../src/pipeline/phases/i18n_closure.rs | 9 ++-
.../src/pipeline/phases/naming.rs | 10 +++-
.../src/util/lone_surrogate.rs | 44 ++++++++++++++-
.../tests/inline_template_escapes_test.rs | 55 +++++++++++++++++++
napi/angular-compiler/index.d.ts | 7 ++-
napi/angular-compiler/src/lib.rs | 18 ++++--
.../test/extract-component-metadata.test.ts | 21 +++++++
12 files changed, 195 insertions(+), 23 deletions(-)
diff --git a/crates/oxc_angular_compiler/src/component/transform.rs b/crates/oxc_angular_compiler/src/component/transform.rs
index 001dde1000..1792e95ddd 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() {
diff --git a/crates/oxc_angular_compiler/src/i18n/digest.rs b/crates/oxc_angular_compiler/src/i18n/digest.rs
index 1b028b70f5..f2726b745d 100644
--- a/crates/oxc_angular_compiler/src/i18n/digest.rs
+++ b/crates/oxc_angular_compiler/src/i18n/digest.rs
@@ -233,17 +233,10 @@ impl Visitor for SerializerIgnoreIcuExpVisitor {
/// `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]> {
- use crate::util::lone_surrogate::{Piece, has_lone_surrogate, pieces};
- if !has_lone_surrogate(str) {
- return std::borrow::Cow::Borrowed(str.as_bytes());
+ 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()),
}
- let text: String = pieces(str)
- .map(|piece| match piece {
- Piece::Char(c) => c,
- Piece::Lone(_) => char::REPLACEMENT_CHARACTER,
- })
- .collect();
- std::borrow::Cow::Owned(text.into_bytes())
}
// ============================================================================
diff --git a/crates/oxc_angular_compiler/src/lib.rs b/crates/oxc_angular_compiler/src/lib.rs
index eda6c7fae5..6d67b165cc 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/parser/expression/lexer.rs b/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
index 1d6744e6c1..31df3ac2d5 100644
--- a/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
+++ b/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
@@ -593,8 +593,19 @@ impl<'a> Lexer<'a> {
/// 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) {
- match self.input.get(self.index as usize..).and_then(|rest| rest.chars().next()) {
+ 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();
}
@@ -602,6 +613,12 @@ impl<'a> Lexer<'a> {
}
}
+ /// 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.
fn is_eof(&self) -> bool {
self.index >= self.length
@@ -677,6 +694,11 @@ impl<'a> Lexer<'a> {
chars::AMPERSAND | chars::BAR => {
self.scan_complex_operator(start, ch, ch, Some(chars::EQ))
}
+ // 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)
+ }
_ => {
self.advance();
if ch.len_utf16() == 2 {
diff --git a/crates/oxc_angular_compiler/src/parser/expression/parser.rs b/crates/oxc_angular_compiler/src/parser/expression/parser.rs
index d3ce942dde..39fa6cbac9 100644
--- a/crates/oxc_angular_compiler/src/parser/expression/parser.rs
+++ b/crates/oxc_angular_compiler/src/parser/expression/parser.rs
@@ -963,8 +963,9 @@ 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 {
@@ -1184,12 +1185,13 @@ impl<'a> Parser<'a> {
}
/// 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
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 c8f86f6b1c..869ea6d2a5 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 27b9ca4a9c..813c7b7eb8 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/util/lone_surrogate.rs b/crates/oxc_angular_compiler/src/util/lone_surrogate.rs
index b2c0270c6f..8c608c5b63 100644
--- a/crates/oxc_angular_compiler/src/util/lone_surrogate.rs
+++ b/crates/oxc_angular_compiler/src/util/lone_surrogate.rs
@@ -83,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],
@@ -102,6 +104,34 @@ pub fn push_lone_surrogate(out: &mut String, unit: u16) {
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.
@@ -127,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/inline_template_escapes_test.rs b/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs
index 0039be67f9..2f090c81b9 100644
--- a/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs
+++ b/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs
@@ -156,3 +156,58 @@ fn octal_escape_in_a_template_literal() {
]
);
}
+
+/// 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. @/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/napi/angular-compiler/index.d.ts b/napi/angular-compiler/index.d.ts
index 3156c83db0..2dde75fad3 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 17ac0a2853..70dcb7788e 100644
--- a/napi/angular-compiler/src/lib.rs
+++ b/napi/angular-compiler/src/lib.rs
@@ -14,7 +14,10 @@ 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;
@@ -2107,8 +2110,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 +2414,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()
diff --git a/napi/angular-compiler/test/extract-component-metadata.test.ts b/napi/angular-compiler/test/extract-component-metadata.test.ts
index 66309ee8d4..5899415801 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`'
')
+ })
+})
From 631c3ec5f65ee9d2c50b24608a4a71513a6b2934 Mon Sep 17 00:00:00 2001
From: LongYinan
Date: Thu, 3 Dec 2026 12:01:27 +0800
Subject: [PATCH 05/12] fix(compiler): HTML parser errors and block parameters
like Angular
HTML lexer and parser errors now carry Angular's message, count, order and
span, and empty spans are widened to one character as ngc does:
- unexpected closing tag and void end tag spans, full name and link
- "Unclosed block" errors over the block start, outermost first
- "Opening tag not terminated" for unterminated attribute values
- self-close, @let, ICU Missing '}' / '{', block close messages
- entity, doctype, raw text, close tag and processing instruction errors
- `@iffy` is an unrecognized block, `:a` attributes are rejected
Block parameters keep their text as written (trailing whitespace too) and
are split like Angular's lexer, so `[a ? ]` and `@for (x of a(; track x)`
match ngc. A `}` closes the elements left open in its block.
Co-Authored-By: Claude Opus 5.5
---
.../snapshots/angular.snap.md | 98 +---
.../src/subsystems/html_lexer.rs | 1 +
crates/oxc_angular_compiler/src/ast/html.rs | 2 +
.../src/component/transform.rs | 11 +-
.../src/parser/html/lexer.rs | 453 ++++++++++--------
.../src/parser/html/parser.rs | 415 ++++++++++------
.../src/transform/control_flow.rs | 98 ++--
.../src/transform/html_to_r3.rs | 5 +-
.../src/util/deferred_time.rs | 10 +-
.../tests/html_parser_angular_errors_test.rs | 229 +++++++++
.../tests/html_parser_test.rs | 21 +-
.../tests/partial_component_test.rs | 2 +-
.../template_parse_error_position_test.rs | 29 +-
13 files changed, 853 insertions(+), 521 deletions(-)
create mode 100644 crates/oxc_angular_compiler/tests/html_parser_angular_errors_test.rs
diff --git a/crates/angular_conformance/snapshots/angular.snap.md b/crates/angular_conformance/snapshots/angular.snap.md
index 7909612a9a..f2f3d1dbe2 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 | 402 | 0 | 1 | 0 | 403 | 99.8% |
+| expression_parser | 401 | 1 | 1 | 0 | 403 | 99.5% |
| 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** | **1442** | **13** | **1** | **0** | **1456** | **99.0%** |
+| **Total** | **1448** | **7** | **1** | **0** | **1456** | **99.5%** |
## Failed Tests
@@ -29,99 +29,17 @@ 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 ${}`]"]
```
-### html_lexer
-
-#### should parse a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("")]
-```
-
-#### should parse a processing instruction ending with > instead of ?>: HtmlLexerTest { input: "", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction ending with > instead of ?>`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("")]
-```
-
-#### should parse a processing instruction surrounded by other content: HtmlLexerTest { input: "\n hello", test_type: HumanizeParts, expected: [Array [String("TokenType.DOC_TYPE"), String("DOCTYPE html")], Array [String("TokenType.TEXT"), String("\n")], Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"1.0\" encoding=\"UTF-8\"")], Array [String("TokenType.TEXT"), String(" hello")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction surrounded by other content`
-
-**Expected:**
-```
-5 tokens
-```
-
-**Actual:**
-```
-3 tokens: [Array [String("TokenType.DOC_TYPE"), String("DOCTYPE html")], Array [String("TokenType.TEXT"), String("\n hello")], Array [String("TokenType.EOF")]]
-```
-
-#### should parse a processing instruction that contains question marks inside quoted content: HtmlLexerTest { input: "-8\"?>", test_type: HumanizeParts, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"?\" encoding=\"UTF?>-8\"")], Array [String("TokenType.EOF")]], options: None }
-Path: `HtmlLexer/processing instructions/should parse a processing instruction that contains question marks inside quoted content`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("xml version=\"?\" encoding=\"UTF?>-8\"")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("-8\"?>")]
-```
-
-#### should store the location of a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeSourceSpans, expected: [Array [String("TokenType.PROCESSING_INSTRUCTION"), String("")], Array [String("TokenType.EOF"), String("")]], options: None }
-Path: `HtmlLexer/processing instructions/should store the location of a processing instruction`
-
-**Expected:**
-```
-Token 0: Array [String("TokenType.PROCESSING_INSTRUCTION"), String("")]
-```
-
-**Actual:**
-```
-Token 0: Array [String("TokenType.TEXT"), String("")]
-```
-
-#### should report missing end of a processing instruction: HtmlLexerTest { input: "", test_type: HumanizeErrors, expected: [Array [String("Unexpected character \"EOF\""), String("0:2")]], options: None }
-Path: `HtmlLexer/processing instructions/should report missing end of a processing instruction`
-
-**Expected:**
-```
-1 errors
-```
-
-**Actual:**
-```
-0 errors
-```
-
-### html_parser
-
-#### should ignore processing instruction: HumanizeDom { input: "hello", expected: [Array [String("html.Text"), String("hello"), Number(0.0), Array [String("hello")]]] }
-Path: `HtmlParser/parse/ignored syntax/should ignore processing instruction`
+#### 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:**
```
-[Array [String("html.Text"), String("hello"), Number(0.0), Array [String("hello")]]]
+Error containing: Unterminated template literal
```
**Actual:**
```
-[Array [String("html.Text"), String("hello"), Number(0), Array [String("hello")]]]
+No errors
```
### r3_transform
diff --git a/crates/angular_conformance/src/subsystems/html_lexer.rs b/crates/angular_conformance/src/subsystems/html_lexer.rs
index 11c0fbd75b..fb6c9fee06 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/html.rs b/crates/oxc_angular_compiler/src/ast/html.rs
index bf07f84890..424943cf19 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/transform.rs b/crates/oxc_angular_compiler/src/component/transform.rs
index 1792e95ddd..0e217d2f5c 100644
--- a/crates/oxc_angular_compiler/src/component/transform.rs
+++ b/crates/oxc_angular_compiler/src/component/transform.rs
@@ -6616,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/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs
index acaa9bed5d..a6903decbb 100644
--- a/crates/oxc_angular_compiler/src/parser/html/lexer.rs
+++ b/crates/oxc_angular_compiler/src/parser/html/lexer.rs
@@ -67,6 +67,8 @@ pub enum HtmlTokenType {
AttrValueInterpolation,
/// DOCTYPE
DocType,
+ /// A processing instruction (``), which the parser skips.
+ ProcessingInstruction,
/// Expansion form start: `{`
ExpansionFormStart,
/// Expansion case value
@@ -545,6 +547,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 +580,10 @@ 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.
+ attr_value_unterminated: bool,
/// Enable escape sequence processing (for inline template strings).
escaped_string: bool,
/// Enable block tokenization (default: true).
@@ -614,6 +622,7 @@ impl<'a> HtmlLexer<'a> {
selectorless_enabled: false,
tokenize_icu: false,
expansion_case_stack: Vec::new(),
+ attr_value_unterminated: false,
escaped_string: false,
tokenize_blocks: true, // default to true like Angular
tokenize_let: true, // default to true like Angular
@@ -729,16 +738,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 +795,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 +1037,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 +1164,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 +1254,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 +1455,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 +1508,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 +1591,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 +1719,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 +1767,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 +1981,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 +2066,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 +2272,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 +2294,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 +2464,9 @@ impl<'a> HtmlLexer<'a> {
self.advance();
self.skip_whitespace();
self.scan_attribute_value();
+ if self.attr_value_unterminated {
+ break;
+ }
}
}
}
@@ -2608,6 +2607,9 @@ impl<'a> HtmlLexer<'a> {
self.advance();
self.skip_whitespace();
self.scan_attribute_value();
+ if self.attr_value_unterminated {
+ break;
+ }
}
}
}
@@ -2642,11 +2644,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
@@ -2935,16 +2934,58 @@ impl<'a> HtmlLexer<'a> {
}
let content = &self.input[content_start as usize..self.index as usize];
- if self.peek() == '>' {
- self.advance();
- } else {
- // Report error for unterminated DOCTYPE
- self.error("Unexpected end of DOCTYPE");
+ if self.peek() != '>' {
+ // As Angular's cursor at the end of the input; the DOCTYPE is dropped.
+ self.error("Unexpected character \"EOF\"");
+ return;
}
+ self.advance();
self.tokens.push(HtmlToken::with_part(HtmlTokenType::DocType, content, start, self.index));
}
+ /// Scans a processing instruction after ``, as Angular's
+ /// `_consumeProcessingInstruction`: up to a `?` or `>` outside quotes, then `>`.
+ fn scan_processing_instruction(&mut self, start: u32) {
+ let content_start = self.index;
+ while self.index < self.length && self.peek() != '?' && self.peek() != '>' {
+ let ch = self.peek();
+ self.advance();
+ if ch == '"' || ch == '\'' || ch == '`' {
+ while self.index < self.length && self.peek() != ch {
+ if self.peek() == '\\' {
+ self.advance();
+ }
+ if self.index < self.length {
+ self.advance();
+ }
+ }
+ if self.index < self.length {
+ self.advance(); // closing quote
+ }
+ }
+ }
+ if self.index >= self.length {
+ self.error("Unexpected character \"EOF\"");
+ return;
+ }
+ let content = self.input[content_start as usize..self.index as usize].to_string();
+ let end_char = self.advance();
+ if end_char == '?' {
+ if self.peek() != '>' {
+ self.error(&self.unexpected_character_message());
+ return;
+ }
+ self.advance();
+ }
+ self.tokens.push(HtmlToken::with_part(
+ HtmlTokenType::ProcessingInstruction,
+ &content,
+ start,
+ self.index,
+ ));
+ }
+
/// Scans a CDATA section.
fn scan_cdata(&mut self, start: u32) {
// Skip ![CDATA[
@@ -3055,9 +3096,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 +3111,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 +3128,7 @@ impl<'a> HtmlLexer<'a> {
self.index,
));
- if self.peek() == ',' {
- self.advance();
- }
+ self.advance(); // consume ','
self.skip_whitespace();
}
@@ -3091,6 +3137,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,
@@ -3204,11 +3255,12 @@ impl<'a> HtmlLexer<'a> {
// 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
@@ -3313,27 +3365,38 @@ impl<'a> HtmlLexer<'a> {
num_str.push(self.advance());
}
- // Check for semicolon and that we have at least one digit
- if self.peek() == ';' && !num_str.is_empty() {
+ if self.peek() == ';' {
let num_str = num_str.as_str();
self.advance(); // consume ';'
// Parse and decode
- if let Ok(code_point) =
+ let code_point =
if is_hex { u32::from_str_radix(num_str, 16) } else { num_str.parse::() }
- {
- if let Some(ch) = char::from_u32(code_point) {
- let decoded = ch.to_string();
- let marker = hex_marker.map(String::from).unwrap_or_default();
- let original = format!("{marker}{num_str};");
- self.tokens.push(HtmlToken::new(
- HtmlTokenType::EncodedEntity,
- vec![decoded, original],
- start,
- self.index,
- ));
- return true;
- }
+ .ok();
+ // Angular's `String.fromCodePoint` throws for no digits or a value past
+ // U+10FFFF: an unknown entity, reported after the `;`.
+ if code_point.is_none_or(|code_point| code_point > 0x0010_FFFF) {
+ let entity_str = &self.input[start as usize..self.index as usize];
+ let msg = format!(
+ "Unknown entity \"{entity_str}\" - use the \";\" or \";\" syntax"
+ );
+ self.push_error(msg, (self.line, self.column), self.index, self.index);
+ self.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 +3410,19 @@ 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,
+ );
} 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);
}
// Revert and treat as text
self.index = start;
@@ -3381,8 +3441,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 +3460,14 @@ impl<'a> HtmlLexer<'a> {
}
// Named entity with semicolon but unknown name - this is an error
- self.errors.push(HtmlTokenError {
- msg: format!(
+ self.push_error(
+ format!(
"Unknown entity \"{name}\" - use the \";\" or \";\" syntax"
),
- position: (start_line, start_col),
- offset: start,
- });
+ (start_line, start_col),
+ start,
+ self.index,
+ );
// 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 0df96651d0..826c72cf4d 100644
--- a/crates/oxc_angular_compiler/src/parser/html/parser.rs
+++ b/crates/oxc_angular_compiler/src/parser/html/parser.rs
@@ -160,7 +160,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));
}
@@ -179,9 +181,24 @@ impl<'a> HtmlParser<'a> {
/// 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 +210,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],
@@ -305,10 +319,17 @@ 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,
- });
+ 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`]).
+ fn inherited_prefix(&self, depth: usize) -> Option<&str> {
+ let elements =
+ self.container_stack[..depth].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 {
(
@@ -320,13 +341,41 @@ impl<'a> HtmlParser<'a> {
};
let tag_def = get_html_tag_definition(local_name);
if tag_def.prevent_namespace_inheritance {
- return false;
+ return None;
}
- if prefix.is_some() || tag_def.implicit_namespace_prefix.is_some() {
- return true;
+ if let Some(prefix) = prefix.or(tag_def.implicit_namespace_prefix) {
+ return Some(prefix);
}
}
- false
+ None
+ }
+
+ /// 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 +385,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 +413,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 +490,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] {
+ 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);
+ };
+
+ 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 +678,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 +704,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 +771,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 +808,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 +828,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 +846,36 @@ 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 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 full_name =
- if prefix.is_empty() { name.to_string() } else { format!(":{}:{}", prefix, name) };
- (full_name, name.to_string())
- };
+ let (tag_name, local_name, message_name) =
+ if token.token_type == HtmlTokenType::ComponentClose {
+ let name = token.value().to_string();
+ (name.clone(), 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().to_string();
+ let name = token.name().to_string();
+ let full_name =
+ if prefix.is_empty() { name.clone() } else { format!(":{prefix}:{name}") };
+ let message_name = self.angular_full_name(&prefix, &name);
+ (full_name, name, message_name)
+ };
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 = format!(
+ "Unexpected closing tag \"{message_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 +884,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 +932,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;
@@ -1334,18 +1429,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 +1496,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 = ;`"
),
@@ -1458,34 +1559,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 +1608,20 @@ 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;
+ let (brace_start, exp_start) = match self.peek() {
+ Some(tok) if tok.token_type == HtmlTokenType::ExpansionCaseExpStart => {
+ let span = (tok.start, tok.end);
self.advance();
- s
- } else {
- value_end
+ span
+ }
+ 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;
}
- } else {
- value_end
};
+ let errors_before = self.errors.len();
// Parse expansion content in isolation
// Following Angular's approach: save current state, parse content, restore state
@@ -1546,6 +1642,14 @@ impl<'a> HtmlParser<'a> {
}
}
+ // 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 +1674,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 {
@@ -1608,18 +1704,28 @@ impl<'a> HtmlParser<'a> {
expansion.push(node);
}
- // Consume ExpansionCaseExpEnd
- let exp_end = if let Some(tok) = self.peek() {
- if tok.token_type == HtmlTokenType::ExpansionCaseExpEnd {
+ // Consume ExpansionCaseExpEnd. A case without its `}` is reported at its `{`,
+ // as Angular's `_collectExpansionExpTokens`; a case whose content has an
+ // error drops the expansion, as Angular's `_parseExpansionCase`.
+ let exp_end = match self.peek() {
+ Some(tok) 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
+ _ => {
+ let err = self.make_span_error(
+ brace_start,
+ exp_start,
+ "Invalid ICU message. Missing '}'.",
+ );
+ self.errors.push(err);
+ return None;
+ }
};
+ 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);
@@ -1659,7 +1765,7 @@ impl<'a> HtmlParser<'a> {
"loading" => BlockType::Loading,
"boundary" => BlockType::Boundary,
"error" => BlockType::Error,
- _ => BlockType::If, // Default
+ _ => BlockType::Unknown,
};
// Collect block parameters
@@ -1865,16 +1971,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/transform/control_flow.rs b/crates/oxc_angular_compiler/src/transform/control_flow.rs
index 190b512a07..4203179232 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;
}
@@ -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,
}
@@ -1759,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());
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 54cb55562e..1b8ee2af3d 100644
--- a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs
+++ b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs
@@ -2531,8 +2531,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(
diff --git a/crates/oxc_angular_compiler/src/util/deferred_time.rs b/crates/oxc_angular_compiler/src/util/deferred_time.rs
index 8ec3c99060..0d9fef0482 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/tests/html_parser_angular_errors_test.rs b/crates/oxc_angular_compiler/tests/html_parser_angular_errors_test.rs
new file mode 100644
index 0000000000..4cc33d2606
--- /dev/null
+++ b/crates/oxc_angular_compiler/tests/html_parser_angular_errors_test.rs
@@ -0,0 +1,229 @@
+//! 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 \";\" syntax",
+ "&unknown;",
+ )],
+ ),
+ ("", &[("Unknown entity \"\" - use the \";\" or \";\" syntax", "`")]),
+ (
+ "",
+ &[("Unknown entity \"\" - use the \";\" or \";\" syntax", "`")],
+ ),
+ (
+ "",
+ &[(
+ "Unknown entity \"\" - use the \";\" or \";\" syntax",
+ "`",
+ )],
+ ),
+ ("&;", &[("Unknown entity \"\" - use the \";\" or \";\" 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 ) {")],
+ ),
+ ("
`", "\r\n", "/x/cut.ts:5:3", Some("{{ a + }}")),
(
"`
\n \n
`",
@@ -814,18 +813,18 @@ 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", "/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
\\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 + }}")),
From d385a29ce16173b9234e8fa06865b30b54c36e11 Mon Sep 17 00:00:00 2001
From: LongYinan
Date: Thu, 3 Dec 2026 12:46:13 +0800
Subject: [PATCH 06/12] fix(compiler): ICU text, nested ICU errors, attribute
entities and end tag cost like Angular
- `@` inside an ICU case or interpolation does not end the text, as Angular's
`_isTextEnd`: `me@forum.com` in a case is text again. `a@letter` outside
ICUs is an incomplete `@let`, and `@content` is lexed as a block, as in
Angular 22.3's SUPPORTED_BLOCKS.
- An ICU case finds its `}` first, as `_collectExpansionExpTokens`, so a
nested ICU with an error no longer adds a "Missing '}'" to the outer case.
Nested case ends are kept from the outer scan, so nothing is scanned twice.
- An entity error in an attribute value stops the tag, as `_consumeTagOpen`
does ("Opening tag not terminated" and the stray end tag). Our entity error
is kept. Unquoted attribute values decode entities, as ngc does.
- Each open element and block keeps the namespace it passes down, so naming
an end tag reads one container instead of walking the stack, and the
"Unexpected closing tag" message is built only for an error.
Co-Authored-By: Claude Opus 5.5
---
.../src/parser/html/lexer.rs | 132 ++++++++--
.../src/parser/html/parser.rs | 239 ++++++++++++------
.../tests/html_parser_angular_errors_test.rs | 165 +++++++++++-
3 files changed, 440 insertions(+), 96 deletions(-)
diff --git a/crates/oxc_angular_compiler/src/parser/html/lexer.rs b/crates/oxc_angular_compiler/src/parser/html/lexer.rs
index a6903decbb..a3611e51ca 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)]
@@ -582,8 +595,11 @@ pub struct HtmlLexer<'a> {
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.
+ /// 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).
@@ -623,6 +639,7 @@ impl<'a> HtmlLexer<'a> {
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
@@ -2508,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;
}
@@ -2631,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 {
@@ -2710,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,
));
}
@@ -2731,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)
@@ -2863,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();
@@ -3235,20 +3328,16 @@ 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;
}
@@ -3340,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;
@@ -3381,6 +3471,7 @@ impl<'a> HtmlLexer<'a> {
"Unknown entity \"{entity_str}\" - use the \";\" or \";\" syntax"
);
self.push_error(msg, (self.line, self.column), self.index, self.index);
+ self.entity_error = Some(EntityError::At(self.index, self.line, self.column));
self.index = start;
self.line = start_line;
self.column = start_col;
@@ -3416,6 +3507,7 @@ impl<'a> HtmlLexer<'a> {
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];
@@ -3423,6 +3515,7 @@ impl<'a> HtmlLexer<'a> {
self.push_error(format!(
"Unable to parse entity \"{entity_str}\" - {entity_type} character reference entities must end with \";\""
), (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;
@@ -3468,6 +3561,7 @@ impl<'a> HtmlLexer<'a> {
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 826c72cf4d..424a4560eb 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,
@@ -60,6 +61,15 @@ 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
"), "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!("{}
{}", 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/napi/angular-compiler/src/lib.rs b/napi/angular-compiler/src/lib.rs
index 70dcb7788e..1de71240d1 100644
--- a/napi/angular-compiler/src/lib.rs
+++ b/napi/angular-compiler/src/lib.rs
@@ -21,6 +21,7 @@ use napi::{
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,
@@ -37,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)]
@@ -745,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());
@@ -908,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() {
@@ -1162,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
@@ -1179,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(),
@@ -1716,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
@@ -1725,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
@@ -3468,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 0000000000..c7a57f9e47
--- /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('
', 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)
+})
From 2b9334fa4d5b8ef8a1466491b75f64970ca52152 Mon Sep 17 00:00:00 2001
From: LongYinan
Date: Thu, 3 Dec 2026 14:07:17 +0800
Subject: [PATCH 10/12] test(compiler): update tests where two of the combined
fixes meet
- A bare lone surrogate in an expression now gives Angular's two errors
(the lexer error token, then the lexer error), now that the escapes
fix reaches the Angular-style expression lexer.
- The closing-tag message now has Angular's 'For more info see' tail.
- Conformance snapshot: 1449/1456 (main 1441), no test newly failing.
Co-Authored-By: Claude Opus 5.5
---
.../snapshots/angular.snap.md | 17 ++---------------
.../tests/inline_template_escapes_test.rs | 4 +++-
2 files changed, 5 insertions(+), 16 deletions(-)
diff --git a/crates/angular_conformance/snapshots/angular.snap.md b/crates/angular_conformance/snapshots/angular.snap.md
index f2f3d1dbe2..df40697d4d 100644
--- a/crates/angular_conformance/snapshots/angular.snap.md
+++ b/crates/angular_conformance/snapshots/angular.snap.md
@@ -7,7 +7,7 @@
| 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 | 297 | 0 | 0 | 0 | 297 | 100.0% |
| html_parser | 90 | 0 | 0 | 0 | 90 | 100.0% |
@@ -15,7 +15,7 @@
| 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** | **1448** | **7** | **1** | **0** | **1456** | **99.5%** |
+| **Total** | **1449** | **6** | **1** | **0** | **1456** | **99.5%** |
## Failed Tests
@@ -29,19 +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
-```
-
### 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/oxc_angular_compiler/tests/inline_template_escapes_test.rs b/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs
index 2f090c81b9..9e08476f5f 100644
--- a/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs
+++ b/crates/oxc_angular_compiler/tests/inline_template_escapes_test.rs
@@ -181,7 +181,9 @@ fn lone_surrogate_in_error_messages() {
(
r"'
x'",
"Unexpected closing tag \"q\u{FFFD}\". It may happen when the tag has already been \
- closed by another tag. @/w/cut.ts:4:18",
+ 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());
From 8420ad88148cd2d7bf197e246a1aa6ad2beadcf4 Mon Sep 17 00:00:00 2001
From: LongYinan
Date: Thu, 3 Dec 2026 14:19:19 +0800
Subject: [PATCH 11/12] style(compiler): collapse a nested if in the HTML
parser
Co-Authored-By: Claude Opus 5.5
---
.../oxc_angular_compiler/src/parser/html/parser.rs | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/crates/oxc_angular_compiler/src/parser/html/parser.rs b/crates/oxc_angular_compiler/src/parser/html/parser.rs
index 3eefe6b1bc..609232ce73 100644
--- a/crates/oxc_angular_compiler/src/parser/html/parser.rs
+++ b/crates/oxc_angular_compiler/src/parser/html/parser.rs
@@ -575,12 +575,12 @@ impl<'a> HtmlParser<'a> {
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;
- }
+ 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;
}
}
From e2ef0db1ba72cb5295be32b9b4b91c18ab8607f1 Mon Sep 17 00:00:00 2001
From: LongYinan
Date: Thu, 3 Dec 2026 14:32:29 +0800
Subject: [PATCH 12/12] fix(compiler): a line break in a regex binding is an
error again
Angular's lexer reads a line break as part of a regex, and ngc then
emits invalid JavaScript with no error. Main reported the regex as
unterminated; keep that error (also for U+2028 and U+2029).
Co-Authored-By: Claude Opus 5.5
---
.../src/parser/expression/lexer.rs | 5 +-
.../tests/expression_lexer_error_text_test.rs | 46 +++++++++++++++++++
2 files changed, 50 insertions(+), 1 deletion(-)
diff --git a/crates/oxc_angular_compiler/src/parser/expression/lexer.rs b/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
index 31df3ac2d5..9805efb2ea 100644
--- a/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
+++ b/crates/oxc_angular_compiler/src/parser/expression/lexer.rs
@@ -1080,7 +1080,10 @@ impl<'a> Lexer<'a> {
let mut in_character_class = false;
loop {
let ch = self.peek();
- if ch == chars::EOF {
+ // 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_escape {
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
index c4d2dfb8d2..360897360d 100644
--- a/crates/oxc_angular_compiler/tests/expression_lexer_error_text_test.rs
+++ b/crates/oxc_angular_compiler/tests/expression_lexer_error_text_test.rs
@@ -774,6 +774,52 @@ const KNOWN_DIFFERENCES: &[Case] = &[
"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`.