/
config.go
97 lines (77 loc) · 2.07 KB
/
config.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cliutil
import (
"fmt"
"go/types"
"golang.org/x/tools/go/packages"
)
// Config has configurations of static analysis.
type Config struct {
Packages *packages.Config
}
// TypeOf returns the value of types.Type which represented by the name.
// If any type could not be found, TypeOf returns [ErrNotFound] as the second return value.
func (conf *Config) TypeOf(name string) (types.Type, error) {
first, second, _, ptr := Split(name)
if second == "" {
obj := types.Universe.Lookup(first)
if obj == nil {
return nil, fmt.Errorf("%s: %w", name, ErrNotFound)
}
typ := obj.Type()
if ptr {
typ = types.NewPointer(typ)
}
return typ, nil
}
pkg, err := conf.load(first)
if err != nil {
return nil, fmt.Errorf("load %s: %w", first, err)
}
obj := pkg.Scope().Lookup(second)
if obj == nil {
return nil, fmt.Errorf("%s: %w", name, ErrNotFound)
}
typ := obj.Type()
if ptr {
typ = types.NewPointer(typ)
}
return typ, nil
}
// ObjectOf returns the value of types.Object which represented by the name.
// If any object could not be found, ObjectOf returns [ErrNotFound] as the second return value.
func (conf *Config) ObjectOf(name string) (types.Object, error) {
first, second, third, ptr := Split(name)
if second == "" {
obj := types.Universe.Lookup(name)
if obj == nil {
return nil, fmt.Errorf("%s: %w", name, ErrNotFound)
}
return obj, nil
}
if third == "" && ptr {
return nil, fmt.Errorf("%s: %w", name, ErrNotFound)
}
pkg, err := conf.load(first)
if err != nil {
return nil, fmt.Errorf("load %s: %w", first, err)
}
obj := pkg.Scope().Lookup(second)
if obj == nil {
return nil, fmt.Errorf("%s: %w", name, ErrNotFound)
}
if third == "" {
return obj, nil
}
fieldOrMethod, _, _ := types.LookupFieldOrMethod(obj.Type(), ptr, pkg, third)
if fieldOrMethod == nil {
return nil, fmt.Errorf("%s: %w", name, ErrNotFound)
}
return fieldOrMethod, nil
}
func (conf *Config) load(name string) (*types.Package, error) {
pkgs, err := packages.Load(conf.Packages, name)
if err != nil {
return nil, err
}
return pkgs[0].Types, nil
}