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>
This commit is contained in:
Konstantin Shaposhnikov 2016-08-01 23:18:57 +08:00 committed by Alan Donovan
parent df703d6484
commit 8ea9d46069
2 changed files with 41 additions and 1 deletions

View File

@ -416,6 +416,45 @@ var _ I = E{}
}
}
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

View File

@ -8,6 +8,7 @@ package rename
import (
"go/ast"
"go/token"
"go/types"
"os"
"path/filepath"
@ -52,7 +53,7 @@ func isValidIdentifier(id string) bool {
return false
}
}
return true
return token.Lookup(id) == token.IDENT
}
// isLocal reports whether obj is local to some function.