forked from KurokuLabs/margo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gocode_suggest.go
280 lines (238 loc) · 6.7 KB
/
gocode_suggest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package golang
import (
"errors"
"go/build"
"go/types"
"kuroku.io/margocode/suggest"
"margo.sh/golang/gopkg"
"margo.sh/mg"
"margo.sh/mgutil"
"runtime/debug"
"strings"
"sync"
"time"
)
var (
errImportCycleDetected = errors.New("import cycle detected")
)
type gsuImpRes struct {
pkg *types.Package
err error
}
type gcSuggest struct {
suggestDebug bool
partials bool
cfg MarGocodeCtl
sync.Mutex
imp *gsuImporter
}
func (gsu *gcSuggest) newGsuImporter(mx *mg.Ctx) *gsuImporter {
gi := &gsuImporter{
mx: mx,
bld: BuildContext(mx),
}
gi.res.m = map[mgcCacheKey]gsuImpRes{}
return gi
}
func (gsu *gcSuggest) noPartialsPos(src []byte, pos int) int {
// move the cursor off the word.
// xxx.yyy| ~> xxx.|
// xxx| ~> |xxx
// this results in fetching all possible results
// which is desirable because the editor is usually better at filtering the list
return mgutil.RepositionLeft(src, pos, IsLetter)
}
func (gsu *gcSuggest) suggestions(mx *mg.Ctx, src []byte, pos int) suggestions {
defer mx.Profile.Push("suggestions").Pop()
sugg := suggestions{}
if len(src) == 0 {
return sugg
}
gsu.Lock()
defer gsu.Unlock()
defer func() {
if e := recover(); e != nil {
mx.Log.Printf("gocode/suggest panic: %s\n%s\n", e, debug.Stack())
}
}()
cfg := suggest.Config{
// we no longer support contextual build env :(
// GoSublime works around this for other packages by restarting the agent
// if GOPATH changes, so we should be ok
Importer: gsu.imp,
Builtin: !gsu.cfg.NoBuiltins,
IgnoreCase: true,
}
if !gsu.cfg.NoUnimportedPackages {
srcDir := mx.View.Dir()
cfg.UnimportedPackage = func(nm string) *types.Package {
pkg, pth := gsu.imp.importFromName(nm, srcDir)
if pkg != nil {
sugg.unimported.Name = nm
sugg.unimported.Path = pth
}
return pkg
}
}
if gsu.suggestDebug {
cfg.Logf = func(f string, a ...interface{}) {
f = "Gocode: " + f
if !strings.HasSuffix(f, "\n") {
f += "\n"
}
mx.Log.Dbg.Printf(f, a...)
}
}
if !gsu.partials {
pos = gsu.noPartialsPos(src, pos)
}
sugg.candidates, _ = cfg.Suggest(mx.View.Filename(), src, pos)
return sugg
}
type gsuPkgInfo struct {
// the import path
Path string
// the abs path to the package directory
Dir string
// whether or not this is a stdlib package
Std bool
}
func (p gsuPkgInfo) cacheKey(source bool) mgcCacheKey {
return mgcCacheKey{gsuPkgInfo: p, Source: source}
}
type gsuImporter struct {
mx *mg.Ctx
bld *build.Context
res struct {
sync.Mutex
m map[mgcCacheKey]gsuImpRes
}
}
func (gi *gsuImporter) Import(path string) (*types.Package, error) {
return gi.ImportFrom(path, ".", 0)
}
func (gi *gsuImporter) importFromName(pkgName, srcDir string) (pkg *types.Package, impPath string) {
impPath = mctl.importPathByName(pkgName, srcDir)
if impPath == "" {
return nil, ""
}
pkg, _ = gi.ImportFrom(impPath, srcDir, 0)
return pkg, impPath
}
func (gi *gsuImporter) ImportFrom(impPath, srcDir string, mode types.ImportMode) (pkg *types.Package, err error) {
// TODO: add mode to the key somehow?
// mode is reserved, but currently not used so it's not a problem
// but if it's used in the future, the importer result could depend on it
//
// adding it to the key might complicate the pkginfo api because it's called
// by code that doesn't know anything about mode
pkgInf, err := mctl.pkgInfo(gi.mx, impPath, srcDir)
if err != nil {
mctl.dbgf("pkgInfo(%q, %q): %s\n", impPath, srcDir, err)
return nil, err
}
newDefImpr, newFbkImpr, srcMode := mctl.importerFactories()
k := pkgInf.cacheKey(srcMode)
gi.res.Lock()
res, seen := gi.res.m[k]
if !seen {
gi.res.m[k] = gsuImpRes{err: errImportCycleDetected}
}
gi.res.Unlock()
// we cache the results of the underlying importer for this *session*
// because if it fails, or there's an import cycle, we could potentialy end up in a loop
// trying to import the package again.
if seen {
return res.pkg, res.err
}
defer func() {
gi.res.Lock()
defer gi.res.Unlock()
gi.res.m[k] = gsuImpRes{pkg: pkg, err: err}
}()
defImpr := newDefImpr(gi.mx, gi)
pkg, err = gi.importFrom(defImpr, k, srcDir, mode)
complete := err == nil && pkg.Complete()
if complete {
return pkg, nil
}
mctl.dbgf("importFrom(%q, %q): default=%T: complete=%v, err=%v\n",
k.Path, k.Dir, defImpr, complete, err,
)
// no fallback allowed
if newFbkImpr == nil {
return pkg, err
}
// problem1:
// if the pkg import fails we will offer no completion
//
// problem 2:
// if it succeeds, but is incomplete we offer completion with `invalid-type` failures
// i.e. completion stops working at random points for no obvious reason
//
// assumption:
// it's better to risk using stale data (bin imports)
// as opposed to offering no completion at all
//
// risks:
// we will end up caching the result, but that shouldn't be a big deal
// because if the pkg is edited, thus (possibly) making it importable,
// we will remove it from the cache anyway.
// there is the issue about mixing binary (potentially incomplete) pkgs with src pkgs
// but we were already not going to return anything, so it *shouldn't* apply here
fbkImpr := newFbkImpr(gi.mx, gi)
fbkPkg, fbkErr := gi.importFrom(fbkImpr, k.fallback(), srcDir, mode)
fbkComplete := fbkErr == nil && fbkPkg.Complete()
switch {
case fbkComplete:
pkg, err = fbkPkg, nil
case fbkPkg != nil && pkg == nil:
pkg, err = fbkPkg, fbkErr
}
mctl.dbgf("importFrom(%q, %q): fallback=%T: complete=%v, err=%v\n",
k.Path, k.Dir, fbkImpr, fbkComplete, fbkErr,
)
return pkg, err
}
func (gi *gsuImporter) importFrom(underlying types.ImporterFrom, ck mgcCacheKey, srcDir string, mode types.ImportMode) (*types.Package, error) {
_, memo, err := gi.mx.VFS.Memo(ck.Dir)
if err != nil {
return nil, err
}
type K struct{ mgcCacheKey }
type V struct {
p *types.Package
e error
}
k := K{ck}
v := memo.Read(k, func() interface{} {
p, err := gi.doImportFrom(underlying, ck, srcDir, mode)
return V{p: p, e: err}
}).(V)
return v.p, v.e
}
func (gi *gsuImporter) doImportFrom(underlying types.ImporterFrom, k mgcCacheKey, srcDir string, mode types.ImportMode) (*types.Package, error) {
defer gi.mx.Profile.Push("gsuImport: " + k.Path).Pop()
if k.Std && k.Path == "unsafe" {
return types.Unsafe, nil
}
if e, ok := mctl.pkgs.get(k); ok {
return e.Pkg, nil
}
impStart := time.Now()
pkg, err := underlying.ImportFrom(k.Path, srcDir, mode)
impDur := time.Since(impStart)
if err == nil {
mctl.pkgs.put(mgcCacheEnt{Key: k, Pkg: pkg, Dur: impDur})
if _, ok := mctl.plst.View().ByDir[k.Dir]; !ok {
mctl.plst.Add(gopkg.Pkg{
Dir: k.Dir,
ImportPath: k.Path,
Name: pkg.Name(),
})
}
} else {
mctl.dbgf("%T.ImportFrom(%q, %q): %s\n", underlying, k.Path, k.Dir, err)
}
return pkg, err
}