-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
350 lines (299 loc) · 8.71 KB
/
loader.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package langd
import (
"fmt"
"go/build"
"go/types"
"io"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"unicode/utf8"
"github.com/gobwas/glob"
"github.com/object88/langd/collections"
"github.com/object88/langd/log"
"github.com/pkg/errors"
"github.com/spf13/afero"
)
// Loader is the workspace-specific configuration and context for
// building and type-checking
type Loader struct {
StartDir string
filteredPaths []glob.Glob
hash collections.Hash
Tags []string
Log *log.Log
le *LoaderEngine
fs afero.Fs
config *types.Config
context build.Context
unsafePath string
distinctPackageHashSet map[collections.Hash]bool
m sync.Mutex
c *sync.Cond
}
// LoaderOption provides a hook for NewLoader to set or modify
// the new loader's build.Context
type LoaderOption func(l *Loader)
// NewLoader creates a new Loader
func NewLoader(le *LoaderEngine, goos, goarch, goroot string, options ...LoaderOption) *Loader {
globs := make([]glob.Glob, 2)
globs[0] = glob.MustCompile(filepath.Join("**", ".*"))
globs[1] = glob.MustCompile(filepath.Join("**", "testdata"))
l := &Loader{
StartDir: "--",
context: build.Default,
filteredPaths: globs,
fs: afero.NewReadOnlyFs(afero.NewOsFs()),
le: le,
distinctPackageHashSet: map[collections.Hash]bool{},
}
l.c = sync.NewCond(&l.m)
l.context.GOARCH = goarch
l.context.GOOS = goos
l.context.GOROOT = goroot
for _, opt := range options {
opt(l)
}
l.context.IsDir = func(path string) bool {
fi, err := l.fs.Stat(path)
return err == nil && fi.IsDir()
}
l.context.OpenFile = func(path string) (io.ReadCloser, error) {
f, err := l.fs.Open(path)
if err != nil {
return nil, err
}
return f, nil
}
l.context.ReadDir = func(dir string) ([]os.FileInfo, error) {
f, err := l.fs.Open(dir)
if err != nil {
return nil, err
}
list, err := f.Readdir(-1)
f.Close()
if err != nil {
return nil, err
}
sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
return list, nil
}
l.config = &types.Config{
Error: l.HandleTypeCheckerError,
Importer: &loaderImporter{l: l},
}
l.hash = calculateHashFromStrings(append([]string{goroot, goarch, goos}, l.Tags...)...)
l.unsafePath = filepath.Join(goroot, "src", "unsafe")
return l
}
// Errors exposes problems with code found during compilation on a file-by-file
// basis.
func (l *Loader) Errors(handleErrs func(file string, errs []FileError)) {
for hash := range l.distinctPackageHashSet {
n, ok := l.le.caravan.Find(hash)
if !ok {
// TODO: This is probably a poor way of handling this problem. The error
// will bubble up to the user, who will have no idea what the hash means.
errs := []FileError{
FileError{
Message: fmt.Sprintf("Failed to find node in caravan with hash 0x%016x", hash),
Warning: false,
},
}
handleErrs("", errs)
continue
}
dp := n.Element.(*DistinctPackage)
for fname, f := range dp.files {
if len(f.errs) != 0 {
handleErrs(filepath.Join(dp.Package.AbsPath, fname), f.errs)
}
}
}
}
func (l *Loader) calculateDistinctPackageHash(absPath string) collections.Hash {
phash := calculateHashFromString(absPath)
chash := combineHashes(phash, l.hash)
return chash
}
// GetTags produces a string detailing the GOROOT, GOARCH, GOOS, and any tags
func (l *Loader) GetTags() string {
var sb strings.Builder
sb.WriteRune('[')
sb.WriteString(l.context.GOROOT)
sb.WriteRune(',')
sb.WriteString(l.context.GOARCH)
sb.WriteRune(',')
sb.WriteString(l.context.GOOS)
for _, v := range l.Tags {
sb.WriteRune(',')
sb.WriteString(v)
}
sb.WriteRune(']')
return sb.String()
}
func (l *Loader) areAllPackagesComplete() bool {
l.m.Lock()
if len(l.distinctPackageHashSet) == 0 {
// NOTE: this is a stopgap to address the problem where a loader context
// will report that all packages are loaded before any of them have been
// processed. If we have a situation where a loader context is reading
// a directory structure where there are legitimately no packages, this
// will be a problem.
fmt.Printf("loader.areAllPackagesComplete (%s): have zero packages\n", l)
l.m.Unlock()
return false
}
complete := true
caravan := l.le.caravan
for chash := range l.distinctPackageHashSet {
n, ok := caravan.Find(chash)
if !ok {
fmt.Printf("loader.areAllPackagesComplete (%s): package hash 0x%016x not found in caravan\n", l, chash)
complete = false
break
}
dp := n.Element.(*DistinctPackage)
if !ok {
fmt.Printf("loader.areAllPackagesComplete (%s): distinct package for %s not found\n", l, dp)
complete = false
break
}
loadState := dp.loadState.get()
if loadState != done {
complete = false
break
}
}
l.m.Unlock()
return complete
}
func (l *Loader) checkPackage(dp *DistinctPackage) error {
l.m.Lock()
err := dp.check()
l.m.Unlock()
return err
}
func (l *Loader) ensureDistinctPackage(absPath string) (*DistinctPackage, bool) {
chash := l.calculateDistinctPackageHash(absPath)
n, created := l.le.caravan.Ensure(chash, func() collections.Hasher {
l.Log.Debugf("ensureDistinctPackage: miss on hash 0x%016x; creating package for '%s'.\n", chash, absPath)
p, _ := l.le.ensurePackage(absPath)
return NewDistinctPackage(l, p)
})
dp := n.Element.(*DistinctPackage)
dp.Package.m.Lock()
dp.Package.loaders[l] = true
dp.Package.m.Unlock()
l.m.Lock()
l.distinctPackageHashSet[chash] = true
l.m.Unlock()
return dp, created
}
// FindDistinctPackage will locate the distinct package at the provided path
func (l *Loader) FindDistinctPackage(absPath string) (*DistinctPackage, error) {
chash := l.calculateDistinctPackageHash(absPath)
n, ok := l.le.caravan.Find(chash)
if !ok {
return nil, errors.Errorf("Loader does not have an entry for %s with tags %s", absPath, l.GetTags())
}
dp := n.Element.(*DistinctPackage)
return dp, nil
}
func (l *Loader) FindImportPath(dp *DistinctPackage, importPath string) (string, error) {
targetPath, err := l.findImportPath(importPath, dp.Package.AbsPath)
if err != nil {
err := errors.Wrap(err, fmt.Sprintf("Failed to find import %s", importPath))
return "", err
}
if targetPath == dp.Package.AbsPath {
l.Log.Debugf("Failed due to self-import\n")
return "", err
}
return targetPath, nil
}
// LoadDirectory adds the contents of a directory to the Loader
func (l *Loader) LoadDirectory(startDir string) error {
if strings.HasPrefix(startDir, "file://") {
startDir = startDir[utf8.RuneCountInString("file://"):]
}
startDir, err := filepath.Abs(startDir)
if err != nil {
return errors.Wrapf(err, "Could not get absolute path for '%s'", startDir)
}
if !l.context.IsDir(startDir) {
return fmt.Errorf("Argument '%s' is not a directory", startDir)
}
l.StartDir = startDir
l.Log.Verbosef("Loader.LoadDirectory: reading dir '%s'\n", l.StartDir)
l.le.readDir(l, l.StartDir)
return nil
}
func (l *Loader) isAllowed(absPath string) bool {
for _, g := range l.filteredPaths {
if g.Match(absPath) {
// We are looking at a filtered out path.
return false
}
}
return true
}
// isUnsafe returns whether the provided package represents the `unsafe`
// package for the loader context
func (l *Loader) isUnsafe(dp *DistinctPackage) bool {
return l.unsafePath == dp.Package.AbsPath
}
func (l *Loader) Signal() {
l.c.Broadcast()
}
// Wait blocks until all packages have been loaded
func (l *Loader) Wait() {
if l.areAllPackagesComplete() {
return
}
l.c.L.Lock()
l.c.Wait()
l.c.L.Unlock()
}
// String is the implementation of fmt.Stringer
func (l *Loader) String() string {
return fmt.Sprintf("%s %s", l.StartDir, l.GetTags())
}
// HandleTypeCheckerError is invoked from the types.Checker when it encounters
// errors
func (l *Loader) HandleTypeCheckerError(e error) {
if terror, ok := e.(types.Error); ok {
position := terror.Fset.Position(terror.Pos)
absPath := filepath.Dir(position.Filename)
dp, err := l.FindDistinctPackage(absPath)
if err != nil {
l.Log.Debugf("ERROR: (missing) No package for %s\n\t%s\n", absPath, err.Error())
return
}
baseFilename := filepath.Base(position.Filename)
ferr := FileError{
Position: position,
Message: terror.Msg,
Warning: terror.Soft,
}
f, ok := dp.files[baseFilename]
if !ok {
l.Log.Debugf("ERROR: (missing file) %s\n", position.Filename)
} else {
f.errs = append(f.errs, ferr)
l.Log.Debugf("ERROR: (types error) %s\n", terror.Error())
}
} else {
l.Log.Debugf("ERROR: (unknown) %#v\n", e)
}
}
func (l *Loader) findImportPath(path, src string) (string, error) {
buildPkg, err := l.context.Import(path, src, build.FindOnly)
if err != nil {
msg := fmt.Sprintf("Failed to find import path:\n\tAttempted build.Import('%s', '%s', build.FindOnly)", path, src)
return "", errors.Wrap(err, msg)
}
return buildPkg.Dir, nil
}