Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions lexer_contention_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package chroma_test

import (
"bytes"
"runtime"
"strings"
"sync/atomic"
"testing"

assert "github.com/alecthomas/assert/v2"
"github.com/alecthomas/chroma/v3/formatters/html"
"github.com/alecthomas/chroma/v3/lexers"
"github.com/alecthomas/chroma/v3/styles"
)

// Regression test for #1498: under CPU contention a rule match can spuriously
// exceed its 250ms timeout, which must not fail tokenising.
func TestTokeniseUnderCPUContention(t *testing.T) {
old := runtime.GOMAXPROCS(1)
defer runtime.GOMAXPROCS(old)
var stop atomic.Bool
for range 64 {
go func() {
for !stop.Load() {
}
}()
}
defer stop.Store(true)
tokens, err := lexers.Get("go").Tokenise(nil, strings.Repeat("s := \"a\" + \"b\"\n", 1000))
assert.NoError(t, err)
var out bytes.Buffer
assert.NoError(t, html.New().Format(&out, styles.Fallback, tokens))
assert.True(t, out.Len() > 0)
}
4 changes: 4 additions & 0 deletions regexp.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,10 @@ func matchRules(text []rune, pos int, rules []*CompiledRule) (int, *CompiledRule
return i, rule, []string{word, word}, map[string]string{"0": word, "1": word}, nil
}
match, err := rule.Regexp.FindRunesMatchStartingAt(text, pos)
if err != nil {
// A match can spuriously time out while its goroutine waits for CPU; retry once now that it is running.
match, err = rule.Regexp.FindRunesMatchStartingAt(text, pos)
}
if err != nil {
return 0, nil, nil, nil, fmt.Errorf("matching %q: %w", rule.Pattern, err)
}
Expand Down
Loading