Skip to content

Commit

Permalink
refactor: simplify IsPredeclaredGoIdentifier
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed Jan 28, 2024
1 parent ad5eada commit f1f9c99
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 55 deletions.
59 changes: 4 additions & 55 deletions pkg/codegen/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package codegen

import (
"fmt"
"go/doc"
"go/token"
"net/url"
"reflect"
Expand All @@ -28,64 +29,13 @@ import (
)

var (
pathParamRE *regexp.Regexp
predeclaredSet map[string]struct{}
separatorSet map[rune]struct{}
pathParamRE *regexp.Regexp
separatorSet map[rune]struct{}
)

func init() {
pathParamRE = regexp.MustCompile(`{[.;?]?([^{}*]+)\*?}`)

predeclaredIdentifiers := []string{
// Types
"bool",
"byte",
"complex64",
"complex128",
"error",
"float32",
"float64",
"int",
"int8",
"int16",
"int32",
"int64",
"rune",
"string",
"uint",
"uint8",
"uint16",
"uint32",
"uint64",
"uintptr",
// Constants
"true",
"false",
"iota",
// Zero value
"nil",
// Functions
"append",
"cap",
"close",
"complex",
"copy",
"delete",
"imag",
"len",
"make",
"new",
"panic",
"print",
"println",
"real",
"recover",
}
predeclaredSet = map[string]struct{}{}
for _, id := range predeclaredIdentifiers {
predeclaredSet[id] = struct{}{}
}

separators := "-#@!$&=.+:;_~ (){}[]"
separatorSet = map[rune]struct{}{}
for _, r := range separators {
Expand Down Expand Up @@ -573,8 +523,7 @@ func IsGoKeyword(str string) bool {
//
// See https://golang.org/ref/spec#Predeclared_identifiers
func IsPredeclaredGoIdentifier(str string) bool {
_, exists := predeclaredSet[str]
return exists
return doc.IsPredeclared(str)
}

// IsGoIdentity checks if the given string can be used as an identity
Expand Down
20 changes: 20 additions & 0 deletions pkg/codegen/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -608,3 +608,23 @@ func Test_replaceInitialisms(t *testing.T) {
})
}
}

func TestIsPredeclaredGoIdentifier(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want bool
}{
{name: "empty string", args: args{s: ""}, want: false},
{name: "not predeclared", args: args{s: "foo"}, want: false},
{name: "predeclared", args: args{s: "any"}, want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, IsPredeclaredGoIdentifier(tt.args.s))
})
}
}

0 comments on commit f1f9c99

Please sign in to comment.