1 // Copyright 2019 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.
17 "golang.org/x/tools/go/types/typeutil"
18 "golang.org/x/tools/internal/event"
19 "golang.org/x/tools/internal/lsp/diff"
20 "golang.org/x/tools/internal/lsp/protocol"
21 "golang.org/x/tools/internal/span"
22 "golang.org/x/tools/refactor/satisfy"
23 errors "golang.org/x/xerrors"
30 objsToUpdate map[types.Object]bool
34 satisfyConstraints map[satisfy.Constraint]bool
35 packages map[*types.Package]Package // may include additional packages that are a rdep of pkg
36 msets typeutil.MethodSetCache
40 type PrepareItem struct {
45 func PrepareRename(ctx context.Context, snapshot Snapshot, f FileHandle, pp protocol.Position) (*PrepareItem, error) {
46 ctx, done := event.Start(ctx, "source.PrepareRename")
49 qos, err := qualifiedObjsAtProtocolPos(ctx, snapshot, f, pp)
53 node, obj, pkg := qos[0].node, qos[0].obj, qos[0].sourcePkg
54 mr, err := posToMappedRange(snapshot, pkg, node.Pos(), node.End())
58 rng, err := mr.Range()
62 if _, isImport := node.(*ast.ImportSpec); isImport {
63 // We're not really renaming the import path.
72 // Rename returns a map of TextEdits for each file modified when renaming a given identifier within a package.
73 func Rename(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position, newName string) (map[span.URI][]protocol.TextEdit, error) {
74 ctx, done := event.Start(ctx, "source.Rename")
77 qos, err := qualifiedObjsAtProtocolPos(ctx, s, f, pp)
85 if obj.Name() == newName {
86 return nil, errors.Errorf("old and new names are the same: %s", newName)
88 if !isValidIdentifier(newName) {
89 return nil, errors.Errorf("invalid identifier to rename: %q", newName)
91 if pkg == nil || pkg.IsIllTyped() {
92 return nil, errors.Errorf("package for %s is ill typed", f.URI())
94 refs, err := references(ctx, s, qos, true, false)
102 objsToUpdate: make(map[types.Object]bool),
105 packages: make(map[*types.Package]Package),
108 // A renaming initiated at an interface method indicates the
109 // intention to rename abstract and concrete methods as needed
110 // to preserve assignability.
111 for _, ref := range refs {
112 if obj, ok := ref.obj.(*types.Func); ok {
113 recv := obj.Type().(*types.Signature).Recv()
114 if recv != nil && IsInterface(recv.Type().Underlying()) {
115 r.changeMethods = true
120 for _, from := range refs {
121 r.packages[from.pkg.GetTypes()] = from.pkg
124 // Check that the renaming of the identifier is ok.
125 for _, ref := range refs {
127 if r.hadConflicts { // one error is enough.
132 return nil, errors.Errorf(r.errors)
135 changes, err := r.update()
139 result := make(map[span.URI][]protocol.TextEdit)
140 for uri, edits := range changes {
141 // These edits should really be associated with FileHandles for maximal correctness.
142 // For now, this is good enough.
143 fh, err := s.GetFile(ctx, uri)
147 data, err := fh.Read()
151 converter := span.NewContentConverter(uri.Filename(), data)
152 m := &protocol.ColumnMapper{
154 Converter: converter,
157 // Sort the edits first.
158 diff.SortTextEdits(edits)
159 protocolEdits, err := ToProtocolEdits(m, edits)
163 result[uri] = protocolEdits
168 // Rename all references to the identifier.
169 func (r *renamer) update() (map[span.URI][]diff.TextEdit, error) {
170 result := make(map[span.URI][]diff.TextEdit)
171 seen := make(map[span.Span]bool)
173 docRegexp, err := regexp.Compile(`\b` + r.from + `\b`)
177 for _, ref := range r.refs {
178 refSpan, err := ref.spanRange.Span()
187 // Renaming a types.PkgName may result in the addition or removal of an identifier,
188 // so we deal with this separately.
189 if pkgName, ok := ref.obj.(*types.PkgName); ok && ref.isDeclaration {
190 edit, err := r.updatePkgName(pkgName)
194 result[refSpan.URI()] = append(result[refSpan.URI()], *edit)
198 // Replace the identifier with r.to.
199 edit := diff.TextEdit{
204 result[refSpan.URI()] = append(result[refSpan.URI()], edit)
206 if !ref.isDeclaration || ref.ident == nil { // uses do not have doc comments to update.
210 doc := r.docComment(ref.pkg, ref.ident)
215 // Perform the rename in doc comments declared in the original package.
216 // go/parser strips out \r\n returns from the comment text, so go
217 // line-by-line through the comment text to get the correct positions.
218 for _, comment := range doc.List {
219 lines := strings.Split(comment.Text, "\n")
220 tok := r.fset.File(comment.Pos())
221 commentLine := tok.Position(comment.Pos()).Line
222 for i, line := range lines {
223 lineStart := comment.Pos()
225 lineStart = tok.LineStart(commentLine + i)
227 for _, locs := range docRegexp.FindAllIndex([]byte(line), -1) {
228 rng := span.NewRange(r.fset, lineStart+token.Pos(locs[0]), lineStart+token.Pos(locs[1]))
229 spn, err := rng.Span()
233 result[spn.URI()] = append(result[spn.URI()], diff.TextEdit{
245 // docComment returns the doc for an identifier.
246 func (r *renamer) docComment(pkg Package, id *ast.Ident) *ast.CommentGroup {
247 _, nodes, _ := pathEnclosingInterval(r.fset, pkg, id.Pos(), id.End())
248 for _, node := range nodes {
249 switch decl := node.(type) {
256 // For {Type,Value}Spec, if the doc on the spec is absent,
257 // search for the enclosing GenDecl
274 // updatePkgName returns the updates to rename a pkgName in the import spec
275 func (r *renamer) updatePkgName(pkgName *types.PkgName) (*diff.TextEdit, error) {
276 // Modify ImportSpec syntax to add or remove the Name as needed.
277 pkg := r.packages[pkgName.Pkg()]
278 _, path, _ := pathEnclosingInterval(r.fset, pkg, pkgName.Pos(), pkgName.Pos())
280 return nil, errors.Errorf("no path enclosing interval for %s", pkgName.Name())
282 spec, ok := path[1].(*ast.ImportSpec)
284 return nil, errors.Errorf("failed to update PkgName for %s", pkgName.Name())
287 var astIdent *ast.Ident // will be nil if ident is removed
288 if pkgName.Imported().Name() != r.to {
289 // ImportSpec.Name needed
290 astIdent = &ast.Ident{NamePos: spec.Path.Pos(), Name: r.to}
293 // Make a copy of the ident that just has the name and path.
294 updated := &ast.ImportSpec{
300 rng := span.NewRange(r.fset, spec.Pos(), spec.End())
301 spn, err := rng.Span()
307 format.Node(&buf, r.fset, updated)
308 newText := buf.String()
310 return &diff.TextEdit{