forked from lukehoban/ident
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlookup.go
54 lines (45 loc) · 1.18 KB
/
lookup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package ident
import (
"errors"
"github.com/rogpeppe/godef/go/ast"
"github.com/rogpeppe/godef/go/parser"
"github.com/rogpeppe/godef/go/types"
)
func lookup(filepath string, offset int) (Definition, error) {
def := Definition{}
f, err := parser.ParseFile(fileset, filepath, nil, 0, getScope(filepath))
if err != nil {
return def, err
}
containsOffset := func(node ast.Node) bool {
from := fileset.Position(node.Pos()).Offset
to := fileset.Position(node.End()).Offset
return offset >= from && offset < to
}
// traverse the ast tree until we find a node at the given offset position
var ident ast.Expr
ast.Inspect(f, func(node ast.Node) bool {
switch expr := node.(type) {
case *ast.SelectorExpr:
if containsOffset(expr) && containsOffset(expr.Sel) {
ident = expr
}
case *ast.Ident:
if containsOffset(expr) {
ident = expr
}
}
return ident == nil
})
if ident == nil {
return def, errors.New("no identifier found")
}
pos := getDefPosition(ident)
if pos == nil {
return def, errors.New("could not find definition of identifier")
}
obj, _ := types.ExprType(ident, types.DefaultImporter)
def.Name = obj.Name
def.Position = *pos
return def, nil
}