Skip to content

Commit

Permalink
lint: avoid suggesting to use a keyword as a valid name
Browse files Browse the repository at this point in the history
In some circumstances the programmer is tempted to use a Go reserved
keyword as a name. A common ofender is the word "type". The Go compiler
will not accept that, of course. In those situations a common strategy
is to append an underline to the keyword, in order to make the compiler
happy. Thus, the name "type" would be changed to "type_" and so on.

The golint considered that use of underline as bad style and was wrongly
suggesting as a corrective action employing the original keyword as name:

astVarRef.go:6:2: don't use underscores in Go names; struct field type_ should be type
cmdIf.go:32:3: don't use underscores in Go names; var goto_ should be goto

This CL changes golint so that it doesn't make such invalid suggestion.

Fixes golang#393
  • Loading branch information
jucie committed Oct 11, 2019
1 parent 479c2bd commit 1f7e6ed
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,11 @@ func isInTopLevel(f *ast.File, ident *ast.Ident) bool {
return true
}

// isGoKeyword returns true if "name" is a reserved keyword.
func isGoKeyword(name string) bool {
return keywords[name]
}

// lintNames examines all names in the file.
// It complains if any use underscores or incorrect known initialisms.
func (f *file) lintNames() {
Expand Down Expand Up @@ -596,7 +601,7 @@ func (f *file) lintNames() {
}

if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") {
if keywords[should] {
if isGoKeyword(should) {
return // refrain from suggesting the use of a keyword as a valid name.
}
f.errorf(id, 0.9, link("http://golang.org/doc/effective_go.html#mixed-caps"), category("naming"), "don't use underscores in Go names; %s %s should be %s", thing, id.Name, should)
Expand Down
17 changes: 17 additions & 0 deletions lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,23 @@ func TestLintName(t *testing.T) {
}
}

func TestKeyword(t *testing.T) {
tests := []struct {
name string
want bool
}{
{"type", true},
{"goto", true},
{"while", false},
}
for _, test := range tests {
got := isGoKeyword(test.name)
if got != test.want {
t.Errorf("isGoKeyword(%q) = %t, want %t", test.name, got, test.want)
}
}
}

func TestExportedType(t *testing.T) {
tests := []struct {
typString string
Expand Down

0 comments on commit 1f7e6ed

Please sign in to comment.