Skip to content

Recover iterator panics in indexed TTY formatters and DelegatingLexer - #1502

Merged
alecthomas merged 1 commit into
alecthomas:masterfrom
SuzumiyaHaruhi719:fix/recover-tty-delegate-panics
Nov 21, 2026
Merged

alecthomas merged 1 commit into
alecthomas:masterfrom
SuzumiyaHaruhi719:fix/recover-tty-delegate-panics

Conversation

@SuzumiyaHaruhi719

Copy link
Copy Markdown
Contributor

Problem

Commit a69d1c0 changed RegexLexer to surface regex match errors (such as the 250ms MatchTimeout) by panicking from the token iterator so Formatter.Format can recover and return an error. Following #1500, two code paths still let iterator panics escape unrecovered:

  1. formatters.TTY (terminal), TTY8 (terminal8), TTY16 (terminal16), and TTY256 (terminal256) implement Formatter via *indexedTTYFormatter without panic recovery, crashing callers instead of returning an error.
  2. DelegatingLexer.Tokenise eagerly consumes d.language's token iterator inside Tokenise before returning (iter.Seq[Token], error) (prior to Formatter.Format), so a panic from the embedded language lexer crashes callers such as quick.Highlight and playground.Highlight instead of returning an error.

Root cause

  • indexedTTYFormatter.Format in formatters/tty_indexed.go bypassed chroma.FormatterFunc and lacked recover().
  • (*delegatingLexer).Tokenise in delegate.go ranges over languageTokens synchronously while building rootText, before any Formatter recovery frame is on the call stack.

Fix

  • Wrap indexedTTYFormatter in chroma.FormatterFunc, matching TTY16m and the other function-backed formatters so every registered formatter recovers iterator panics uniformly.
  • Add panic recovery in (*delegatingLexer).Tokenise so panics during the eager languageTokens pass are returned as error.

Tests

  • Added TestFormattersRecoverIteratorPanic in formatters/tty_indexed_test.go exercising every registered formatter in formatters.Names() with both string and error panics.
  • Added TestDelegateRecoversLanguageIteratorPanic in delegate_test.go verifying both error and string panics in the embedded language lexer are returned from Tokenise.

@alecthomas
alecthomas enabled auto-merge (squash) November 21, 2026 05:49
@alecthomas
alecthomas merged commit 894af9f into alecthomas:master Nov 21, 2026
4 checks passed
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.

2 participants