Repository navigation
fix(syntax): cap pattern nesting through shell parts - #879
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.
Each shell part in a case, [[ ]] or extglob pattern is re-parsed by a sub-parser that reads the text of every level inside it again, so patterns nested through shell parts, such as `case x in $(case x in $(...) ) ;; esac) ) ;; esac`, parsed in time quadratic in their depth: 12.6 s at 4000 levels and minutes near MaxNestingDepth. Cap that depth at the new MaxPatternNestingDepth (64). Each sub-parser that rawWordPart starts adds a level, heredoc bodies continue their holder's count, and the raw-part cache reuses an entry only at pattern depths where a fresh parse gives the same result. Deeper input fails with "shell code nested in patterns exceeds the maximum depth of 64". Every nested shape at 16000 levels now fails within 250 ms. At the cap, parsing costs up to about 1 s per MiB of nested text. DebugPrint and error output are unchanged on the filetests corpus, error cases and every shell script in the repo (5 dialects x 3 option sets). SPEC.md section 9.1 documents the new limit.
ewhauser
enabled auto-merge (squash)
October 20, 2026 03:50
Parsing every nested shape at MaxNestingDepth in parallel took 6-26 s per parse with the race detector on CI and starved other packages' tests. Check all shapes at 4x the cap, and only the case and [[ shapes at MaxNestingDepth, sequentially, with a 30 s bound.
Resolves conflicts with the squash-merged #877 by keeping this PR's own change on top of main.
…nd-5b5e45 # Conflicts: # SPEC.md # shell/syntax/nesting.go # shell/syntax/parser.go # shell/syntax/pattern_nesting_test.go # shell/syntax/raw_part_cache.go
…into claude/strange-rosalind-5b5e45
Merged
ewhauser
added a commit
that referenced
this pull request
Oct 20, 2026
#879 capped shell code nested in patterns at 64 levels, so 1000 levels now fail to parse. 64 levels still run well past the 1KiB read buffer.
ewhauser
added a commit
that referenced
this pull request
Oct 20, 2026
…880) * fix(syntax): don't panic simplifying an invalid ${%} in arithmetic Simplify dereferenced ParamExp.Param, which is nil for an invalid expansion such as ${%}, so "((${%}))" crashed it. Found by FuzzParsePrint. * fix(syntax): stop nested patterns from parsing in exponential time 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. * fix(syntax): parse case patterns that run past the 1 KiB read buffer A case pattern was only scanned within the parser's 1 KiB read buffer. When a shell part such as $(...) ran past it, the scan fell back to getPattern, which failed on the cut-off part, so scripts bash accepts, like `case x in $(<1 KiB of commands>) ) ;; esac`, gave "syntax error near unexpected token `('". - patternSourceAhead gives the case pattern scans (scanRawPatternSource and casePatternUsesOptionalOpener) the whole pattern. Real readers are read ahead in doubling steps until the scan ends inside the text and no shell part or bracket expression ran into its end; the bytes go back to the input through a prependReader. Interactive readers are not read ahead. - Sub-parsers read a string, so they scan a view of the rest of it at once; doubling steps there rescanned every nesting level per step. - Until the input ends, scans of text that may be cut off give up at the cut, and their parse-cache entries are not kept, so cut text is not re-parsed through the uncached fallback at every level. - fill keeps the current token buffered while a case pattern's first token is lexed, so a pattern whose first token straddles the buffer end is still scanned from its start. DebugPrint and error output are unchanged on the filetests, error cases, fuzz corpora, benchmark files and repo scripts (5 dialects x 3 option sets). Nested `case x in @($(case ...))) ;; esac` at 25 KB now parses in about 0.9 s instead of about 9 s. * test(syntax): nest past the read buffer within MaxPatternNestingDepth #879 capped shell code nested in patterns at 64 levels, so 1000 levels now fail to parse. 64 levels still run well past the 1KiB read buffer.
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
Patterns nested through shell parts, such as
case x in $(case x in $(...) ) ;; esac) ) ;; esacor[[ x == $([[ x == $(...) ]]) ]], parsed in time quadratic in their depth. Each shell part in a case,[[ ]]or extglob pattern is re-parsed by a sub-parser that reads the text of every level inside it again. WithMaxNestingDepthat 16000, nestedcasetook 12.6 s at 4000 levels and would take minutes near the limit.[[took 3.4 s at 8000 levels.This PR adds a separate, lower cap,
syntax.MaxPatternNestingDepth = 64:rawWordPart, so each sub-parser it starts adds one level. That covers$(...),"...",${...}, backquotes and<(...)in any pattern context.ParseError:shell code nested in patterns exceeds the maximum depth of 64.64 is above the runtime's default
MaxSubstitutionDepth(50), so the cap does not reject scripts that default policy would otherwise run.Results
case: ~1 ms,[[: ~140 ms).Verification
fileTests*,errorCases, and every.sh/.bash/.bats/.zsh/.kshfile in the repo, across 5 dialects × {default, KeepComments, RecoverErrors(3)}. The only differences are synthetic inputs deeper than 64 pattern levels, which already failed on the base with another error.shell/syntax/pattern_nesting_test.go:MaxNestingDepth, with time bounds[[and extglob shapesgo test ./shell/...andmake lintpass. FuzzParseAdversarial and FuzzParsePrint pass 60 s runs.$(, parsed with error recovery on. They are just as slow on the base commits, so this change didn't cause them. A separate session is fixing that.SPEC
SPEC.md §9.1 now documents
MaxPatternNestingDepth, its error, and the remaining cost at the cap.