@@ -46,6 +46,14 @@ class ScriptParser
4646private:
4747 std::vector<Token> tokens_;
4848 size_t current_ = 0 ;
49+ int depth_ = 0 ;
50+
51+ // Upper bound on the nesting of the recursive-descent grammar. Each open
52+ // paren / unary prefix / right-hand operand adds one parseExpr frame, so a
53+ // crafted expression like "((((...0...))))" would otherwise recurse until the
54+ // native stack is exhausted. This mirrors the kMaxNestingDepth cap the XML
55+ // parser already applies in VerifyXML and recursivelyCreateSubtree.
56+ static constexpr int kMaxNestingDepth = 256 ;
4957
5058 // Binding power constants. Higher value = tighter binding.
5159 static constexpr int kAssignmentBP = 2 ;
@@ -254,6 +262,18 @@ class ScriptParser
254262 // / Main Pratt expression parser
255263 Ast::expr_ptr parseExpr (int minBP)
256264 {
265+ // Bound the recursion so a deeply nested expression can't overflow the
266+ // stack. Every open paren / unary prefix / right-hand operand adds one
267+ // parseExpr frame; depth_ is decremented before the normal return below so
268+ // it tracks the current nesting rather than the total call count. A parse
269+ // failure throws and discards the parser, so the error paths need no reset.
270+ if (++depth_ > kMaxNestingDepth )
271+ {
272+ throw RuntimeError (StrCat (" Parse error at position " , std::to_string (peek ().pos ),
273+ " : expression nesting is too deep (limit " ,
274+ std::to_string (kMaxNestingDepth ), " )" ));
275+ }
276+
257277 auto left = parsePrefix ();
258278
259279 while (true )
@@ -293,6 +313,7 @@ class ScriptParser
293313 left = makeBinary (std::move (left), opTok.type , std::move (right));
294314 }
295315
316+ --depth_;
296317 return left;
297318 }
298319
0 commit comments