refactor/rename: do not allow a new name to be a keyword
Fixes golang/go#16535
Change-Id: I46f9b9530e25bb286557712a7969715f8dde99b9
Reviewed-on: https://go-review.googlesource.com/25343
Reviewed-by: Alan Donovan <adonovan@google.com>
diff --git a/refactor/rename/rename_test.go b/refactor/rename/rename_test.go
index 3670319..0b3aad6 100644
--- a/refactor/rename/rename_test.go
+++ b/refactor/rename/rename_test.go
@@ -416,6 +416,45 @@
}
}
+func TestInvalidIdentifiers(t *testing.T) {
+ ctxt := fakeContext(map[string][]string{
+ "main": {`
+package main
+
+func f() { }
+`}})
+
+ for _, test := range []struct {
+ from, to string // values of the -offset/-from and -to flags
+ want string // expected error message
+ }{
+ {
+ from: "main.f", to: "_",
+ want: `-to "_": not a valid identifier`,
+ },
+ {
+ from: "main.f", to: "123",
+ want: `-to "123": not a valid identifier`,
+ },
+ {
+ from: "main.f", to: "for",
+ want: `-to "for": not a valid identifier`,
+ },
+ {
+ from: "switch", to: "v",
+ want: `-from "switch": invalid expression`,
+ },
+ } {
+ err := Main(ctxt, "", test.from, test.to)
+ prefix := fmt.Sprintf("-from %q -to %q", test.from, test.to)
+ if err == nil {
+ t.Errorf("%s: expected error %q", prefix, test.want)
+ } else if err.Error() != test.want {
+ t.Errorf("%s: unexpected error\nwant: %s\n got: %s", prefix, test.want, err.Error())
+ }
+ }
+}
+
func TestRewrites(t *testing.T) {
defer func(savedWriteFile func(string, []byte) error) {
writeFile = savedWriteFile
diff --git a/refactor/rename/util.go b/refactor/rename/util.go
index f0f80f0..e90b704 100644
--- a/refactor/rename/util.go
+++ b/refactor/rename/util.go
@@ -8,6 +8,7 @@
import (
"go/ast"
+ "go/token"
"go/types"
"os"
"path/filepath"
@@ -52,7 +53,7 @@
return false
}
}
- return true
+ return token.Lookup(id) == token.IDENT
}
// isLocal reports whether obj is local to some function.