| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
|
| 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 |
|
| 31 |
func canExtractToNewFile(pgf *parsego.File, start, end token.Pos) bool { |
| 32 |
_, _, _, ok := selectedToplevelDecls(pgf, start, end) |
| 33 |
return ok |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
func findImportEdits(file *ast.File, info *types.Info, start, end token.Pos) (adds, deletes []*ast.ImportSpec, _ error) { |
| 41 |
|
| 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 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
for _, spec := range file.Imports { |
| 54 |
if spec.Name != nil && spec.Name.Name == "." { |
| 55 |
|
| 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 |
|
| 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 |
|
| 97 |
start, end, firstSymbol, ok := selectedToplevelDecls(pgf, start, end) |
| 98 |
if !ok { |
| 99 |
return nil, fmt.Errorf("invalid selection") |
| 100 |
} |
| 101 |
pgf.CheckPos(start) |
| 102 |
|
| 103 |
|
| 104 |
|
| 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) |
| 113 |
if !(start <= end) { |
| 114 |
bug.Reportf("start: not before end") |
| 115 |
} |
| 116 |
|
| 117 |
fileStart := pgf.File.FileStart |
| 118 |
pgf.CheckPos(fileStart) |
| 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 |
|
| 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 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 202 |
protocol.DocumentChangeEdit(fh, append(importDeletes, protocol.TextEdit{Range: replaceRange, NewText: ""})), |
| 203 |
|
| 204 |
protocol.DocumentChangeCreate(newFile.URI()), |
| 205 |
|
| 206 |
protocol.DocumentChangeEdit(newFile, []protocol.TextEdit{ |
| 207 |
{Range: protocol.Range{}, NewText: string(newFileContent)}, |
| 208 |
})}, nil |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
|
| 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 |
| 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 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
func selectedToplevelDecls(pgf *parsego.File, start, end token.Pos) (token.Pos, token.Pos, string, bool) { |
| 235 |
|
| 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 |
| 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 |
|
| 252 |
|
| 253 |
if posRangeContains(decl.Pos(), decl.Name.End(), start, end) { |
| 254 |
pgf.CheckNode(decl) |
| 255 |
start, end = decl.Pos(), decl.End() |
| 256 |
|
| 257 |
} |
| 258 |
comment = decl.Doc |
| 259 |
id = decl.Name |
| 260 |
|
| 261 |
case *ast.GenDecl: |
| 262 |
|
| 263 |
if decl.Tok == token.IMPORT { |
| 264 |
return 0, 0, "", false |
| 265 |
} |
| 266 |
|
| 267 |
|
| 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) |
| 272 |
start, end = decl.Pos(), decl.End() |
| 273 |
|
| 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 |
|
| 286 |
if !posRangeContains(start, end, decl.Pos(), decl.End()) { |
| 287 |
return 0, 0, "", false |
| 288 |
} |
| 289 |
if id != nil && firstName == "" { |
| 290 |
|
| 291 |
firstName = id.Name |
| 292 |
} |
| 293 |
if comment != nil && comment.Pos() < start { |
| 294 |
pgf.CheckNode(comment) |
| 295 |
start = comment.Pos() |
| 296 |
|
| 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 |
|
| 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 |
|
| 315 |
|
| 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 |
|
| 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 |
|
| 336 |
func posRangeIntersects(a, b, c, d token.Pos) bool { |
| 337 |
return !(b <= c || d <= a) |
| 338 |
} |
| 339 |
|
| 340 |
|
| 341 |
func posRangeContains(a, b, c, d token.Pos) bool { |
| 342 |
return a <= c && d <= b |
| 343 |
} |