2019-03-25 18:56:05 -06:00
|
|
|
// 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"
|
2019-06-21 15:00:02 -06:00
|
|
|
"fmt"
|
2019-03-25 18:56:05 -06:00
|
|
|
"go/ast"
|
|
|
|
"go/token"
|
|
|
|
|
|
|
|
"golang.org/x/tools/go/ast/astutil"
|
2019-06-21 14:28:23 -06:00
|
|
|
"golang.org/x/tools/internal/lsp/telemetry/trace"
|
2019-03-25 18:56:05 -06:00
|
|
|
"golang.org/x/tools/internal/span"
|
|
|
|
)
|
|
|
|
|
2019-06-21 15:00:02 -06:00
|
|
|
func Highlight(ctx context.Context, f GoFile, pos token.Pos) ([]span.Span, error) {
|
2019-06-26 20:46:12 -06:00
|
|
|
ctx, done := trace.StartSpan(ctx, "source.Highlight")
|
|
|
|
defer done()
|
2019-05-20 13:23:02 -06:00
|
|
|
file := f.GetAST(ctx)
|
|
|
|
if file == nil {
|
2019-06-21 15:00:02 -06:00
|
|
|
return nil, fmt.Errorf("no AST for %s", f.URI())
|
2019-05-20 13:23:02 -06:00
|
|
|
}
|
2019-05-17 08:51:19 -06:00
|
|
|
fset := f.FileSet()
|
2019-05-20 13:23:02 -06:00
|
|
|
path, _ := astutil.PathEnclosingInterval(file, pos, pos)
|
2019-03-25 18:56:05 -06:00
|
|
|
if len(path) == 0 {
|
2019-06-21 15:00:02 -06:00
|
|
|
return nil, fmt.Errorf("no enclosing position found for %s", fset.Position(pos))
|
2019-03-25 18:56:05 -06:00
|
|
|
}
|
|
|
|
id, ok := path[0].(*ast.Ident)
|
|
|
|
if !ok {
|
2019-06-21 15:00:02 -06:00
|
|
|
return nil, fmt.Errorf("%s is not an identifier", fset.Position(pos))
|
2019-03-25 18:56:05 -06:00
|
|
|
}
|
|
|
|
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
|
|
|
|
})
|
|
|
|
}
|
2019-06-21 15:00:02 -06:00
|
|
|
return result, nil
|
2019-03-25 18:56:05 -06:00
|
|
|
}
|