Debian Codegraph @

gopls/internal/golang/extracttofile.go

raw symbols SCIP
1 // Copyright 2024 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 golang
6
7 // This file defines the code action "Extract declarations to new file".
8
9 import (
10 "bytes"
11 "context"
12 "errors"
13 "fmt"
14 "go/ast"
15 "go/format"
16 "go/token"
17 "go/types"
18 "os"
19 "path/filepath"
20 "strings"
21
22 "golang.org/x/tools/gopls/internal/cache"
23 "golang.org/x/tools/gopls/internal/cache/parsego"
24 "golang.org/x/tools/gopls/internal/file"
25 "golang.org/x/tools/gopls/internal/protocol"
26 "golang.org/x/tools/gopls/internal/util/bug"
27 "golang.org/x/tools/gopls/internal/util/safetoken"
28 )
29
30 // canExtractToNewFile reports whether the code in the given range can be extracted to a new file.
31 func canExtractToNewFile(pgf *parsego.File, start, end token.Pos) bool {
32 _, _, _, ok := selectedToplevelDecls(pgf, start, end)
33 return ok
34 }
35
36 // findImportEdits finds imports specs that needs to be added to the new file
37 // or deleted from the old file if the range is extracted to a new file.
38 //
39 // TODO: handle dot imports.
40 func findImportEdits(file *ast.File, info *types.Info, start, end token.Pos) (adds, deletes []*ast.ImportSpec, _ error) {
41 // make a map from a pkgName to its references
42 pkgNameReferences := make(map[*types.PkgName][]*ast.Ident)
43 for ident, use := range info.Uses {
44 if pkgName, ok := use.(*types.PkgName); ok {
45 pkgNameReferences[pkgName] = append(pkgNameReferences[pkgName], ident)
46 }
47 }
48
49 // PkgName referenced in the extracted selection must be
50 // imported in the new file.
51 // PkgName only referenced in the extracted selection must be
52 // deleted from the original file.
53 for _, spec := range file.Imports {
54 if spec.Name != nil && spec.Name.Name == "." {
55 // TODO: support dot imports.
56 return nil, nil, errors.New("\"extract to new file\" does not support files containing dot imports")
57 }
58 pkgName := info.PkgNameOf(spec)
59 if pkgName == nil {
60 continue
61 }
62 usedInSelection := false
63 usedInNonSelection := false
64 for _, ident := range pkgNameReferences[pkgName] {
65 if posRangeContains(start, end, ident.Pos(), ident.End()) {
66 usedInSelection = true
67 } else {
68 usedInNonSelection = true
69 }
70 }
71 if usedInSelection {
72 adds = append(adds, spec)
73 }
74 if usedInSelection && !usedInNonSelection {
75 deletes = append(deletes, spec)
76 }
77 }
78
79 return adds, deletes, nil
80 }
81
82 // ExtractToNewFile moves selected declarations into a new file.
83 func ExtractToNewFile(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.DocumentChange, error) {
84 errorPrefix := "ExtractToNewFile"
85
86 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
87 if err != nil {
88 return nil, err
89 }
90
91 start, end, err := pgf.RangePos(rng)
92 if err != nil {
93 return nil, fmt.Errorf("%s: %w", errorPrefix, err)
94 }
95
96 // Expand the selection, and compute the portion to extract.
97 start, end, firstSymbol, ok := selectedToplevelDecls(pgf, start, end)
98 if !ok {
99 return nil, fmt.Errorf("invalid selection")
100 }
101 pgf.CheckPos(start) // #70553
102 // Inv: start is valid wrt pgf.Tok.
103
104 // select trailing empty lines
105 offset, err := safetoken.Offset(pgf.Tok, end)
106 if err != nil {
107 return nil, err
108 }
109 rest := pgf.Src[offset:]
110 spaces := len(rest) - len(bytes.TrimLeft(rest, " \t\n"))
111 end += token.Pos(spaces)
112 pgf.CheckPos(end) // #70553
113 if !(start <= end) {
114 bug.Reportf("start: not before end")
115 }
116 // Inv: end is valid wrt pgf.Tok; env >= start.
117 fileStart := pgf.File.FileStart
118 pgf.CheckPos(fileStart) // #70553
119 if !(0 <= start-fileStart) {
120 bug.Reportf("start: out of bounds")
121 }
122 if !(int(end-fileStart) <= len(pgf.Src)) {
123 bug.Reportf("end: out of bounds")
124 }
125 // Inv: 0 <= start-fileStart <= end-fileStart <= len(Src).
126 src := pgf.Src[start-fileStart : end-fileStart]
127
128 replaceRange, err := pgf.PosRange(start, end)
129 if err != nil {
130 return nil, bug.Errorf("invalid range: %v", err)
131 }
132
133 adds, deletes, err := findImportEdits(pgf.File, pkg.TypesInfo(), start, end)
134 if err != nil {
135 return nil, err
136 }
137
138 var importDeletes []protocol.TextEdit
139 // For unparenthesised declarations like `import "fmt"` we remove
140 // the whole declaration because simply removing importSpec leaves
141 // `import \n`, which does not compile.
142 // For parenthesised declarations like `import ("fmt"\n "log")`
143 // we only remove the ImportSpec, because removing the whole declaration
144 // might remove other ImportsSpecs we don't want to touch.
145 unparenthesizedImports := unparenthesizedImports(pgf)
146 for _, importSpec := range deletes {
147 if decl := unparenthesizedImports[importSpec]; decl != nil {
148 importDeletes = append(importDeletes, removeNode(pgf, decl))
149 } else {
150 importDeletes = append(importDeletes, removeNode(pgf, importSpec))
151 }
152 }
153
154 var buf bytes.Buffer
155 if c := CopyrightComment(pgf.File); c != nil {
156 text, err := pgf.NodeText(c)
157 if err != nil {
158 return nil, err
159 }
160 buf.Write(text)
161 // One empty line between copyright header and following.
162 buf.WriteString("\n\n")
163 }
164
165 if c := buildConstraintComment(pgf.File); c != nil {
166 text, err := pgf.NodeText(c)
167 if err != nil {
168 return nil, err
169 }
170 buf.Write(text)
171 // One empty line between build constraint and following.
172 buf.WriteString("\n\n")
173 }
174
175 fmt.Fprintf(&buf, "package %s\n", pgf.File.Name.Name)
176 if len(adds) > 0 {
177 buf.WriteString("import (")
178 for _, importSpec := range adds {
179 if importSpec.Name != nil {
180 fmt.Fprintf(&buf, "%s %s\n", importSpec.Name.Name, importSpec.Path.Value)
181 } else {
182 fmt.Fprintf(&buf, "%s\n", importSpec.Path.Value)
183 }
184 }
185 buf.WriteString(")\n")
186 }
187
188 newFile, err := chooseNewFile(ctx, snapshot, pgf.URI.DirPath(), firstSymbol)
189 if err != nil {
190 return nil, fmt.Errorf("%s: %w", errorPrefix, err)
191 }
192
193 buf.Write(src)
194
195 newFileContent, err := format.Source(buf.Bytes())
196 if err != nil {
197 return nil, err
198 }
199
200 return []protocol.DocumentChange{
201 // edit the original file
202 protocol.DocumentChangeEdit(fh, append(importDeletes, protocol.TextEdit{Range: replaceRange, NewText: ""})),
203 // create a new file
204 protocol.DocumentChangeCreate(newFile.URI()),
205 // edit the created file
206 protocol.DocumentChangeEdit(newFile, []protocol.TextEdit{
207 {Range: protocol.Range{}, NewText: string(newFileContent)},
208 })}, nil
209 }
210
211 // chooseNewFile chooses a new filename in dir, based on the name of the
212 // first extracted symbol, and if necessary to disambiguate, a numeric suffix.
213 func chooseNewFile(ctx context.Context, snapshot *cache.Snapshot, dir string, firstSymbol string) (file.Handle, error) {
214 basename := strings.ToLower(firstSymbol)
215 newPath := protocol.URIFromPath(filepath.Join(dir, basename+".go"))
216 for count := 1; count < 5; count++ {
217 fh, err := snapshot.ReadFile(ctx, newPath)
218 if err != nil {
219 return nil, err // canceled
220 }
221 if _, err := fh.Content(); errors.Is(err, os.ErrNotExist) {
222 return fh, nil
223 }
224 filename := fmt.Sprintf("%s.%d.go", basename, count)
225 newPath = protocol.URIFromPath(filepath.Join(dir, filename))
226 }
227 return nil, fmt.Errorf("chooseNewFileURI: exceeded retry limit")
228 }
229
230 // selectedToplevelDecls returns the lexical extent of the top-level
231 // declarations enclosed by [start, end), along with the name of the
232 // first declaration. The returned boolean reports whether the selection
233 // should be offered a code action to extract the declarations.
234 func selectedToplevelDecls(pgf *parsego.File, start, end token.Pos) (token.Pos, token.Pos, string, bool) {
235 // selection cannot intersect a package declaration
236 if posRangeIntersects(start, end, pgf.File.Package, pgf.File.Name.End()) {
237 return 0, 0, "", false
238 }
239 firstName := ""
240 for _, decl := range pgf.File.Decls {
241 if posRangeIntersects(start, end, decl.Pos(), decl.End()) {
242 var (
243 comment *ast.CommentGroup // (include comment preceding decl)
244 id *ast.Ident
245 )
246 switch decl := decl.(type) {
247 case *ast.BadDecl:
248 return 0, 0, "", false
249
250 case *ast.FuncDecl:
251 // if only selecting keyword "func" or function name, extend selection to the
252 // whole function
253 if posRangeContains(decl.Pos(), decl.Name.End(), start, end) {
254 pgf.CheckNode(decl) // #70553
255 start, end = decl.Pos(), decl.End()
256 // Inv: start, end are valid wrt pgf.Tok.
257 }
258 comment = decl.Doc
259 id = decl.Name
260
261 case *ast.GenDecl:
262 // selection cannot intersect an import declaration
263 if decl.Tok == token.IMPORT {
264 return 0, 0, "", false
265 }
266 // if only selecting keyword "type", "const", or "var", extend selection to the
267 // whole declaration
268 if decl.Tok == token.TYPE && posRangeContains(decl.Pos(), decl.Pos()+token.Pos(len("type")), start, end) ||
269 decl.Tok == token.CONST && posRangeContains(decl.Pos(), decl.Pos()+token.Pos(len("const")), start, end) ||
270 decl.Tok == token.VAR && posRangeContains(decl.Pos(), decl.Pos()+token.Pos(len("var")), start, end) {
271 pgf.CheckNode(decl) // #70553
272 start, end = decl.Pos(), decl.End()
273 // Inv: start, end are valid wrt pgf.Tok.
274 }
275 comment = decl.Doc
276 if len(decl.Specs) > 0 {
277 switch spec := decl.Specs[0].(type) {
278 case *ast.TypeSpec:
279 id = spec.Name
280 case *ast.ValueSpec:
281 id = spec.Names[0]
282 }
283 }
284 }
285 // selection cannot partially intersect a node
286 if !posRangeContains(start, end, decl.Pos(), decl.End()) {
287 return 0, 0, "", false
288 }
289 if id != nil && firstName == "" {
290 // may be "_"
291 firstName = id.Name
292 }
293 if comment != nil && comment.Pos() < start {
294 pgf.CheckNode(comment) // #70553
295 start = comment.Pos()
296 // Inv: start is valid wrt pgf.Tok.
297 }
298 }
299 }
300 for _, comment := range pgf.File.Comments {
301 if posRangeIntersects(start, end, comment.Pos(), comment.End()) {
302 if !posRangeContains(start, end, comment.Pos(), comment.End()) {
303 // selection cannot partially intersect a comment
304 return 0, 0, "", false
305 }
306 }
307 }
308 if firstName == "" {
309 return 0, 0, "", false
310 }
311 return start, end, firstName, true
312 }
313
314 // unparenthesizedImports returns a map from each unparenthesized ImportSpec
315 // to its enclosing declaration (which may need to be deleted too).
316 func unparenthesizedImports(pgf *parsego.File) map[*ast.ImportSpec]*ast.GenDecl {
317 decls := make(map[*ast.ImportSpec]*ast.GenDecl)
318 for _, decl := range pgf.File.Decls {
319 if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.IMPORT && !decl.Lparen.IsValid() {
320 decls[decl.Specs[0].(*ast.ImportSpec)] = decl
321 }
322 }
323 return decls
324 }
325
326 // removeNode returns a TextEdit that removes the node.
327 func removeNode(pgf *parsego.File, node ast.Node) protocol.TextEdit {
328 rng, err := pgf.NodeRange(node)
329 if err != nil {
330 bug.Reportf("removeNode: %v", err)
331 }
332 return protocol.TextEdit{Range: rng, NewText: ""}
333 }
334
335 // posRangeIntersects checks if [a, b) and [c, d) intersects, assuming a <= b and c <= d.
336 func posRangeIntersects(a, b, c, d token.Pos) bool {
337 return !(b <= c || d <= a)
338 }
339
340 // posRangeContains checks if [a, b) contains [c, d), assuming a <= b and c <= d.
341 func posRangeContains(a, b, c, d token.Pos) bool {
342 return a <= c && d <= b
343 }