mirror of
https://github.com/golang/go
synced 2024-11-18 22:14:56 -07:00
d0600fd9f1
I realized this was a mistake, we should try to keep the source directory independent of the LSP protocol itself, and adapt in the outer layer. This will keep us honest about capabilities, let us add the caching and conversion layers easily, and also allow for a future where we expose the source directory as a supported API for other tools. The outer lsp package then becomes the adapter from the core features to the specifics of the LSP protocol. Change-Id: I68fd089f1b9f2fd38decc1cbc13c6f0f86157b94 Reviewed-on: https://go-review.googlesource.com/c/148157 Reviewed-by: Rebecca Stambler <rstambler@golang.org>
83 lines
1.6 KiB
Go
83 lines
1.6 KiB
Go
// 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.
|
|
|
|
package source
|
|
|
|
import (
|
|
"fmt"
|
|
"go/token"
|
|
"sync"
|
|
|
|
"golang.org/x/tools/go/packages"
|
|
)
|
|
|
|
type View struct {
|
|
mu sync.Mutex // protects all mutable state of the view
|
|
|
|
Config *packages.Config
|
|
|
|
files map[URI]*File
|
|
}
|
|
|
|
func NewView() *View {
|
|
return &View{
|
|
Config: &packages.Config{
|
|
Mode: packages.LoadSyntax,
|
|
Fset: token.NewFileSet(),
|
|
Tests: true,
|
|
Overlay: make(map[string][]byte),
|
|
},
|
|
files: make(map[URI]*File),
|
|
}
|
|
}
|
|
|
|
// 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 URI) *File {
|
|
v.mu.Lock()
|
|
f := v.getFile(uri)
|
|
v.mu.Unlock()
|
|
return f
|
|
}
|
|
|
|
// getFile is the unlocked internal implementation of GetFile.
|
|
func (v *View) getFile(uri URI) *File {
|
|
f, found := v.files[uri]
|
|
if !found {
|
|
f = &File{
|
|
URI: uri,
|
|
view: v,
|
|
}
|
|
v.files[f.URI] = f
|
|
}
|
|
return f
|
|
}
|
|
|
|
func (v *View) parse(uri URI) error {
|
|
path, err := uri.Filename()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pkgs, err := packages.Load(v.Config, fmt.Sprintf("file=%s", path))
|
|
if len(pkgs) == 0 {
|
|
if err == nil {
|
|
err = fmt.Errorf("no packages found for %s", path)
|
|
}
|
|
return err
|
|
}
|
|
for _, pkg := range pkgs {
|
|
// add everything we find to the files cache
|
|
for _, fAST := range pkg.Syntax {
|
|
// if a file was in multiple packages, which token/ast/pkg do we store
|
|
fToken := v.Config.Fset.File(fAST.Pos())
|
|
fURI := ToURI(fToken.Name())
|
|
f := v.getFile(fURI)
|
|
f.token = fToken
|
|
f.ast = fAST
|
|
f.pkg = pkg
|
|
}
|
|
}
|
|
return nil
|
|
}
|