Skip to content

fix(syntax): cap pattern nesting through shell parts - #879

Merged
ewhauser merged 8 commits into
mainfrom
claude/strange-rosalind-5b5e45
Oct 20, 2026
Merged

ewhauser merged 8 commits into
mainfrom
claude/strange-rosalind-5b5e45

Conversation

@ewhauser

Copy link
Copy Markdown
Owner

Stacked on #877. This branch builds on claude/fix-pattern-parse-exponential. Until #877 merges, this diff also shows its two commits. Only the last commit (fix(syntax): cap pattern nesting through shell parts) is new here. Review or merge #877 first.

What

Patterns nested through shell parts, such as case x in $(case x in $(...) ) ;; esac) ) ;; esac or [[ 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. With MaxNestingDepth at 16000, nested case took 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:

  • Every re-parse goes through rawWordPart, so each sub-parser it starts adds one level. That covers $(...), "...", ${...}, backquotes and <(...) in any pattern context.
  • Deeper input fails with a ParseError: shell code nested in patterns exceeds the maximum depth of 64.
  • Here-document bodies continue the count of the code that holds them.
  • The raw-part cache (from fix(syntax): stop nested patterns from parsing in exponential time #877) records each entry's pattern depth. It reuses an entry only at depths where a fresh parse gives the same result.

64 is above the runtime's default MaxSubstitutionDepth (50), so the cap does not reject scripts that default policy would otherwise run.

Results

  • Every nested shape at 16000 levels now fails within 250 ms (case: ~1 ms, [[: ~140 ms).
  • At the cap the cost is bounded but not linear. 64 levels around 1 MB of inner text parse in 0.35–1.15 s, depending on shape. A fully linear design would remove that; this PR doesn't attempt it.

Verification

  • DebugPrint and error output are identical to the base on fileTests*, errorCases, and every .sh/.bash/.bats/.zsh/.ksh file 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.
  • New tests in shell/syntax/pattern_nesting_test.go:
    • nested shapes at the cap and at MaxNestingDepth, with time bounds
    • the exact limit for [[ and extglob shapes
    • heredoc carry-over
    • a cache unit test for reuse across pattern depths
  • I checked by breaking the code on purpose that the heredoc and cache tests fail when their logic is removed.
  • go test ./shell/... and make lint pass. FuzzParseAdversarial and FuzzParsePrint pass 60 s runs.
  • FuzzParseAttackMutations did not pass. Both 60 s runs stopped on a slow input. The two inputs it caught are unterminated backquotes combined with heredocs and $(, 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.

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
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
The merge of main in 4beaa57 resolved pattern_nesting_test.go to the
version before 7cbc986, which parsed every shape at MaxNestingDepth in
parallel and timed out under -race on CI.
@ewhauser
ewhauser merged commit f0fdaba into main Oct 20, 2026
17 checks passed
@ewhauser
ewhauser deleted the claude/strange-rosalind-5b5e45 branch October 20, 2026 04:31
@ewhauser ewhauser mentioned this pull request Oct 20, 2026
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.
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