Skip to content
New issue

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

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

Already on GitHub? # to your account

go: Performance: Don't compile regex on matcher create #107

Merged
merged 10 commits into from
Aug 10, 2023
Merged
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This document is formatted according to the principles of [Keep A CHANGELOG](htt
## [Unreleased]
### Changed
- [Go] Upgraded messages to v22
- [Go] Improve performance - don't compile regex on matcher create

### Added
- (i18n) Add Malayalam localization
Expand Down
14 changes: 9 additions & 5 deletions go/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ const (
DocstringAlternativeSeparator = "```"
)

var (
defaultLanguagePattern = regexp.MustCompile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$")
commentDelimiterPattern = regexp.MustCompile(`\s+` + CommentPrefix)
)

type matcher struct {
gdp DialectProvider
defaultLang string
Expand All @@ -35,7 +40,7 @@ func NewMatcher(gdp DialectProvider) Matcher {
defaultLang: DefaultDialect,
lang: DefaultDialect,
dialect: gdp.GetDialect(DefaultDialect),
languagePattern: regexp.MustCompile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$"),
languagePattern: defaultLanguagePattern,
}
}

Expand All @@ -45,7 +50,7 @@ func NewLanguageMatcher(gdp DialectProvider, language string) Matcher {
defaultLang: language,
lang: language,
dialect: gdp.GetDialect(language),
languagePattern: regexp.MustCompile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$"),
languagePattern: defaultLanguagePattern,
}
}

Expand Down Expand Up @@ -95,8 +100,7 @@ func (m *matcher) MatchTagLine(line *Line) (ok bool, token *Token, err error) {
if !line.StartsWith(TagPrefix) {
return
}
commentDelimiter := regexp.MustCompile(`\s+` + CommentPrefix)
uncommentedLine := commentDelimiter.Split(line.TrimmedLineText, 2)[0]
uncommentedLine := commentDelimiterPattern.Split(line.TrimmedLineText, 2)[0]
var tags []*LineSpan
var column = line.Indent() + 1

Expand All @@ -108,7 +112,7 @@ func (m *matcher) MatchTagLine(line *Line) (ok bool, token *Token, err error) {
if len(txt) == 0 {
continue
}
if !regexp.MustCompile(`^\S+$`).MatchString(txt) {
if strings.ContainsAny(txt, "\t\n\f\r ") {
location := &Location{line.LineNumber, column}
msg := "A tag may not contain whitespace"
err = &parseError{msg, location}
Expand Down