Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make regex matcher timeout configurable #638

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
24 changes: 19 additions & 5 deletions regexp.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package chroma

import (
"fmt"
"math"
"os"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -100,6 +101,7 @@ func NewLexer(config *Config, rulesFunc func() Rules) (*RegexLexer, error) {
}
r := &RegexLexer{
config: config,
regexTimeout: time.Millisecond * 250,
fetchRulesFunc: func() (Rules, error) { return rulesFunc(), nil },
}
// One-off code to generate XML lexers in the Chroma source tree.
Expand Down Expand Up @@ -261,10 +263,11 @@ func (l *LexerState) Iterator() Token { // nolint: gocognit

// RegexLexer is the default lexer implementation used in Chroma.
type RegexLexer struct {
registry *LexerRegistry // The LexerRegistry this Lexer is associated with, if any.
config *Config
analyser func(text string) float32
trace bool
registry *LexerRegistry // The LexerRegistry this Lexer is associated with, if any.
config *Config
regexTimeout time.Duration
analyser func(text string) float32
trace bool

mu sync.Mutex
compiled bool
Expand All @@ -286,6 +289,12 @@ func (r *RegexLexer) Rules() (Rules, error) {
return r.rawRules, nil
}

// SetTimeout sets the timeout after which the lexer gives up. The default
// timeout is 250 ms. To disable the timeout, set it to zero.
func (r *RegexLexer) SetTimeout(timeout time.Duration) {
r.regexTimeout = timeout
}

// SetRegistry the lexer will use to lookup other lexers if necessary.
func (r *RegexLexer) SetRegistry(registry *LexerRegistry) Lexer {
r.registry = registry
Expand Down Expand Up @@ -334,7 +343,12 @@ func (r *RegexLexer) maybeCompile() (err error) {
if err != nil {
return fmt.Errorf("failed to compile rule %s.%d: %s", state, i, err)
}
rule.Regexp.MatchTimeout = time.Millisecond * 250

timeout := r.regexTimeout
if timeout == 0 {
timeout = time.Duration(math.MaxInt64)
}
rule.Regexp.MatchTimeout = timeout
}
}
}
Expand Down