1
0
mirror of https://github.com/golang/go synced 2024-11-19 03:24:40 -07:00
go/internal/lsp/source/highlight.go
Rebecca Stambler b667c4c58e internal/lsp: cache the *ast.File and *token.File on the package
This change removes the need for the ast and token fields on the *goFile
object. We switch to using source.ParseGoHandles on the package, which
means that we can easily access both the AST and token via the package,
which is already cached.

Change-Id: I5f78bbe09362f4d95eb15556617bdbd809a7a55d
Reviewed-on: https://go-review.googlesource.com/c/tools/+/185878
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-07-16 19:44:59 +00:00

49 lines
1.2 KiB
Go

// Copyright 2019 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 (
"context"
"fmt"
"go/ast"
"go/token"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/internal/lsp/telemetry/trace"
"golang.org/x/tools/internal/span"
)
func Highlight(ctx context.Context, f GoFile, pos token.Pos) ([]span.Span, error) {
ctx, done := trace.StartSpan(ctx, "source.Highlight")
defer done()
file, err := f.GetAST(ctx, ParseFull)
if file == nil {
return nil, err
}
fset := f.FileSet()
path, _ := astutil.PathEnclosingInterval(file, pos, pos)
if len(path) == 0 {
return nil, fmt.Errorf("no enclosing position found for %s", fset.Position(pos))
}
id, ok := path[0].(*ast.Ident)
if !ok {
return nil, fmt.Errorf("%s is not an identifier", fset.Position(pos))
}
var result []span.Span
if id.Obj != nil {
ast.Inspect(path[len(path)-1], func(n ast.Node) bool {
if n, ok := n.(*ast.Ident); ok && n.Obj == id.Obj {
s, err := nodeSpan(n, fset)
if err == nil {
result = append(result, s)
}
}
return true
})
}
return result, nil
}