Repository navigation
fix(syntax): stop nested patterns from parsing in exponential time - #877
Merged
Merged
Conversation
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.
ewhauser
enabled auto-merge (squash)
October 20, 2026 02:47
This was referenced Oct 20, 2026
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.
Merged
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
[[ x == @(@(…x…)) ]], 22 levelscase x in $(case x in $(…) ) ;; esac) ) ;; esac, 8 levelsThe second commit also fixes a
Simplifynil-pointer panic on((${%})), which FuzzParsePrint found while I was verifying this change.How (shell/syntax)
parseExtGlobandparsePatternGroupscanned 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 inpatternSkips, 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).scanPatternText,findInvalidCasePatternOperator,findPatternListSplit,hasTopLevelWhitespaceandparse. The newrawPartCachecaches 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 byrawPartReader, checked with a seededmaphash).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
.sh/.bash/.batsfile in the repo, the fuzz corpora and benchmark files, across 5 dialects × 3 option sets. Also on 150k random pattern-heavy inputs.pattern_nesting_test.go. On main, 9 of the 12 shapes don't finish within 10 s.BenchmarkParse*is unchanged.Known limits
These are follow-ups, each being worked in its own session:
casetakes 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. WithMaxNestingDepthat 16000 this needs either a redesign or a lower cap for pattern shell parts.case x in $(<~1100 bytes>) ) ;; esacgivessyntax error near unexpected token `('. That code path is also whycase x in @($(case …)))is still slow past 1 KiB.