Skip to content

Commit 1f7e6ed

Browse files
committed
lint: avoid suggesting to use a keyword as a valid name
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
1 parent 479c2bd commit 1f7e6ed

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lint.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,11 @@ func isInTopLevel(f *ast.File, ident *ast.Ident) bool {
551551
return true
552552
}
553553

554+
// isGoKeyword returns true if "name" is a reserved keyword.
555+
func isGoKeyword(name string) bool {
556+
return keywords[name]
557+
}
558+
554559
// lintNames examines all names in the file.
555560
// It complains if any use underscores or incorrect known initialisms.
556561
func (f *file) lintNames() {
@@ -596,7 +601,7 @@ func (f *file) lintNames() {
596601
}
597602

598603
if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") {
599-
if keywords[should] {
604+
if isGoKeyword(should) {
600605
return // refrain from suggesting the use of a keyword as a valid name.
601606
}
602607
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)

lint_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,23 @@ func TestLintName(t *testing.T) {
252252
}
253253
}
254254

255+
func TestKeyword(t *testing.T) {
256+
tests := []struct {
257+
name string
258+
want bool
259+
}{
260+
{"type", true},
261+
{"goto", true},
262+
{"while", false},
263+
}
264+
for _, test := range tests {
265+
got := isGoKeyword(test.name)
266+
if got != test.want {
267+
t.Errorf("isGoKeyword(%q) = %t, want %t", test.name, got, test.want)
268+
}
269+
}
270+
}
271+
255272
func TestExportedType(t *testing.T) {
256273
tests := []struct {
257274
typString string

0 commit comments

Comments
 (0)