Skip to content

Commit

Permalink
chore(lint): forbid usage of regexp.Match(String)? (#2066)
Browse files Browse the repository at this point in the history
Just to avoid [this
comment](#875 (comment))
again :)
  • Loading branch information
thehowl authored May 26, 2024
1 parent 0a1e732 commit 50bf659
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 25 deletions.
5 changes: 5 additions & 0 deletions .github/golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ linters:
- gofumpt # Stricter gofmt
- unused # Checks Go code for unused constants, variables, functions and types
- gomodguard # Enforces an allow and block list for direct Go module dependencies
- forbidigo # Forbids some custom-set identifiers, like regexp.MatchString

linters-settings:
gofmt:
Expand All @@ -60,6 +61,10 @@ linters-settings:
- opinionated
- performance
- style
forbidigo:
forbid:
- p: '^regexp\.(Match|MatchString)$'
msg: it will re-compile the regexp for each execution; compile the regexp with regexp.Compile and store it as a singleton

issues:
whole-files: true
Expand Down
48 changes: 23 additions & 25 deletions tm2/pkg/amino/genproto/bindings.go
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,27 @@ func _fields(args ...interface{}) *ast.FieldList {
}
}

const (
reDGTS = `(?:[0-9]+)`
reHExX = `(?:0[xX][0-9a-fA-F]+)`
rePSCI = `(?:[eE]+?[0-9]+)`
reNSCI = `(?:[eE]-[1-9][0-9]+)`
reASCI = `(?:[eE][-+]?[0-9]+)`
)

var (
reIsInt = regexp.MustCompile(
`^-?(?:` +
reDGTS + `|` +
reHExX + `)` + rePSCI + `?$`,
)
reIsFloat = regexp.MustCompile(
`^-?(?:` +
reDGTS + `\.` + reDGTS + reASCI + `?|` +
reDGTS + reNSCI + `)$`,
)
)

// Parses simple expressions (but not all).
// Useful for parsing strings to ast nodes, like foo.bar["qwe"](),
// new(bytes.Buffer), *bytes.Buffer, package.MyStruct{FieldA:1}, numeric
Expand Down Expand Up @@ -1282,38 +1303,15 @@ func _x(expr string, args ...interface{}) ast.Expr {
}
}
// Numeric int? We do these before dots, because dots are legal in numbers.
const (
DGTS = `(?:[0-9]+)`
HExX = `(?:0[xX][0-9a-fA-F]+)`
PSCI = `(?:[eE]+?[0-9]+)`
NSCI = `(?:[eE]-[1-9][0-9]+)`
ASCI = `(?:[eE][-+]?[0-9]+)`
)
isInt, err := regexp.Match(
`^-?(?:`+
DGTS+`|`+
HExX+`)`+PSCI+`?$`,
[]byte(expr),
)
if err != nil {
panic("should not happen")
}
isInt := reIsInt.MatchString(expr)
if isInt {
return &ast.BasicLit{
Kind: token.INT,
Value: expr,
}
}
// Numeric float? We do these before dots, because dots are legal in floats.
isFloat, err := regexp.Match(
`^-?(?:`+
DGTS+`\.`+DGTS+ASCI+`?|`+
DGTS+NSCI+`)$`,
[]byte(expr),
)
if err != nil {
panic("should not happen")
}
isFloat := reIsFloat.MatchString(expr)
if isFloat {
return &ast.BasicLit{
Kind: token.FLOAT,
Expand Down

0 comments on commit 50bf659

Please sign in to comment.