A constant regular expression is compiled on every iteration of a loop

tx0/go:regexp-in-looprecommendedwarningperformance

What it finds

regexp.MustCompile or regexp.Compile with a constant pattern inside a loop: the same expression is compiled again on every iteration.

The pattern must be a constant string as [Scopes::constant_string] reads it, and the call must be in the body of the loop, not in a function literal inside it.

From the rule's source, regexp_in_loop.rs.

Example from the rule's tests
package p import (	"regexp"	re "regexp") const word = `\w+` var once = regexp.MustCompile(word) func match(lines, patterns []string) int {	n := 0	for _, line := range lines {		if regexp.MustCompile(`^\d+$`).MatchString(line) {tx0 reports: regexp.MustCompile compiles the same pattern on every iteration			n++		}		r, err := re.Compile("^" + word + "$")tx0 reports: re.Compile compiles the same pattern on every iteration		if err == nil && r.MatchString(line) {			n++		}		for i := 0; i < 2; i++ {			_ = regexp.MustCompilePOSIX("a|b")tx0 reports: regexp.MustCompilePOSIX compiles the same pattern		}		check := func() bool { return regexp.MustCompile("x").MatchString(line) }		_ = check	}	for _, p := range patterns {		_ = regexp.MustCompile(p)	}	for _, m := range regexp.MustCompile("y").FindAllString(lines[0], -1) {		_ = m	}	return n + len(once.String())}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:regexp-in-loop" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:regexp-in-loop] reason="..."

tx0 explain tx0/go:regexp-in-loop shows the same in the terminal. Found a false positive? Report it.