forked from open-policy-agent/opa
/
compilehelper.go
60 lines (47 loc) · 1.84 KB
/
compilehelper.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
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package ast
// CompileModules takes a set of Rego modules represented as strings and
// compiles them for evaluation. The keys of the map are used as filenames.
func CompileModules(modules map[string]string) (*Compiler, error) {
return CompileModulesWithOpt(modules, CompileOpts{})
}
// CompileOpts defines a set of options for the compiler.
type CompileOpts struct {
EnablePrintStatements bool
ParserOptions ParserOptions
}
// CompileModulesWithOpt takes a set of Rego modules represented as strings and
// compiles them for evaluation. The keys of the map are used as filenames.
func CompileModulesWithOpt(modules map[string]string, opts CompileOpts) (*Compiler, error) {
parsed := make(map[string]*Module, len(modules))
for f, module := range modules {
var pm *Module
var err error
if pm, err = ParseModuleWithOpts(f, module, opts.ParserOptions); err != nil {
return nil, err
}
parsed[f] = pm
}
compiler := NewCompiler().WithEnablePrintStatements(opts.EnablePrintStatements)
compiler.Compile(parsed)
if compiler.Failed() {
return nil, compiler.Errors
}
return compiler, nil
}
// MustCompileModules compiles a set of Rego modules represented as strings. If
// the compilation process fails, this function panics.
func MustCompileModules(modules map[string]string) *Compiler {
return MustCompileModulesWithOpts(modules, CompileOpts{})
}
// MustCompileModulesWithOpts compiles a set of Rego modules represented as strings. If
// the compilation process fails, this function panics.
func MustCompileModulesWithOpts(modules map[string]string, opts CompileOpts) *Compiler {
compiler, err := CompileModulesWithOpt(modules, opts)
if err != nil {
panic(err)
}
return compiler
}