From 8ea9d4606980305f7f46cabde046adbb530e71c8 Mon Sep 17 00:00:00 2001 From: Konstantin Shaposhnikov Date: Mon, 1 Aug 2016 23:18:57 +0800 Subject: [PATCH] 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 --- refactor/rename/rename_test.go | 39 ++++++++++++++++++++++++++++++++++ refactor/rename/util.go | 3 ++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/refactor/rename/rename_test.go b/refactor/rename/rename_test.go index 3670319736d..0b3aad6510f 100644 --- a/refactor/rename/rename_test.go +++ b/refactor/rename/rename_test.go @@ -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 diff --git a/refactor/rename/util.go b/refactor/rename/util.go index f0f80f03a76..e90b7042eb5 100644 --- a/refactor/rename/util.go +++ b/refactor/rename/util.go @@ -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.