github.com/rajeev159/opa@v0.45.0/ast/compilehelper.go (about)

     1  // Copyright 2016 The OPA Authors.  All rights reserved.
     2  // Use of this source code is governed by an Apache2
     3  // license that can be found in the LICENSE file.
     4  
     5  package ast
     6  
     7  // CompileModules takes a set of Rego modules represented as strings and
     8  // compiles them for evaluation. The keys of the map are used as filenames.
     9  func CompileModules(modules map[string]string) (*Compiler, error) {
    10  	return CompileModulesWithOpt(modules, CompileOpts{})
    11  }
    12  
    13  // CompileOpts defines a set of options for the compiler.
    14  type CompileOpts struct {
    15  	EnablePrintStatements bool
    16  	ParserOptions         ParserOptions
    17  }
    18  
    19  // CompileModulesWithOpt takes a set of Rego modules represented as strings and
    20  // compiles them for evaluation. The keys of the map are used as filenames.
    21  func CompileModulesWithOpt(modules map[string]string, opts CompileOpts) (*Compiler, error) {
    22  
    23  	parsed := make(map[string]*Module, len(modules))
    24  
    25  	for f, module := range modules {
    26  		var pm *Module
    27  		var err error
    28  		if pm, err = ParseModuleWithOpts(f, module, opts.ParserOptions); err != nil {
    29  			return nil, err
    30  		}
    31  		parsed[f] = pm
    32  	}
    33  
    34  	compiler := NewCompiler().WithEnablePrintStatements(opts.EnablePrintStatements)
    35  	compiler.Compile(parsed)
    36  
    37  	if compiler.Failed() {
    38  		return nil, compiler.Errors
    39  	}
    40  
    41  	return compiler, nil
    42  }
    43  
    44  // MustCompileModules compiles a set of Rego modules represented as strings. If
    45  // the compilation process fails, this function panics.
    46  func MustCompileModules(modules map[string]string) *Compiler {
    47  	return MustCompileModulesWithOpts(modules, CompileOpts{})
    48  }
    49  
    50  // MustCompileModulesWithOpts compiles a set of Rego modules represented as strings. If
    51  // the compilation process fails, this function panics.
    52  func MustCompileModulesWithOpts(modules map[string]string, opts CompileOpts) *Compiler {
    53  
    54  	compiler, err := CompileModulesWithOpt(modules, opts)
    55  	if err != nil {
    56  		panic(err)
    57  	}
    58  
    59  	return compiler
    60  }