Skip to content

Follow-up to #272: walk the template tree with an explicit stack in the Rust parser and compiler, for the planned JS binding #300

Open

Description

@JuroOravec

What happens

Since the fix for #272 (PR #470), a template can nest at most 512 tags, and at most 256 levels of Citry logic among them. A deeper template raises SyntaxError with the code citry.parse.too-deep. The parser checks this while it builds the tree, so every later pass knows the deepest tree it can get.

Many Rust passes still call themselves once per level of the tree. To keep them from overflowing the stack, each of those calls starts with a stack guard (#343, #400, #428). The guard calls the stacker crate's maybe_grow: when less stack is left than a margin (usually 100 KiB), it runs the rest of the pass on a new block allocated on the heap (usually 1 MiB). A few guards use larger sizes, such as the formatter's guard around Ruff (4 MiB and 8 MiB) and the Vue compiler's large stack (16 MiB). Tests run the parser, compiler, formatter and Vue passes at the limits on threads with stacks of 128 KiB to 384 KiB.

This works on every target citry_core ships today, including the wasm32-unknown-emscripten wheel for Pyodide. The question here is the planned JS binding. docs/codebase.md says it will use wasm-bindgen (target wasm32-unknown-unknown), and nothing in the repository builds that target yet.

What the guard can and cannot do on WebAssembly

A WebAssembly program has two stacks:

  • The program's own stack lives in WebAssembly memory. On wasm32-unknown-unknown the linker gives it 1 MiB by default; on Emscripten, emcc sets its size. Local variables that are too big for a register, or whose address is taken, live there.
  • The engine's call stack holds every function call's return address and locals. The engine (V8 in Node.js and Chrome) manages it, and the program cannot move or grow it.

stacker 0.1.25 and psm 0.1.32, the crate it uses to switch stacks, can switch only the first one:

  • psm switches the stack on any wasm32 target by pointing the __stack_pointer global at the new block (psm-0.1.32/build.rs:53, src/arch/wasm32.s:29-49).
  • stacker can't measure how much stack is left on wasm32 (stacker-0.1.25/src/backends/mod.rs:8-28 falls back to fallback.rs, which returns None). So maybe_grow always moves the work to a new block (lib.rs:52-55). Inside that block, stacker knows the block's size (lib.rs:159), so the guards in deeper calls measure against it and allocate again only when it runs low.

So on wasm-bindgen the guards keep the program's stack from overflowing. They do nothing for the engine's call stack, and each level of a recursive pass still uses part of it. crates/python_safe_eval/src/stack.rs:17-26 notes the same limit for Pyodide. Nobody has measured this on wasm-bindgen. On Pyodide, only parsing and compiling at the limits are checked, when citry_core is qualified for a release (see the end of this issue).

Who hits it

Nobody yet: the JS binding does not exist. This matters once that work starts, for templates near the nesting limits.

What still calls itself once per level

All of these are guarded at each level, and none keeps its own stack yet.

  • Parser passes (crates/citry_template_parser/src/parser.rs): recompute_template_used_variables (:3629) with recompute_node_used_variables (:3648), validate_template_bindings (:3772), collect_template_binding_tokens (:3739), extract_fill_nodes (:5056), find_ignored_content_problem (:3053), _contains_only_fills_and_control_flow (:3501), validate_fill_group_content (:3556), and process_template_string (:818), which parses a template inside an attribute.
  • The grammar: python_expr and python_nested_curly (grammar.pest:445, :474) call themselves once per {. parse_grammar gives them a stack block sized to the number of braces (parser.rs:238-245), and more than 100,000 braces is a SyntaxError.
  • The compiler: compile_template_body_with_mode (compiler.rs:236) calls itself for each nested body.
  • The tree type: Template's own Clone, PartialEq, Debug and Drop (ast.rs:1030-1104). Other AST types use derived implementations, but each level passes through Template.
  • The formatter (crates/citry_template_formatter): visit_node (source.rs:406), project_node (projection.rs:444), analyze_node (layout.rs:114), and the projection types' PartialEq, Debug and Drop.
  • The Vue compiler (crates/citry_vue_compiler): the reader, the writers, eval and the other passes in server_render.rs, and the readers in hydration.rs and lib.rs. Compiling and reading a Vue template run inside a 16 MiB block (with_large_stack, stack.rs:82). A server render runs in 1 MiB blocks, plus a 16 MiB one for data deeper than 128 levels. Separate caps also stop very deep output: MAX_READ_DEPTH, MAX_DEPTH and MAX_MANIFEST_DEPTH (all 2,048) and MAX_ELEMENT_DEPTH (400), in server_render.rs.

Some passes already keep their own list of pending nodes. One is the compiler's limit check for a tree built by hand (first_too_deep_tag, nesting.rs). The others are the Python code printer (lang/python.rs, #318) and the drop of LangSpecArgument (lang/lang.rs:209, #343).

A few walkers recurse over things other than tag depth: c-for tuple targets (lang/python.rs:626), JavaScript initializers (browser.rs:1453), comment pairs (parser_context.rs:711), and nested mergeProps (server_render.rs:2064, :3372). Each looks shallow, but nothing proves a bound for them.

Fix direction

  1. When the JS binding starts, add a wasm-bindgen test that parses, compiles, formats and server-renders templates at both limits, in Node.js and in a browser. It should also cover an attribute template and an expression full of braces. If every case passes with room to spare, record the measured margin here and close this issue.
  2. If a case fails, rewrite the passes it reaches to keep their own stack of pending nodes, starting with the deepest one the test reports. These files are high-risk areas in CLAUDE.md, and the compiler's output is a contract, so the generated code must stay the same byte for byte. The locked compiler tests check that.
  3. Check whether the Pest expression rules can loop instead of calling themselves once per {.

Until then, the only WebAssembly check is the Pyodide wheel's smoke run (scripts/smoke_citry_core.py). It parses and compiles templates at both limits, and checks that one level more is rejected. It uses Emscripten, not wasm-bindgen, and runs only when citry_core is qualified for a release (.github/workflows/py--citry-core--publish.yml), so it has not yet run with these limits.

Activity

  1. JuroOravec commented on Oct 24, 2026

    @JuroOravec
    MemberAuthor

    One more recursion to make iterative, found while fixing deep expressions for #272 (the fourth PR for that issue).

    The template grammar calls python_expr again for every { it opens inside a {{ ... }} expression (python_expr and python_nested_curly in crates/citry_template_parser/src/grammar.pest). So a template like this one recurses once per {:

    {{ {"}"{"}"{"}" ... }}} }}
    

    The grammar skips the } inside each string, so it keeps opening levels. A count of { minus } stays near zero for this input. The same happens with a } inside a # comment. A quick count can't match the grammar exactly, because where a string or comment starts depends on the grammar's own parsing context.

    What #272 ships: the parser counts every { in the source, which is always at least the grammar's depth. It sizes the grammar's stack from that count, using stacker, and rejects a template with more than 100,000 {.

    What this issue should add: make python_expr loop instead of recurse, keeping the open braces on Pest's own stack. Push on {, close a } only while that stack is non-empty, then drop the entry. Then the grammar needs no extra stack for braces, and the brace limit and the stack sizing in parse_grammar (crates/citry_template_parser/src/parser.rs) can be removed. This also matters for Pyodide. On wasm32 the grammar's recursion runs on the WebAssembly engine's own call stack, which stacker cannot grow, so a template with a few thousand nested { may still fail fatally there (unproven, since it hasn't been run in Pyodide). A grammar that loops removes that.

    This is a grammar change, so it needs a written plan and a review of the grammar files first. Every existing parser test should pass unchanged.

    🤖 Generated with Claude Code

  2. JuroOravec commented on Oct 28, 2026

    @JuroOravec
    MemberAuthor

    #520 covers the parser's side of fix direction 2:

    • the parser's passes over the finished tree keep their own work list;
    • Template's Clone, PartialEq and Drop do the same, while Debug stays on the stack guard;
    • the doc comments record why the grammar keeps its stack reservation and why parsing an attribute template keeps its guard.

    The compiler moves to v1.1, and fix directions 1 and 3 stay open. This is the approach I would take for the compiler.

    What calls itself today

    compile_template_body_with_mode (compiler.rs) compiles one body. For each node in it, it calls the matching node function: compile_simple_node, compile_component_node, compile_control_flow_node, or compile_element_node. compile_element_node hands off to the component or HTML function, and compile_html_node hands off to compile_prepared_html_node in prepared mode.

    Six places call compile_template_body_with_mode again for a node's body:

    • compile_html_node, at two sites;
    • compile_prepared_html_node;
    • compile_simple_node;
    • compile_component_node;
    • compile_control_flow_node, once per branch, in a loop.

    Two things make a rewrite manageable:

    • Turning the compiled tree into Python source already works without recursion (lang/python.rs), and so does the depth check (first_too_deep_tag).
    • A body's output depends only on the body and the compile mode, and the mode is the same through the whole tree. Nothing else is passed down from a parent.

    Option A: a work list with a saved state per call site (chosen)

    • Split each node function at the point where it needs its body compiled. The first half returns either finished items, or a saved state together with the body to compile. The second half takes that state and the body's compiled items and finishes the node.
    • A driver loop keeps a stack of frames. A body frame holds the body's remaining elements and the items compiled so far. A node frame is an enum with one variant for each of the six call sites, holding the locals that site computed before it needed the body.
    • compile_control_flow_node gets its own variant, which keeps the branches compiled so far and the branches still to compile.
    • The driver runs the same steps in the same order as the recursive code, so the output stays the same. That includes which error is reported first when a template has several. Only where the in-progress state is kept changes: it moves from the native stack into the frames.
    • Estimated cost: 2 to 3 days. The risk is the size of the edit in a high-risk file. A saved state that misses a local the second half reads would change the output.

    Option B: compile every body first, children before parents (rejected)

    • This would be an iterative pre-pass that compiles the deepest bodies first and stores each result, so that the existing node functions read the stored result in place of calling down.

    • It has to wrap control-flow attributes (c-if="..." on a tag) first, because wrapping builds new nodes and changes the tree's shape.

    • The blocker is matching a stored result to its body. Bodies are passed around by value, and an AST node has no field to carry an id; adding one changes a #[pyclass] shape. That leaves two ways to find the result, both weak:

      • A counter in visiting order silently goes out of step if any path skips a body or compiles one twice.
      • A key taken from the elements' heap address depends on a detail that is easy to break.

      A private copy of the tree for the compiler would avoid both, but that is close to a rewrite.

    • Error order needs extra care too. Each result would have to be stored and returned only when its parent asks for it. Otherwise an error deep in a body would be reported before an earlier error in the parent's own attributes.

    How to show the output is byte for byte the same

    • The locked compiler tests, which assert exact generated strings (tests/tag_compiler*.rs and the others), must pass unchanged.
    • A throwaway harness compiles every template in the crate's tests and in the Python test suites twice, once with main and once with the branch, in both compile modes. It then diffs the generated source and the error messages.
    • The 512- and 256-level deep-nesting tests must keep passing on small threads.

    Measure on wasm-bindgen first

    On native targets, the guard already keeps the compiler from overflowing the stack. On Pyodide it guards only the program's own stack, as the issue explains, and the run at the limits there has not happened yet, so that case is unproven. Fix direction 1 still applies: once the JS binding exists, measure compiling at both nesting limits under wasm-bindgen, in Node.js and in a browser. If the engine's call stack has room to spare at 512 and 256 levels, record the margin here; part 2 may then not be needed at all. If it runs out, option A is the way to go.

  3. added
    next-sprint
    on Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    next-sprint

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions