Source file src/cmd/vendor/golang.org/x/tools/internal/refactor/refactor.go

     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  // TODO(adonovan): refine this to choose a fresh name only when there
    21  // would be a conflict with the existing declaration: it's fine to
    22  // redeclare a name in a narrower scope so long as there are no free
    23  // references to the outer name from within the narrower scope.
    24  func FreshName(scope *types.Scope, pos token.Pos, preferred string) string {
    25  	newName := preferred
    26  	for i := 0; ; i++ {
    27  		if _, obj := scope.LookupParent(newName, pos); obj == nil {
    28  			break // fresh
    29  		}
    30  		newName = fmt.Sprintf("%s%d", preferred, i)
    31  	}
    32  	return newName
    33  }
    34  

View as plain text