Debian Codegraph @

gopls/internal/golang/stub.go

raw symbols SCIP
1 // Copyright 2022 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 import (
8 "bytes"
9 "context"
10 "fmt"
11 "go/format"
12 "go/parser"
13 "go/token"
14 "go/types"
15 pathpkg "path"
16 "strings"
17
18 "golang.org/x/tools/go/analysis"
19 "golang.org/x/tools/go/ast/astutil"
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/cache/metadata"
22 "golang.org/x/tools/gopls/internal/cache/parsego"
23 "golang.org/x/tools/gopls/internal/golang/stubmethods"
24 "golang.org/x/tools/gopls/internal/util/bug"
25 "golang.org/x/tools/gopls/internal/util/safetoken"
26 "golang.org/x/tools/gopls/internal/util/tokeninternal"
27 "golang.org/x/tools/internal/diff"
28 )
29
30 // stubMissingInterfaceMethodsFixer returns a suggested fix to declare the missing
31 // methods of the concrete type that is assigned to an interface type
32 // at the cursor position.
33 func stubMissingInterfaceMethodsFixer(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
34 si := stubmethods.GetIfaceStubInfo(pkg.FileSet(), pkg.TypesInfo(), pgf, start, end)
35 if si == nil {
36 return nil, nil, fmt.Errorf("nil interface request")
37 }
38 return insertDeclsAfter(ctx, snapshot, pkg.Metadata(), si.Fset, si.Concrete.Obj(), si.Emit)
39 }
40
41 // stubMissingCalledFunctionFixer returns a suggested fix to declare the missing
42 // method that the user may want to generate based on CallExpr
43 // at the cursor position.
44 func stubMissingCalledFunctionFixer(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
45 si := stubmethods.GetCallStubInfo(pkg.FileSet(), pkg.TypesInfo(), pgf, start, end)
46 if si == nil {
47 return nil, nil, fmt.Errorf("invalid type request")
48 }
49 return insertDeclsAfter(ctx, snapshot, pkg.Metadata(), si.Fset, si.After, si.Emit)
50 }
51
52 // An emitter writes new top-level declarations into an existing
53 // file. References to symbols should be qualified using qual, which
54 // respects the local import environment.
55 type emitter = func(out *bytes.Buffer, qual types.Qualifier) error
56
57 // insertDeclsAfter locates the file that declares symbol sym,
58 // (which must be among the dependencies of mp),
59 // calls the emit function to generate new declarations,
60 // respecting the local import environment,
61 // and splices those declarations into the file after the declaration of sym,
62 // updating imports as needed.
63 //
64 // fset must provide the position of sym.
65 func insertDeclsAfter(ctx context.Context, snapshot *cache.Snapshot, mp *metadata.Package, fset *token.FileSet, sym types.Object, emit emitter) (*token.FileSet, *analysis.SuggestedFix, error) {
66 // Parse the file declaring the sym.
67 //
68 // Beware: declPGF is not necessarily covered by pkg.FileSet() or si.Fset.
69 declPGF, _, err := parseFull(ctx, snapshot, fset, sym)
70 if err != nil {
71 return nil, nil, fmt.Errorf("failed to parse file %q declaring implementation symbol: %w", declPGF.URI, err)
72 }
73 if declPGF.Fixed() {
74 return nil, nil, fmt.Errorf("file contains parse errors: %s", declPGF.URI)
75 }
76
77 // Find metadata for the symbol's declaring package
78 // as we'll need its import mapping.
79 declMeta := findFileInDeps(snapshot, mp, declPGF.URI)
80 if declMeta == nil {
81 return nil, nil, bug.Errorf("can't find metadata for file %s among dependencies of %s", declPGF.URI, mp)
82 }
83
84 // Build import environment for the declaring file.
85 // (typesinternal.FileQualifier works only for complete
86 // import mappings, and requires types.)
87 importEnv := make(map[ImportPath]string) // value is local name
88 for _, imp := range declPGF.File.Imports {
89 importPath := metadata.UnquoteImportPath(imp)
90 var name string
91 if imp.Name != nil {
92 name = imp.Name.Name
93 if name == "_" {
94 continue
95 } else if name == "." {
96 name = "" // see types.Qualifier
97 }
98 } else {
99 // Use the correct name from the metadata of the imported
100 // package---not a guess based on the import path.
101 mp := snapshot.Metadata(declMeta.DepsByImpPath[importPath])
102 if mp == nil {
103 continue // can't happen?
104 }
105 name = string(mp.Name)
106 }
107 importEnv[importPath] = name // latest alias wins
108 }
109
110 // Create a package name qualifier that uses the
111 // locally appropriate imported package name.
112 // It records any needed new imports.
113 // TODO(adonovan): factor with golang.FormatVarType?
114 //
115 // Prior to CL 469155 this logic preserved any renaming
116 // imports from the file that declares the interface
117 // method--ostensibly the preferred name for imports of
118 // frequently renamed packages such as protobufs.
119 // Now we use the package's declared name. If this turns out
120 // to be a mistake, then use parseHeader(si.iface.Pos()).
121 //
122 type newImport struct{ name, importPath string }
123 var newImports []newImport // for AddNamedImport
124 qual := func(pkg *types.Package) string {
125 // TODO(adonovan): don't ignore vendor prefix.
126 //
127 // Ignore the current package import.
128 if pkg.Path() == sym.Pkg().Path() {
129 return ""
130 }
131
132 importPath := ImportPath(pkg.Path())
133 name, ok := importEnv[importPath]
134 if !ok {
135 // Insert new import using package's declared name.
136 //
137 // TODO(adonovan): resolve conflict between declared
138 // name and existing file-level (declPGF.File.Imports)
139 // or package-level (sym.Pkg.Scope) decls by
140 // generating a fresh name.
141 name = pkg.Name()
142 importEnv[importPath] = name
143 new := newImport{importPath: string(importPath)}
144 // For clarity, use a renaming import whenever the
145 // local name does not match the path's last segment.
146 if name != pathpkg.Base(trimVersionSuffix(new.importPath)) {
147 new.name = name
148 }
149 newImports = append(newImports, new)
150 }
151 return name
152 }
153
154 // Compute insertion point for new declarations:
155 // after the top-level declaration enclosing the (package-level) type.
156 insertOffset, err := safetoken.Offset(declPGF.Tok, declPGF.File.End())
157 if err != nil {
158 return nil, nil, bug.Errorf("internal error: end position outside file bounds: %v", err)
159 }
160 symOffset, err := safetoken.Offset(fset.File(sym.Pos()), sym.Pos())
161 if err != nil {
162 return nil, nil, bug.Errorf("internal error: finding type decl offset: %v", err)
163 }
164 for _, decl := range declPGF.File.Decls {
165 declEndOffset, err := safetoken.Offset(declPGF.Tok, decl.End())
166 if err != nil {
167 return nil, nil, bug.Errorf("internal error: finding decl offset: %v", err)
168 }
169 if declEndOffset > symOffset {
170 insertOffset = declEndOffset
171 break
172 }
173 }
174
175 // Splice the new declarations into the file content.
176 var buf bytes.Buffer
177 input := declPGF.Mapper.Content // unfixed content of file
178 buf.Write(input[:insertOffset])
179 buf.WriteByte('\n')
180 err = emit(&buf, qual)
181 if err != nil {
182 return nil, nil, err
183 }
184 buf.Write(input[insertOffset:])
185
186 // Re-parse the file.
187 fset = token.NewFileSet()
188 newF, err := parser.ParseFile(fset, declPGF.URI.Path(), buf.Bytes(), parser.ParseComments|parser.SkipObjectResolution)
189 if err != nil {
190 return nil, nil, fmt.Errorf("could not reparse file: %w", err)
191 }
192
193 // Splice the new imports into the syntax tree.
194 for _, imp := range newImports {
195 astutil.AddNamedImport(fset, newF, imp.name, imp.importPath)
196 }
197
198 // Pretty-print.
199 var output bytes.Buffer
200 if err := format.Node(&output, fset, newF); err != nil {
201 return nil, nil, fmt.Errorf("format.Node: %w", err)
202 }
203
204 // Report the diff.
205 diffs := diff.Bytes(input, output.Bytes())
206 return tokeninternal.FileSetFor(declPGF.Tok), // edits use declPGF.Tok
207 &analysis.SuggestedFix{TextEdits: diffToTextEdits(declPGF.Tok, diffs)},
208 nil
209 }
210
211 // diffToTextEdits converts diff (offset-based) edits to analysis (token.Pos) form.
212 func diffToTextEdits(tok *token.File, diffs []diff.Edit) []analysis.TextEdit {
213 edits := make([]analysis.TextEdit, 0, len(diffs))
214 for _, edit := range diffs {
215 edits = append(edits, analysis.TextEdit{
216 Pos: tok.Pos(edit.Start),
217 End: tok.Pos(edit.End),
218 NewText: []byte(edit.New),
219 })
220 }
221 return edits
222 }
223
224 // trimVersionSuffix removes a trailing "/v2" (etc) suffix from a module path.
225 //
226 // This is only a heuristic as to the package's declared name, and
227 // should only be used for stylistic decisions, such as whether it
228 // would be clearer to use an explicit local name in the import
229 // because the declared name differs from the result of this function.
230 // When the name matters for correctness, look up the imported
231 // package's Metadata.Name.
232 func trimVersionSuffix(path string) string {
233 dir, base := pathpkg.Split(path)
234 if len(base) > 1 && base[0] == 'v' && strings.Trim(base[1:], "0123456789") == "" {
235 return dir // sans "/v2"
236 }
237 return path
238 }