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"
|
|
|
|
"go/ast"
|
|
|
|
"go/token"
|
|
|
|
|
|
|
|
"golang.org/x/tools/go/ast/astutil"
|
|
|
|
"golang.org/x/tools/internal/span"
|
2019-08-13 13:07:39 -06:00
|
|
|
"golang.org/x/tools/internal/telemetry/trace"
|
2019-08-06 13:13:11 -06:00
|
|
|
errors "golang.org/x/xerrors"
|
2019-03-25 18:56:05 -06:00
|
|
|
)
|
|
|
|
|
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-07-11 19:05:55 -06:00
|
|
|
|
|
|
|
file, err := f.GetAST(ctx, ParseFull)
|
2019-05-20 13:23:02 -06:00
|
|
|
if file == nil {
|
2019-07-11 19:05:55 -06:00
|
|
|
return nil, err
|
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-08-06 13:13:11 -06:00
|
|
|
return nil, errors.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-08-06 13:13:11 -06:00
|
|
|
return nil, errors.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
|
|
|
}
|