Skip to content

fix(syntax): stop nested patterns from parsing in exponential time - #877

Merged
ewhauser merged 3 commits into
mainfrom
claude/fix-pattern-parse-exponential
Oct 20, 2026
Merged

ewhauser merged 3 commits into
mainfrom
claude/fix-pattern-parse-exponential

Conversation

@ewhauser

Copy link
Copy Markdown
Owner

What

Nested patterns no longer take exponential time to parse. Before this change, a few dozen bytes of shell could tie up a parser goroutine indefinitely:

Input Before After
[[ x == @(@(…x…)) ]], 22 levels ~2 s (each level doubles it) 16,000 levels in ~20 ms
case x in $(case x in $(…) ) ;; esac) ) ;; esac, 8 levels ~0.9 s (~5× per level) 1,000 levels in ~0.2 s

The second commit also fixes a Simplify nil-pointer panic on ((${%})), which FuzzParsePrint found while I was verifying this change.

How (shell/syntax)

  • Group scans don't rebuild arms. parseExtGlob and parsePatternGroup scanned each nested group with a recursive call that built the group's AST and threw it away; then they built the same arm again. Callers that only need a group's end now use scan-only walkers (skipExtGlob, skipPatternGroup). Their result is cached in patternSkips, keyed by the address of the group's first byte in the pattern string. A cached end is reused only while the new text still holds everything the original scan looked at. Bare groups skip nested groups the same way instead of counting parentheses (the end is the same).
  • Shell parts are cached across sub-parsers. Each case pattern's shell parts were re-parsed by fresh sub-parsers in scanPatternText, findInvalidCasePatternOperator, findPatternListSplit, hasTopLevelWhitespace and parse. The new rawPartCache caches those results for the whole parse and shares them with every sub-parser. Callers pass different amounts of trailing text, and some AST fields depend on what follows the part (CmdSubst.DiagnosticEnd, ParamExp.Invalid). So a cached result is reused only when the new input holds exactly the bytes the sub-parser read (tracked by rawPartReader, checked with a seeded maphash).
  • Pattern groups count toward MaxNestingDepth. Extended-glob and bare groups are parsed recursively, so deep @( input could overflow the stack. Pattern scans also stop as soon as the limit is hit.

SPEC.md §9.1 is updated to match.

Verification

  • Same ASTs as before. DebugPrint and error output are identical to main on every shared input: the filetests, the error cases, every .sh/.bash/.bats file in the repo, the fuzz corpora and benchmark files, across 5 dialects × 3 option sets. Also on 150k random pattern-heavy inputs.
  • Regression tests with time bounds are in pattern_nesting_test.go. On main, 9 of the 12 shapes don't finish within 10 s.
  • Fuzzers: FuzzParsePrint, FuzzParseAdversarial and FuzzParseAttackMutations each run clean for 60 s.
  • Speed: BenchmarkParse* is unchanged.

Known limits

These are follow-ups, each being worked in its own session:

  • Shell parts that nest patterns are quadratic in depth, not linear. Every level still copies and re-lexes the text of the levels inside it. Nested case takes 0.2 s at 1,000 levels and about 12 s at 4,000. Nested [[ x == $(…) ]] takes 3.4 s at 8,000 levels; it was already quadratic on main. With MaxNestingDepth at 16000 this needs either a redesign or a lower cap for pattern shell parts.
  • Case patterns past 1 KiB can fail to parse. If a shell part in a case pattern crosses the parser's 1 KiB read buffer, parsing fails, which is also true on main: case x in $(<~1100 bytes>) ) ;; esac gives syntax error near unexpected token `('. That code path is also why case x in @($(case …))) is still slow past 1 KiB.

Simplify dereferenced ParamExp.Param, which is nil for an invalid
expansion such as ${%}, so "((${%}))" crashed it. Found by
FuzzParsePrint.
Pattern parsing scans a pattern several times and re-parsed every nested
group and shell part on each scan, so nesting took exponential time:
22 levels of "[[ x == @(@(...)) ]]" took about 2s and 8 levels of
"case x in $(case x in $(...) ) ;; esac) ) ;; esac" about 1s.

- Scans that only need where a group ends no longer build the group's
  arms, and memoize the end by the address of the group's first byte,
  reusing it only while the text still holds everything the scan looked
  at. Bare groups skip nested groups the same way instead of counting
  parentheses.
- parseRawWordPart memoizes its results for the whole parse, shared by
  every sub-parser it starts. Callers pass different tails of the same
  source and the sub-parser's output can depend on what follows the part,
  so an entry is only reused when the new input holds exactly the bytes
  the sub-parser read for it.
- Extended glob and bare pattern groups count toward MaxNestingDepth,
  since they are parsed recursively and could overflow the stack, and
  pattern scans stop once the limit is hit.

DebugPrint output is unchanged on the filetests, error cases, repo
scripts and fuzz corpora, and on 150k random pattern-heavy inputs.

Nested groups now parse in linear time: 16000 levels of @( take about
20ms. Shell parts that nest patterns are parsed once each but every
level still copies and re-lexes the text inside it, so they are
quadratic: 1000 levels of nested case take about 0.2s, 4000 about 12s.
TestFunctionDepthDefaultAllowsDeepRecursion takes under a second
locally but about ten seconds in CI, where the race detector runs it
alongside the rest of the package, so its 10s bound failed twice on
PR #877. 25s still catches the O(depth^2) writes it guards against,
which took over ten seconds even without the race detector.
@ewhauser
ewhauser merged commit 43326a9 into main Oct 20, 2026
17 checks passed
@ewhauser
ewhauser deleted the claude/fix-pattern-parse-exponential branch October 20, 2026 04:06
@ewhauser ewhauser mentioned this pull request Oct 20, 2026
ewhauser added a commit that referenced this pull request Oct 20, 2026
Resolves conflicts with the squash-merged #877 by keeping this PR's own change on top of main.
ewhauser added a commit that referenced this pull request Oct 20, 2026
Resolves conflicts with the squash-merged #877 by keeping this PR's own change on top of main.
ewhauser added a commit that referenced this pull request Oct 20, 2026
* test(runtime): allow for -race in the deep recursion timing check

TestFunctionDepthDefaultAllowsDeepRecursion takes under a second
locally but about ten seconds in CI, where the race detector runs it
alongside the rest of the package, so its 10s bound failed twice on
PR #877. 25s still catches the O(depth^2) writes it guards against,
which took over ten seconds even without the race detector.

* fix(interp): make deep function recursion linear in its depth

Every function call adds an environ layer, and variable lookups, writes
that pass through function scopes, and the OPTIND/SECONDS/temp-binding
searches all walked the chain one layer at a time. Each command in a
recursive function reads globals such as IFS and PWD many times, so
recursing to depth d cost O(d^2): depth 1000 took 0.9s, or about 10s
under -race in CI.

Each layer now caches, per name, which layer further down binds it. The
cache stays valid until some layer sharing the epoch gains or loses a
binding of that name, which value updates do not do. Pass-through writes
jump straight to the nearer of that owner and the first layer that does
not pass writes on, and temp-binding lookups skip plain function scopes.

Depth 2000 now takes about 0.16s instead of 3.5s, and quadrupling the
depth costs about 4-5x instead of 14x.
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