Skip to content

fix(syntax): parse case patterns that run past the 1 KiB read buffer - #880

Merged
ewhauser merged 8 commits into
mainfrom
claude/interesting-faraday-65e34a
Oct 20, 2026
Merged

ewhauser merged 8 commits into
mainfrom
claude/interesting-faraday-65e34a

Conversation

@ewhauser

@ewhauser ewhauser commented Oct 20, 2026 •

Copy link
Copy Markdown
Owner

What

A case pattern whose shell part runs past the parser's 1 KiB read buffer no longer fails to parse. Bash accepts these, and gbash rejected them:

case x in $(echo aaaa; …~1100 bytes… case x in x) ;; esac) ) ;; esac
# before: 1:12: syntax error near unexpected token `('
# after:  parses

Why

scanRawPatternSource and casePatternUsesOptionalOpener only scanned the current 1 KiB buffer window. When the scan reached the window end before the input ended, it fell back to getPattern. A $(...) cut off by the window failed to parse there, so the scan ended early. The fallback path also defeats the parse cache, so nested case x in @($(case ...))) past 1 KiB was slow (about 9 s at 25 KB).

How (shell/syntax)

  • Read-ahead. patternSourceAhead gives both scans the whole pattern. A real reader is read ahead in doubling steps until the scan ends inside the text and no shell part or bracket expression ran into its end; scanPatternText now reports that through sawEnd. The extra bytes go back to the input through a prependReader, so the lexer is unaffected. Interactive input is never read ahead.
  • Sub-parsers. Sub-parsers already hold their input as a string, so they scan a view of all of it at once, without copying. Doubling steps there rescanned every nesting level per step.
  • Scans of cut-off text. While more input may follow, a scan that reaches the cut gives up, and nothing it produced there goes into the parse cache. Without this, each nesting level fell back to the uncached getPattern path, which was exponential.
  • fill keeps the current token buffered while a case pattern's first token is lexed. A pattern whose first token straddles the buffer end is then still scanned from its start. Before, this failed at certain alignments, such as padding 1012/1013 with nested @($(case …, and with short reads.

Verification

  • DebugPrint and error output are byte-identical to the base on 1,731 inputs (filetests, errorCases, print/simplify tests, fuzz corpora, benchmark files, repo scripts) × 5 dialects × 3 option sets.
  • Short reads. Half-size reads give the same output as whole reads. With one-byte reads, 262 outputs changed versus the base. All of them moved closer to the whole-input result and none got worse.
  • New tests in pattern_lookahead_test.go cover 15 pattern shapes across many paddings and three read sizes, plus 1,000-level nesting, source kept intact after a read-ahead, and read errors. A fuzz seed covers a hang found while developing this.
  • Depth. Nested case x in $(…), @($(…)) and ($(…)) parse correctly at 2,000–4,000 levels. @($(case …))) at 25 KB takes 0.9 s, down from about 9 s. Time still grows with the square of depth (4,000 levels ≈ 13–16 s); that is a known separate issue.
  • BenchmarkParse and BenchmarkParseBenchmarkFiles are unchanged.
  • go test ./shell/... and make lint pass. FuzzParsePrint and FuzzParseAdversarial each ran 60 s clean.

Known issue (not from this PR)

FuzzParseAttackMutations fails within a minute on a slow input family that is just as slow on the base: an unterminated backquote followed by $( (( and heredocs, with no case pattern. A 175-byte script takes 6.5 s and a 304-byte one 25 s. A separate fix is in progress.

No SPEC change: this is a parser bug fix with no change to the sandbox or API contract.

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.
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.
@ewhauser
ewhauser enabled auto-merge (squash) October 20, 2026 03:50
…raday-65e34a

# Conflicts:
#	shell/syntax/parser.go
#	shell/syntax/pattern_nesting_test.go
#	shell/syntax/raw_part_cache.go
Resolves conflicts with the squash-merged #877 by keeping this PR's own change on top of main.
# Conflicts:
#	shell/syntax/pattern_nesting_test.go
#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
ewhauser merged commit bfd6646 into main Oct 20, 2026
17 checks passed
@ewhauser
ewhauser deleted the claude/interesting-faraday-65e34a branch October 20, 2026 05:06
@ewhauser ewhauser mentioned this pull request Oct 20, 2026
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