| 1 | // Copyright 2025 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package refactor provides operators to compute common textual edits |
| 6 | // for refactoring tools. |
| 7 | // |
| 8 | // This package should not use features of the analysis API other than [Edit]. |
| 9 | package refactor |
| 10 | |
| 11 | import ( |
| 12 | "fmt" |
| 13 | "go/token" |
| 14 | "go/types" |
| 15 | ) |
| 16 | |
| 17 | // FreshName returns the name of an identifier that is undefined |
| 18 | // at the specified position, based on the preferred name. |
| 19 | // |
| 20 | // export/use freshName in go/analysis/passes/modernize/modernize.go if you want |
| 21 | // to generate a fresh name only when necessary (i.e., there is both an existing |
| 22 | // declaration and some free reference to the name within a narrower scope) |
| 23 | func FreshName(scope *types.Scope, pos token.Pos, preferred string) string { |
| 24 | newName := preferred |
| 25 | for i := 0; ; i++ { |
| 26 | if _, obj := scope.LookupParent(newName, pos); obj == nil { |
| 27 | break // fresh |
| 28 | } |
| 29 | newName = fmt.Sprintf("%s%d", preferred, i) |
| 30 | } |
| 31 | return newName |
| 32 | } |