2018-11-05 12:48:08 -07:00
|
|
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2018-11-02 14:15:31 -06:00
|
|
|
package source
|
2018-09-27 16:15:45 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2018-10-19 14:03:29 -06:00
|
|
|
"go/token"
|
2018-09-27 16:15:45 -06:00
|
|
|
"sync"
|
|
|
|
|
2018-10-19 14:03:29 -06:00
|
|
|
"golang.org/x/tools/go/packages"
|
2018-09-27 16:15:45 -06:00
|
|
|
"golang.org/x/tools/internal/lsp/protocol"
|
|
|
|
)
|
|
|
|
|
2018-11-02 14:15:31 -06:00
|
|
|
type View struct {
|
2018-11-02 16:10:49 -06:00
|
|
|
mu sync.Mutex // protects all mutable state of the view
|
2018-11-02 14:15:31 -06:00
|
|
|
|
2018-11-02 16:10:49 -06:00
|
|
|
Config *packages.Config
|
2018-10-19 14:03:29 -06:00
|
|
|
|
2018-11-02 16:10:49 -06:00
|
|
|
files map[protocol.DocumentURI]*File
|
2018-09-27 16:15:45 -06:00
|
|
|
}
|
|
|
|
|
2018-11-02 14:15:31 -06:00
|
|
|
func NewView() *View {
|
|
|
|
return &View{
|
|
|
|
Config: &packages.Config{
|
2018-10-29 16:12:41 -06:00
|
|
|
Mode: packages.LoadSyntax,
|
2018-11-02 16:10:49 -06:00
|
|
|
Fset: token.NewFileSet(),
|
2018-10-29 16:12:41 -06:00
|
|
|
Tests: true,
|
|
|
|
},
|
2018-11-02 16:10:49 -06:00
|
|
|
files: make(map[protocol.DocumentURI]*File),
|
2018-09-27 16:15:45 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-02 16:10:49 -06:00
|
|
|
// GetFile returns a File for the given uri.
|
|
|
|
// It will always succeed, adding the file to the managed set if needed.
|
|
|
|
func (v *View) GetFile(uri protocol.DocumentURI) *File {
|
|
|
|
v.mu.Lock()
|
|
|
|
f, found := v.files[uri]
|
|
|
|
if !found {
|
|
|
|
f := &File{URI: uri}
|
|
|
|
v.files[f.URI] = f
|
2018-10-19 14:03:29 -06:00
|
|
|
}
|
2018-11-02 16:10:49 -06:00
|
|
|
v.mu.Unlock()
|
|
|
|
return f
|
2018-09-27 16:15:45 -06:00
|
|
|
}
|
2018-10-19 14:03:29 -06:00
|
|
|
|
2018-11-02 14:15:31 -06:00
|
|
|
// TypeCheck type-checks the package for the given package path.
|
|
|
|
func (v *View) TypeCheck(uri protocol.DocumentURI) (*packages.Package, error) {
|
2018-11-02 16:10:49 -06:00
|
|
|
v.mu.Lock()
|
|
|
|
defer v.mu.Unlock()
|
2018-11-02 14:15:31 -06:00
|
|
|
path, err := FromURI(uri)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
pkgs, err := packages.Load(v.Config, fmt.Sprintf("file=%s", path))
|
2018-10-19 14:03:29 -06:00
|
|
|
if len(pkgs) == 0 {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
pkg := pkgs[0]
|
|
|
|
return pkg, nil
|
|
|
|
}
|