forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oracle.go
231 lines (192 loc) · 5.66 KB
/
oracle.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package oracle
import (
"errors"
"github.com/meta-quick/opax/ast"
)
// Error defines the structure of errors returned by the oracle.
type Error struct {
Code string `json:"code"`
}
func (e Error) Error() string {
return e.Code
}
// Oracle implements different queries over ASTs, e.g., find definition.
type Oracle struct {
}
// New returns a new Oracle object.
func New() *Oracle {
return &Oracle{}
}
// DefinitionQuery defines a Rego definition query.
type DefinitionQuery struct {
Filename string // name of file to search for position inside of
Pos int // position to search for
Modules map[string]*ast.Module // workspace modules; buffer may shadow a file inside the workspace
Buffer []byte // buffer that overrides module with filename
}
var (
// ErrNoDefinitionFound indicates the position was valid but no matching definition was found.
ErrNoDefinitionFound = Error{Code: "oracle_no_definition_found"}
// ErrNoMatchFound indicates the position was invalid.
ErrNoMatchFound = Error{Code: "oracle_no_match_found"}
)
// DefinitionQueryResult defines output of a definition query.
type DefinitionQueryResult struct {
Result *ast.Location `json:"result"`
}
// FindDefinition returns the location of the definition referred to by the symbol
// at the position in q.
func (o *Oracle) FindDefinition(q DefinitionQuery) (*DefinitionQueryResult, error) {
// TODO(tsandall): how can we cache the results of compilation and parsing so that
// multiple queries can be executed without having to re-compute the same values?
// Ditto for caching across runs. Avoid repeating the same work.
compiler, parsed, err := compileUpto("SetRuleTree", q.Modules, q.Buffer, q.Filename)
if err != nil {
return nil, err
}
mod, ok := compiler.Modules[q.Filename]
if !ok {
return nil, ErrNoMatchFound
}
stack := findContainingNodeStack(mod, q.Pos)
if len(stack) == 0 {
return nil, ErrNoMatchFound
}
// Walk outwards from the match location, attempting to find the definition via
// references to imports or other rules. This handles intra-module, intra-package,
// and inter-package references.
for i := len(stack) - 1; i >= 0; i-- {
if term, ok := stack[i].(*ast.Term); ok {
if ref, ok := term.Value.(ast.Ref); ok {
prefix := ref.ConstantPrefix()
if rules := compiler.GetRulesExact(prefix); len(rules) > 0 {
return &DefinitionQueryResult{rules[0].Location}, nil
}
for _, imp := range parsed.Imports {
if path, ok := imp.Path.Value.(ast.Ref); ok {
if prefix.HasPrefix(path) {
return &DefinitionQueryResult{imp.Path.Location}, nil
}
}
}
}
}
}
// If the match is a variable, walk inward to find the first occurrence of the variable
// in function arguments or the body.
top := stack[len(stack)-1]
if term, ok := top.(*ast.Term); ok {
if name, ok := term.Value.(ast.Var); ok {
for i := 0; i < len(stack); i++ {
switch node := stack[i].(type) {
case *ast.Rule:
if match := walkToFirstOccurrence(node.Head.Args, name); match != nil {
return &DefinitionQueryResult{match.Location}, nil
}
case ast.Body:
if match := walkToFirstOccurrence(node, name); match != nil {
return &DefinitionQueryResult{match.Location}, nil
}
}
}
}
}
return nil, ErrNoDefinitionFound
}
func walkToFirstOccurrence(node ast.Node, needle ast.Var) (match *ast.Term) {
ast.WalkNodes(node, func(x ast.Node) bool {
if match == nil {
switch x := x.(type) {
case *ast.SomeDecl:
// NOTE(tsandall): The visitor doesn't traverse into some decl terms
// so special case here.
for i := range x.Symbols {
if x.Symbols[i].Value.Compare(needle) == 0 {
match = x.Symbols[i]
break
}
}
case *ast.Term:
if x.Value.Compare(needle) == 0 {
match = x
}
}
}
return match != nil
})
return match
}
func compileUpto(stage string, modules map[string]*ast.Module, bs []byte, filename string) (*ast.Compiler, *ast.Module, error) {
compiler := ast.NewCompiler()
if stage != "" {
compiler = compiler.WithStageAfter(stage, ast.CompilerStageDefinition{
Name: "halt",
Stage: func(c *ast.Compiler) *ast.Error {
return &ast.Error{
Code: "halt",
}
},
})
}
var module *ast.Module
if len(bs) > 0 {
var err error
module, err = ast.ParseModule(filename, string(bs))
if err != nil {
return nil, nil, err
}
} else {
module = modules[filename]
}
if modules == nil {
modules = map[string]*ast.Module{}
}
if len(bs) > 0 {
modules[filename] = module
}
compiler.Compile(modules)
if stage != "" {
if err := halted(compiler); err != nil {
return nil, nil, err
}
}
return compiler, module, nil
}
func halted(c *ast.Compiler) error {
if c.Failed() && len(c.Errors) == 1 && c.Errors[0].Code == "halt" {
return nil
} else if len(c.Errors) > 0 {
return c.Errors
}
// NOTE(tsandall): this indicate an internal error in the compiler and should
// not be reachable.
return errors.New("unreachable: did not halt")
}
func findContainingNodeStack(module *ast.Module, pos int) []ast.Node {
var matches []ast.Node
ast.WalkNodes(module, func(x ast.Node) bool {
min, max := getLocMinMax(x)
if pos < min || pos >= max {
return true
}
matches = append(matches, x)
return false
})
return matches
}
func getLocMinMax(x ast.Node) (int, int) {
if x.Loc() == nil {
return -1, -1
}
loc := x.Loc()
min := loc.Offset
// Special case bodies because location text is only for the first expr.
if body, ok := x.(ast.Body); ok {
extraLoc := body[len(body)-1].Loc()
if extraLoc == nil {
return -1, -1
}
return min, extraLoc.Offset + len(extraLoc.Text)
}
return min, min + len(loc.Text)
}