Skip to content

fix(compiler): older template bugs (deep input crash, lexer errors, escapes, ngNonBindable ICUs, …) - #756

Merged
Brooooooklyn merged 12 commits into
mainfrom
fix/older-template-bugs
Dec 4, 2026
Merged

Brooooooklyn merged 12 commits into
mainfrom
fix/older-template-bugs

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Member

Follow-up to #753 and #754: the older template bugs they listed as "not covered". Every expected value comes from Angular 22.3.0 (parseTemplate, and ngc NgtscProgram for emitted code and file:line:col).

A  deep input      ─ 500+ terms / deep tags crash the process    napi/src/lib.rs, parser/*, html_to_r3.rs
B  lexer errors    ─ error text and order                        parser/expression/lexer.rs
C  big numbers     ─ 100000000000000000000000 lexed to 0         parser/expression/lexer.rs
D  HTML errors     ─ zero-width labels, message text             parser/html/*
E  block params    ─ lost trailing spaces, "Incomplete block"    parser/html/lexer.rs
F  entity + {{ }}  ─ no whitespace folding after an entity       transform/html_to_r3.rs
G  ngNonBindable   ─ ICU still compiled                          transform/html_to_r3.rs
H  ngIfElse order  ─ consts order                                transform/html_to_r3.rs
I  escapes         ─ \u surrogate pairs, octal in inline tpl     component/transform.rs, util/lone_surrogate.rs

A. Deep input no longer crashes the process

Before, a long a + a + … chain, deep ( ( ( a ) ) ), nested ternaries, ** chains, deep <div>s or @ifs overflowed the native stack. Node died with exit 139 / 132 and no message.

compile (calling thread, low depth limits)
   │
   ├─ fits ──────────────────────────────▶ result   (almost every template)
   │
   └─ hit a limit ─▶ compile again on a new thread with a big stack
                          │
                          ├─ fits ───────▶ result
                          └─ still too deep ▶ "RangeError: Maximum call stack size exceeded"
  • Every recursive cycle in the expression parser and the HTML parser has a depth check. The expression lexer is now a loop (nested template literals and ${} used to recurse).
  • HTML errors win over the RangeError, as in ngc: its _TreeBuilder keeps open tags in a list and stops at HTML errors before the deep walk.
input ngc main this PR
a.b + a.b + … ×1900 compiles crash (exit 139) compiles
same ×100000, or 100000 (, [, <div>, @if RangeError crash RangeError
a ? a : … ×300000, a ** … ×1M RangeError crash RangeError
<p></span></p> + 2100 nested <div> Unexpected closing tag "span" 1:4 crash same as ngc
@switch with 2100 cases, {{ a b }} in the first Unexpected token 'b'… 1:25 crash same as ngc

Cost: nothing for normal templates (calls stay on the calling thread). Best of 4 runs, interleaved:

case main this PR
[a.b, …] ×8000 111 ms 112 ms
{{ a.b }} ×8000 172 ms 174 ms
[a.b, …] ×32000 429 ms 454 ms
entity attrs ×16000 312 ms 319 ms
entity text ×16000 342 ms 336 ms

Templates deeper than the inline limit (release: 32 tag levels / 64 expression levels) are compiled twice; e.g. 40 nested divs 109 → 189 µs.

B. Expression lexer errors

input Angular main
'abc 1. Unexpected token Lexer Error: Unterminated quote at column 4 …
2. Lexer Error: Unterminated quote … at the end of the expression ['abc]
Unterminated string + Unexpected token Unterminated string at column 1
a # b 1. Unexpected token 'Lexer Error: Invalid character [#] …'
2. Lexer Error: … at column 5 in [a # b]
same 2 errors, other order
'\u12' 3 errors: unicode escape ×2, then Unterminated quote at column 6 3 errors, other text and order
a; 'b … chained expression at column 6, then Unterminated quote at column 5 Unterminated string, … at column 4
{{ a \uD83D }} (inline) 2 errors: Unexpected token 'Lexer Error: Unexpected character […]…' + the lexer error 1 error, other text

Lexer errors now use Angular's text (Lexer Error: {msg} at column N in expression [input]), and the parser reports them where Angular does, in Angular's order. A lone surrogate prints as U+FFFD (what ngc's output shows too).

C. Number literals

input ngc main this PR
100000000000000000000000 1e+23 0 1e+23
0x10 error Unexpected token 'x10' compiles same as ngc
'\x41' "x41" "A" same as ngc

D. HTML parser errors

input Angular main
{a, select, x {</i>}} Unexpected closing tag "i"…, label width 4 label width 0
<p [x]="\"abc"></p> Opening tag "p" not terminated. Unexpected end of tag 'p'
<p>@content</p>, <p>a@letter</p> Incomplete block … / Incomplete @let … no error
{a, select, x {a@error.com}} no error Incomplete block "error"
</p> … For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags no tail

Entities in unquoted attribute values are now decoded, as Angular does: <div title=a&amp;b> → consts ["title","a&b"] (main kept a&amp;b).

E. Block parameters

input Angular main
@if (a + ) {x} … [a + ] (spaces kept) [a +]
@for (x of a(; track x) {} Unexpected end of expression: a( + Missing expected ) Incomplete block "for"
@for (x of y; track ) {} only must have a "track" expression + Unrecognized @for loop parameter "track"

F. Whitespace folding after an entity

input ngc main
<p>&amp; {{ "a b" }}</p> textInterpolate1("& ", "a b") "a b"
<p>&amp;{{ a + }}</p> error text [ a + ] [ a + ]

<pre> keeps the spaces, as in ngc.

G. ICUs under ngNonBindable

input ngc main
<div ngNonBindable>{a, plural, =0 {x}}</div> domElement(0,"div") only i18n const + i18nExp(ctx.a)

H. Value-less microsyntax keys come first in consts

input ngc main
<div *ngIf="a; else"> [4,"ngIfElse","ngIf"] [4,"ngIf","ngIfElse"]
<li *ngFor="let x of xs; as"> [4,"ngFor","ngForAs","ngForOf"] [4,"ngFor","ngForOf","ngForAs"]

I. Escapes in inline templates

Before, these fell back to "line L, column C of the template" or were not compiled at all.

inline template ngc main
'<p>a😀b</p>{{ a + }}' error cut.ts:4:35 template-relative fallback
'<p>a\777b</p>{{ a + }}' error cut.ts:4:27 fallback
'<p>a\400b</p>' text "aĀb" "a 0b"
'<p>a\<CR><LF>b</p>' text "a\nb" "ab"
'<p>a\uD83Db</p>' (lone surrogate) text(1,"a\uD83Db") no ɵcmp, no error
'<p (cl\uD83Dk)="…">' listener …_p_cl_k_0_listener not compiled

A lone surrogate is kept inside Rust strings as two private-use chars (util/lone_surrogate.rs); every lexer, column count and printer counts it as one UTF-16 unit.

Checks

  • Valid templates compile byte-identically to main: 145 repo components × AOT / JIT / HMR (435 pairs), 0 differences.
  • cargo test --workspace: 4118 passed. napi: 623 passed. Conformance 1441 → 1449 / 1456 (8 now pass, none regress).
  • New tests fail without the fixes: deep_nesting_test.rs, napi/test/deep-nesting.test.ts, expression_lexer_error_text_test.rs, html_parser_angular_errors_test.rs, r3_transform_ngc_parity_test.rs, inline_template_escapes_test.rs.
  • No new clippy warnings on changed lines (2 as u32 casts follow the file's style).
  • A local Codex adversarial review found 2 issues:
    • fixed: the new regex scanner (copied from Angular) let a line break into a regex, so [x]="/a⏎b/" emitted invalid JS with no error. ngc does the same, but main reported Unterminated regular expression; that error is back (also for U+2028 / U+2029).
    • left as is: many lexer errors in one huge binding use a lot of memory (see below).

Known differences from Angular (left on purpose)

  • Deep TypeScript or CSS (:is( ×10000) still crashes as on main: that recursion is in the oxc parser / CSS selector parser, not in templates.
  • A too-deep expression gets its RangeError at the binding; ngc reports it with no position.
  • ICUs nested past the limit (~1000) skip the rest of the input, so HTML errors after that point are not reported. ngc reports them up to ~2000 ICUs.
  • We keep an entity error inside an attribute value (Unknown entity "foo") that Angular swallows, then give ngc's 2 errors too. Dropping an error is a product call.
  • @content (new in Angular 22.3) is lexed as a block but not supported: Unrecognized block @content.
  • <div ngNonBindable i18n>a{x, plural, =0 {y}}b</div>: ngc crashes on it; we report a placeholder error.
  • A lone surrogate in an error message shows as U+FFFD; a template from a const with a lone surrogate is still not compiled (as on main).
  • <div i18n>@let x = 1;</div> keeps main's output (ngc drops the @let here).
  • [x]="/a⏎b/": we report Unterminated regular expression; Angular is silent and ngc emits invalid JS.
  • Each lexer error repeats the whole binding in its text, as Angular's does. So an 18 KB binding with 3000 bad numbers (1e2e+ ×3000) gives 3001 errors, like Angular, and ~780 MB peak memory (Angular ~90 MB, because JS strings share the input). Main already does this for other repeated errors (1__0+ ×3000: 3001 errors, 310 MB). A cap would drop errors Angular reports, so it is left for a separate decision.

🤖 Generated with Claude Code

Brooooooklyn and others added 12 commits December 3, 2026 13:56
The expression lexer is now a port of Angular's `_Scanner`:

- Errors are error tokens with Angular's text ("Lexer Error: ... at column N
  in expression [input]", N in UTF-16 units) and the parser reports each one
  when it reaches it (in `skip`, with Angular's location quirk, and in
  template literals), instead of collecting them all up front. The count and
  order now follow the parse, as in Angular.
- Characters Angular does not know (`~`, `@`, `\`, `é`, ...) are
  "Unexpected character" errors; a character outside the BMP gives two (one
  per UTF-16 half). "Unterminated quote", "Invalid unicode escape" and the
  rest use Angular's text, position and recovery.
- Numbers read like Angular's parseInt / parseFloat:
  `100000000000000000000000` is 1e+23 (was 0), `1.2.3` is 1.2, and there are
  no hex / octal / binary numbers (`0x10` is an error, as in ngc).
- Strings only know \n \f \r \t \v and \uXXXX (`'\x41'` is "x41");
  surrogate escapes pair up, a lone one is kept.
- Template literals use Angular's brace stack, so `${...}` holds any token.
- `/` starts a regex where Angular's isStartOfRegex says so; regex flags are
  checked by the parser with Angular's messages.
- @defer trigger errors print numbers and template parts as Angular does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…time without trim

- A lone surrogate in a template literal part (`\`\uD83D\``, also tagged) is
  printed as U+FFFD, as ngtsc's UTF-8 output does, instead of the internal
  lone-surrogate marker.
- "Unexpected token" messages show a token's lone surrogate as U+FFFD
  (Token::message_text, shared by the expression parser and @defer triggers).
- @defer time values are matched like Angular's TIME_PATTERN, with no trim,
  so `timer(~ 1)`, `timer(é 1)` and `idle(~ 1)` again give "Could not parse
  time value of trigger".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…racterCursor

ngtsc parses an inline template string or template literal from its raw
text with Angular's EscapedCharacterCursor. `cook_literal` returned None for
a `\u` surrogate pair, a lone surrogate, a legacy octal escape and `\8`/`\9`,
so template errors fell back to "line L, column C of the template" and
`ɵɵattachSourceLocations` was left out. It now maps every escape to its
backslash as the cursor does.

The template Angular compiles is what the cursor reads, which is not always
the literal's value: `\400`..`\777` take three octal digits, a line
continuation skips one character (`\` CR LF keeps the LF, `\` U+2028 keeps
U+2028), and after `\` LF the next character is read as written. The
component metadata now holds that text, so the output matches ngc.

A template with a lone surrogate was left uncompiled with no error; it now
compiles, and i18n message ids hash a lone surrogate as U+FFFD like
TextEncoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…d 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 <noreply@anthropic.com>
…value-less template attrs like Angular

- A text with an HTML entity parses its interpolations from the text value
  (whitespace folded unless preserved), as Angular's parseInterpolation does,
  not from the raw tokens. `&amp;{{ a   + }}` now prints `[ a + ]`,
  `&amp;{{ <U+3000>// c }}` reports the comment-only error, and
  `&amp; {{ "a   b" }}` compiles to "a b" like ngc.
- An ICU inside ngNonBindable is dropped (NonBindableVisitor.visitExpansion),
  and an element inside ngNonBindable has no i18n. An i18n element starts an
  i18n block when its message is not empty (from its HTML children), so
  `<div ngNonBindable i18n>{a, plural, ...}</div>` keeps ɵɵi18n like ngc.
- A microsyntax key with no value (`*ngIf="c; else"`) is a literal template
  attribute, listed before the bound ones: [4, "ngIfElse", "ngIf"].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nBindable

Keep the old "R3 children not empty" check in ingest and add only the
ngNonBindable case, whose ICU children are dropped. An i18n element whose only
children are @let, <script>, <style> or <link rel=stylesheet> compiles as on
main again. Move the doc comment of wrap_component_in_template back above it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cess

A deep template or expression (a 500-term `a.b + a.b + ...` binding in a
debug build, a few thousand levels in a release build) overflowed the
calling thread's stack and killed the process (SIGSEGV / SIGILL).

- The NAPI binding compiles on threads with a large stack (64 MiB, 1 GiB in
  debug builds): one compile thread per calling thread, kept for later
  calls, for every entry point that parses or compiles.
- The template parser and the expression parser stop at 2000 levels
  (`MAX_TEMPLATE_DEPTH`, `MAX_EXPRESSION_DEPTH`), and so do `@if` /
  `@else if` chains and `@switch` cases (they compile to nested
  conditionals). Deeper input is reported with the error ngc reports when
  its own stack overflows, `RangeError: Maximum call stack size exceeded`;
  for a binding at the span ngc's binding parser uses. ngc overflows below
  1000 levels, so everything it compiles still compiles.

Review round:

Review fixes for deep templates and expressions:

- The expression parser's nesting guard now sits on every recursive cycle:
  an operand, a conditional's branches, and the right side of `**`.
  Long `a ? b : …` and `a ** a ** …` chains no longer overflow any stack.
- The template parser goes on past the depth limit (its open elements and
  blocks are in a list). The template's own errors are reported, as ngc
  reports them. `RangeError` is reported only when there are no others.
  For too-deep ICUs, which are parsed recursively, the rest of the input is
  still skipped, and the errors of the cut parse are dropped.
- A `@switch` with too many cases still visits its cases. The `RangeError`
  is reported only if the template has no other errors (ngc overflows only
  when it prints output).
- The expression lexer scans nested template literals and substitutions
  with a list, not recursion.
- The NAPI binding no longer sends each compilation to another thread. That
  made compiles up to ~3x slower on a busy machine. Now a compilation runs
  on the calling thread with low depth limits (`with_depth_limits`:
  32/64 levels when optimized, 8/8 unoptimized). Only an input that nests
  deeper runs again, on a new thread with a large stack. Entry points that
  compile no template no longer hop at all, as on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@Brooooooklyn

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T06:36:28.184185Z e2ef0db Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: e2ef0db1ba

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Brooooooklyn
Brooooooklyn merged commit 15105df into main Dec 4, 2026
10 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/older-template-bugs branch December 4, 2026 05:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant