package ast
import "github.com/open-policy-agent/opa/ast"
Package ast declares Rego syntax tree types and also includes a parser and compiler for preparing policies for execution in the policy engine.
Rego policies are defined using a relatively small set of types: modules, package and import declarations, rules, expressions, and terms. At their core, policies consist of rules that are defined by one or more expressions over documents available to the policy engine. The expressions are defined by intrinsic values (terms) such as strings, objects, variables, etc.
Rego policies are typically defined in text files and then parsed and compiled by the policy engine at runtime. The parsing stage takes the text or string representation of the policy and converts it into an abstract syntax tree (AST) that consists of the types mentioned above. The AST is organized as follows:
Module | +--- Package (Reference) | +--- Imports | | | +--- Import (Term) | +--- Rules | +--- Rule | +--- Head | | | +--- Name (Variable) | | | +--- Key (Term) | | | +--- Value (Term) | +--- Body | +--- Expression (Term | Terms)
At query time, the policy engine expects policies to have been compiled. The compilation stage takes one or more modules and compiles them into a format that the policy engine supports.
Index ¶
- Constants
- Variables
- func Compare(a, b interface{}) int
- func CompileModule(m string) (*Compiler, *Module, error)
- func CompileQuery(q string) (*Compiler, Body, error)
- func IsScalar(v Value) bool
- func MustParseStatement(input string) interface{}
- func MustParseStatements(input string) []interface{}
- func Parse(filename string, b []byte, opts ...Option) (interface{}, error)
- func ParseFile(filename string, opts ...Option) (interface{}, error)
- func ParseReader(filename string, r io.Reader, opts ...Option) (interface{}, error)
- func ParseStatement(input string) (interface{}, error)
- func ParseStatements(filename, input string) ([]interface{}, error)
- func RegisterBuiltin(b *Builtin)
- func Transform(t Transformer, x interface{}) (interface{}, error)
- func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error)
- func Walk(v Visitor, x interface{})
- func WalkBodies(x interface{}, f func(Body) bool)
- func WalkClosures(x interface{}, f func(interface{}) bool)
- func WalkRefs(x interface{}, f func(Ref) bool)
- type Array
- func (arr Array) Equal(other Value) bool
- func (arr Array) Hash() int
- func (arr Array) IsGround() bool
- func (arr Array) String() string
- type ArrayComprehension
- func (ac *ArrayComprehension) Equal(other Value) bool
- func (ac *ArrayComprehension) Hash() int
- func (ac *ArrayComprehension) IsGround() bool
- func (ac *ArrayComprehension) String() string
- type Body
- func MustParseBody(input string) Body
- func NewBody(exprs ...*Expr) Body
- func ParseBody(input string) (Body, error)
- func (body Body) Compare(other Body) int
- func (body Body) Contains(x *Expr) bool
- func (body Body) Equal(other Body) bool
- func (body Body) Hash() int
- func (body Body) IsGround() bool
- func (body Body) Loc() *Location
- func (body Body) OutputVars(safe VarSet) VarSet
- func (body Body) String() string
- func (body Body) Vars(skipClosures bool) VarSet
- type Boolean
- func (bol Boolean) Equal(other Value) bool
- func (bol Boolean) Hash() int
- func (bol Boolean) IsGround() bool
- func (bol Boolean) String() string
- type Builtin
- type Compiler
- func NewCompiler() *Compiler
- func (c *Compiler) Compile(modules map[string]*Module)
- func (c *Compiler) Failed() bool
- func (c *Compiler) GetRulesExact(ref Ref) (rules []*Rule)
- func (c *Compiler) GetRulesForVirtualDocument(ref Ref) (rules []*Rule)
- func (c *Compiler) GetRulesWithPrefix(ref Ref) (rules []*Rule)
- type DocKind
- type ErrCode
- type Error
- func NewError(code int, loc *Location, f string, a ...interface{}) *Error
- func (e *Error) Error() string
- type Errors
- type Expr
- func MustParseExpr(input string) *Expr
- func NewBuiltinExpr(terms ...*Term) *Expr
- func ParseExpr(input string) (*Expr, error)
- func (expr *Expr) Compare(other *Expr) int
- func (expr *Expr) Complement() *Expr
- func (expr *Expr) Equal(other *Expr) bool
- func (expr *Expr) Hash() int
- func (expr *Expr) IsEquality() bool
- func (expr *Expr) IsGround() bool
- func (expr *Expr) OutputVars(safe VarSet) VarSet
- func (expr *Expr) String() string
- func (expr *Expr) UnmarshalJSON(bs []byte) error
- func (expr *Expr) Vars(skipClosures bool) VarSet
- type GenericTransformer
- type GenericVisitor
- type Head
- type Import
- func (imp *Import) Compare(other *Import) int
- func (imp *Import) Equal(other *Import) bool
- func (imp *Import) Loc() *Location
- func (imp *Import) String() string
- type Location
- func NewLocation(text []byte, file string, row int, col int) *Location
- func (loc *Location) Errorf(f string, a ...interface{}) error
- func (loc *Location) Format(f string, a ...interface{}) string
- func (loc *Location) Wrapf(err error, f string, a ...interface{}) error
- type Module
- func MustParseModule(input string) *Module
- func ParseModule(filename, input string) (*Module, error)
- func (mod *Module) Compare(other *Module) int
- func (mod *Module) Equal(other *Module) bool
- func (mod *Module) String() string
- type ModuleTreeNode
- type Null
- func (null Null) Equal(other Value) bool
- func (null Null) Hash() int
- func (null Null) IsGround() bool
- func (null Null) String() string
- type Number
- func (num Number) Equal(other Value) bool
- func (num Number) Hash() int
- func (num Number) IsGround() bool
- func (num Number) String() string
- type Object
- func (obj Object) Diff(other Object) Object
- func (obj Object) Equal(other Value) bool
- func (obj Object) Get(k *Term) *Term
- func (obj Object) Hash() int
- func (obj Object) Intersect(other Object) [][3]*Term
- func (obj Object) IsGround() bool
- func (obj Object) Keys() []*Term
- func (obj Object) Merge(other Object) (Object, bool)
- func (obj Object) String() string
- type Option
- type Package
- func (pkg *Package) Compare(other *Package) int
- func (pkg *Package) Equal(other *Package) bool
- func (pkg *Package) Loc() *Location
- func (pkg *Package) String() string
- type QueryIterator
- type Ref
- func EmptyRef() Ref
- func MustParseRef(input string) Ref
- func ParseRef(input string) (Ref, error)
- func (ref Ref) Append(term *Term) Ref
- func (ref Ref) Equal(other Value) bool
- func (ref Ref) GroundPrefix() Ref
- func (ref Ref) HasPrefix(other Ref) bool
- func (ref Ref) Hash() int
- func (ref Ref) IsGround() bool
- func (ref Ref) IsNested() bool
- func (ref Ref) OutputVars() VarSet
- func (ref Ref) String() string
- func (ref Ref) Underlying() ([]interface{}, error)
- type Rule
- func MustParseRule(input string) *Rule
- func ParseConstantRule(body Body) *Rule
- func ParseRule(input string) (*Rule, error)
- func (rule *Rule) Compare(other *Rule) int
- func (rule *Rule) DocKind() DocKind
- func (rule *Rule) Equal(other *Rule) bool
- func (rule *Rule) Head() *Head
- func (rule *Rule) HeadVars() VarSet
- func (rule *Rule) Loc() *Location
- func (rule *Rule) Path(ns Ref) Ref
- func (rule *Rule) String() string
- type RuleTreeNode
- type Set
- func (s *Set) Add(t *Term)
- func (s Set) Contains(t *Term) bool
- func (s *Set) Diff(other *Set) *Set
- func (s *Set) Equal(v Value) bool
- func (s *Set) Hash() int
- func (s *Set) IsGround() bool
- func (s *Set) Map(f func(*Term) (*Term, error)) (*Set, error)
- func (s *Set) String() string
- type Statement
- type String
- func (str String) Equal(other Value) bool
- func (str String) Hash() int
- func (str String) IsGround() bool
- func (str String) String() string
- type Term
- func ArrayComprehensionTerm(term *Term, body Body) *Term
- func ArrayTerm(a ...*Term) *Term
- func BooleanTerm(b bool) *Term
- func Item(key, value *Term) [2]*Term
- func MustParseTerm(input string) *Term
- func NullTerm() *Term
- func NumberTerm(n float64) *Term
- func ObjectTerm(o ...[2]*Term) *Term
- func ParseTerm(input string) (*Term, error)
- func RefTerm(r ...*Term) *Term
- func SetTerm(t ...*Term) *Term
- func StringTerm(s string) *Term
- func VarTerm(v string) *Term
- func (term *Term) Equal(other *Term) bool
- func (term *Term) Hash() int
- func (term *Term) IsGround() bool
- func (term *Term) MarshalJSON() ([]byte, error)
- func (term *Term) String() string
- func (term *Term) UnmarshalJSON(bs []byte) error
- func (term *Term) Vars() VarSet
- type Transformer
- type Value
- type ValueMap
- func NewValueMap() *ValueMap
- func (vs *ValueMap) Copy() *ValueMap
- func (vs *ValueMap) Delete(k Value)
- func (vs *ValueMap) Equal(other *ValueMap) bool
- func (vs *ValueMap) Get(k Value) Value
- func (vs *ValueMap) Hash() int
- func (vs *ValueMap) Iter(iter func(Value, Value) bool) bool
- func (vs *ValueMap) Len() int
- func (vs *ValueMap) Put(k, v Value)
- func (vs *ValueMap) String() string
- type Var
- func (v Var) Equal(other Value) bool
- func (v Var) Hash() int
- func (v Var) IsGround() bool
- func (v Var) IsWildcard() bool
- func (v Var) String() string
- type VarSet
- func NewVarSet(vs ...Var) VarSet
- func Unify(safe VarSet, a *Term, b *Term) VarSet
- func (s VarSet) Add(v Var)
- func (s VarSet) Contains(v Var) bool
- func (s VarSet) Copy() VarSet
- func (s VarSet) Diff(vs VarSet) VarSet
- func (s VarSet) Intersect(vs VarSet) VarSet
- func (s VarSet) String() string
- func (s VarSet) Update(vs VarSet)
- type Visitor
Examples ¶
Constants ¶
const ( // ParseErr indicates an unclassified parse error occurred. ParseErr = iota // CompileErr indicates an unclassified compile error occurred. CompileErr = iota // UnsafeVarErr indicates an unsafe variable was found during compilation. UnsafeVarErr = iota // RecursionErr indicates recursion was found during compilation. RecursionErr = iota )
const ( // CompleteDoc represents a document that is completely defined by the rule. CompleteDoc = iota // PartialSetDoc represents a set document that is partially defined by the rule. PartialSetDoc = iota // PartialObjectDoc represents an object document that is partially defined by the rule. PartialObjectDoc = iota )
Variables ¶
Abs returns the number without its sign.
BuiltinMap provides a convenient mapping of built-in names to built-in definitions.
var Builtins []*Builtin
Builtins is the registry of built-in functions supported by OPA. Call RegisterBuiltin to add a new built-in.
Concat joins an array of strings to with an input string.
Count takes a collection and counts the number of elements in it.
var DefaultBuiltins = [...]*Builtin{ Equality, GreaterThan, GreaterThanEq, LessThan, LessThanEq, NotEqual, Plus, Minus, Multiply, Divide, Round, Abs, Count, Sum, Max, ToNumber, RegexMatch, Concat, FormatInt, }
DefaultBuiltins is the registry of built-in functions supported in OPA by default. When adding a new built-in function to OPA, update this list.
var DefaultRootDocument = VarTerm("data")
DefaultRootDocument is the default root document. All package directives inside source files are implicitly prefixed with the DefaultRootDocument value.
Divide divides the first number by the second number.
Equality represents the "=" operator.
FormatInt returns the string representation of the number in the given base after converting it to an integer value.
GreaterThan represents the ">" comparison operator.
GreaterThanEq represents the ">=" comparison operator.
LessThan represents the "<" comparison operator.
LessThanEq represents the "<=" comparison operator.
Max returns the maximum value in a collection.
Minus subtracts the second number from the first number.
Multiply multiplies two numbers together.
NotEqual represents the "!=" comparison operator.
Plus adds two numbers together.
RegexMatch takes two strings and evaluates to true if the string in the second position matches the pattern in the first position.
var ReservedVars = NewVarSet(DefaultRootDocument.Value.(Var))
ReservedVars is the set of reserved variable names.
Round rounds the number up to the nearest integer.
Sum takes an array of numbers and sums them.
ToNumber takes a string, bool, or number value and converts it to a number. Strings are converted to numbers using strconv.Atoi. Boolean false is converted to 0 and boolean true is converted to 1.
Wildcard represents the wildcard variable as defined in the language.
var WildcardPrefix = "$"
WildcardPrefix is the special character that all wildcard variables are prefixed with when the statement they are contained in is parsed.
Functions ¶
func Compare ¶
func Compare(a, b interface{}) int
Compare returns an integer indicating whether two AST values are less than, equal to, or greater than each other.
If a is less than b, the return value is negative. If a is greater than b, the return value is positive. If a is equal to b, the return value is zero.
Different types are never equal to each other. For comparison purposes, types are sorted as follows:
nil < Null < Boolean < Number < String < Var < Ref < Array < Object < Set < ArrayComprehension < Expr < Body < Rule < Import < Package < Module.
Arrays and Refs are equal iff both a and b have the same length and all corresponding elements are equal. If one element is not equal, the return value is the same as for the first differing element. If all elements are equal but a and b have different lengths, the shorter is considered less than the other.
Objects are considered equal iff both a and b have the same sorted (key, value) pairs and are of the same length. Other comparisons are consistent but not defined.
Sets are considered equal iff the symmetric difference of a and b is empty. Other comparisons are consistent but not defined.
func CompileModule ¶
CompileModule is a helper function to compile a module represented as a string.
func CompileQuery ¶
CompileQuery is a helper function to compile a query represented as a string.
func IsScalar ¶
IsScalar returns true if the AST value is a scalar.
func MustParseStatement ¶
func MustParseStatement(input string) interface{}
MustParseStatement returns exactly one statement. If an error occurs during parsing, panic.
func MustParseStatements ¶
func MustParseStatements(input string) []interface{}
MustParseStatements returns a slice of parsed statements. If an error occurs during parsing, panic.
func Parse ¶
Parse parses the data from b using filename as information in the error messages.
func ParseFile ¶
ParseFile parses the file identified by filename.
func ParseReader ¶
ParseReader parses the data from r using filename as information in the error messages.
func ParseStatement ¶
ParseStatement returns exactly one statement. A statement might be a term, expression, rule, etc. Regardless, this function expects *exactly* one statement. If multiple statements are parsed, an error is returned.
func ParseStatements ¶
ParseStatements returns a slice of parsed statements. This is the default return value from the parser.
func RegisterBuiltin ¶
func RegisterBuiltin(b *Builtin)
RegisterBuiltin adds a new built-in function to the registry.
func Transform ¶
func Transform(t Transformer, x interface{}) (interface{}, error)
Transform iterates the AST and calls the Transform function on the Transformer t for x before recursing.
func TransformRefs ¶
TransformRefs calls the function f on all references under x.
func Walk ¶
func Walk(v Visitor, x interface{})
Walk iterates the AST by calling the Visit function on the Visitor v for x before recursing.
func WalkBodies ¶
WalkBodies calls the function f on all bodies under x. If the function f returns true, AST nodes under the last node will not be visited.
func WalkClosures ¶
func WalkClosures(x interface{}, f func(interface{}) bool)
WalkClosures calls the function f on all closures under x. If the function f returns true, AST nodes under the last node will not be visited.
func WalkRefs ¶
WalkRefs calls the function f on all references under x. If the function f returns true, AST nodes under the last node will not be visited.
Types ¶
type Array ¶
type Array []*Term
Array represents an array as defined by the language. Arrays are similar to the same types as defined by JSON with the exception that they can contain Vars and References.
func (Array) Equal ¶
Equal returns true if arr is equal to other.
func (Array) Hash ¶
Hash returns the hash code for the Value.
func (Array) IsGround ¶
IsGround returns true if all of the Array elements are ground.
func (Array) String ¶
type ArrayComprehension ¶
ArrayComprehension represents an array comprehension as defined in the language.
func (*ArrayComprehension) Equal ¶
func (ac *ArrayComprehension) Equal(other Value) bool
Equal returns true if ac is equal to other.
func (*ArrayComprehension) Hash ¶
func (ac *ArrayComprehension) Hash() int
Hash returns the hash code of the Value.
func (*ArrayComprehension) IsGround ¶
func (ac *ArrayComprehension) IsGround() bool
IsGround returns true if the Term and Body are ground.
func (*ArrayComprehension) String ¶
func (ac *ArrayComprehension) String() string
type Body ¶
type Body []*Expr
Body represents one or more expressios contained inside a rule.
func MustParseBody ¶
MustParseBody returns a parsed body. If an error occurs during parsing, panic.
func NewBody ¶
NewBody returns a new Body containing the given expressions. The indices of the immediate expressions will be reset.
func ParseBody ¶
ParseBody returns exactly one body. If multiple bodies are parsed, an error is returned.
func (Body) Compare ¶
Compare returns an integer indicating whether body is less than, equal to, or greater than other.
If body is a subset of other, it is considered less than (and vice versa).
func (Body) Contains ¶
Contains returns true if this body contains the given expression.
func (Body) Equal ¶
Equal returns true if this Body is equal to the other Body.
func (Body) Hash ¶
Hash returns the hash code for the Body.
func (Body) IsGround ¶
IsGround returns true if all of the expressions in the Body are ground.
func (Body) Loc ¶
Loc returns the location of the Body in the definition.
func (Body) OutputVars ¶
OutputVars returns a VarSet containing the variables that would be bound by evaluating the body.
func (Body) String ¶
func (Body) Vars ¶
Vars returns a VarSet containing all of the variables in the body. If skipClosures is true, variables contained inside closures within the body will be ignored.
type Boolean ¶
type Boolean bool
Boolean represents a boolean value defined by JSON.
func (Boolean) Equal ¶
Equal returns true if the other Value is a Boolean and is equal.
func (Boolean) Hash ¶
Hash returns the hash code for the Value.
func (Boolean) IsGround ¶
IsGround always returns true.
func (Boolean) String ¶
type Builtin ¶
type Builtin struct { Name Var // Unique name of built-in function, e.g., <Name>(term,term,...,term) Infix Var // Unique name of infix operator. Default should be unset. NumArgs int // Total number of args required by built-in. TargetPos []int // Argument positions that bind outputs. Indexing is zero-based. }
Builtin represents a built-in function supported by OPA. Every built-in function is uniquely identified by a name.
func (*Builtin) Expr ¶
Expr creates a new expression for the built-in with the given terms.
func (*Builtin) IsTargetPos ¶
IsTargetPos returns true if a variable in the i-th position will be bound when the expression is evaluated.
type Compiler ¶
type Compiler struct { // Errors contains errors that occurred during the compilation process. // If there are one or more errors, the compilation process is considered // "failed". Errors Errors // Modules contains the compiled modules. The compiled modules are the // output of the compilation process. If the compilation process failed, // there is no guarantee about the state of the modules. Modules map[string]*Module // ModuleTree organizes the modules into a tree where each node is keyed // by an element in the module's package path. E.g., given modules containg // the following package directives: "a", "a.b", "a.c", and "a.b", the // resulting module tree would be: // // root // | // +--- data (no modules) // | // +--- a (1 module) // | // +--- b (2 modules) // | // +--- c (1 module) // ModuleTree *ModuleTreeNode // RuleTree organizes rules into a tree where each node is keyed by an // element in the rule's path. The rule path is the concatenation of the // containing package and the stringified rule name. E.g., given the following module: // // package ex // p[1] :- true // p[2] :- true // q :- true // // root // | // +--- data (no rules) // | // +--- ex (no rules) // | // +--- p (2 rules) // | // +--- q (1 rule) RuleTree *RuleTreeNode // RuleGraph represents the rule dependencies. // An edge (u, v) is added to the graph if rule "u" depends on rule "v". // A rule depends on another rule if it refers to it. RuleGraph map[*Rule]map[*Rule]struct{} // contains filtered or unexported fields }
Compiler contains the state of a compilation process.
func NewCompiler ¶
func NewCompiler() *Compiler
NewCompiler returns a new empty compiler.
func (*Compiler) Compile ¶
Compile runs the compilation process on the input modules. The compiled
version of the modules and associated data structures are stored on the
compiler. If the compilation process fails for any reason, the compiler will
contain a slice of errors.
Code:play
Output:Example¶
package main
import (
"fmt"
"github.com/open-policy-agent/opa/ast"
)
func main() {
// Define an input module that will be compiled.
exampleModule := `
package opa.example
import data.foo
import bar
p[x] :- foo[x], not bar[x], x < min_x
min_x = 100
`
// Parse the input module to obtain the AST representation.
mod, err := ast.ParseModule("my_module", exampleModule)
if err != nil {
fmt.Println("Parse error:", err)
}
// Create a new compiler instance and compile the module.
c := ast.NewCompiler()
mods := map[string]*ast.Module{
"my_module": mod,
}
if c.Compile(mods); c.Failed() {
fmt.Println("Compile error:", c.Errors)
}
fmt.Println("Expr 1:", mod.Rules[0].Body[0])
fmt.Println("Expr 2:", mod.Rules[0].Body[1])
fmt.Println("Expr 3:", mod.Rules[0].Body[2])
}
Expr 1: data.foo[x]
Expr 2: not bar[x]
Expr 3: lt(x, data.opa.example.min_x)
func (*Compiler) Failed ¶
Failed returns true if a compilation error has been encountered.
func (*Compiler) GetRulesExact ¶
GetRulesExact returns a slice of rules referred to by the reference.
E.g., given the following module:
package a.b.c p[k] = v :- ... # rule1 p[k1] = v1 :- ... # rule2
The following calls yield the rules on the right.
GetRulesExact("data.a.b.c.p") => [rule1, rule2] GetRulesExact("data.a.b.c.p.x") => nil GetRulesExact("data.a.b.c") => nil
func (*Compiler) GetRulesForVirtualDocument ¶
GetRulesForVirtualDocument returns a slice of rules that produce the virtual document referred to by the reference.
E.g., given the following module:
package a.b.c p[k] = v :- ... # rule1 p[k1] = v1 :- ... # rule2
The following calls yield the rules on the right.
GetRulesForVirtualDocument("data.a.b.c.p") => [rule1, rule2] GetRulesForVirtualDocument("data.a.b.c.p.x") => [rule1, rule2] GetRulesForVirtualDocument("data.a.b.c") => nil
func (*Compiler) GetRulesWithPrefix ¶
GetRulesWithPrefix returns a slice of rules that share the prefix ref.
E.g., given the following module:
package a.b.c p[x] = y :- ... # rule1 p[k] = v :- ... # rule2 q :- ... # rule3
The following calls yield the rules on the right.
GetRulesWithPrefix("data.a.b.c.p") => [rule1, rule2] GetRulesWithPrefix("data.a.b.c.p.a") => nil GetRulesWithPrefix("data.a.b.c") => [rule1, rule2, rule3]
type DocKind ¶
type DocKind int
DocKind represents the collection of document types that can be produced by rules.
type ErrCode ¶
type ErrCode int
ErrCode defines the types of errors returned during parsing, compiling, etc.
type Error ¶
Error represents a single error caught during parsing, compiling, etc.
func NewError ¶
NewError returns a new Error object.
func (*Error) Error ¶
type Errors ¶
type Errors []*Error
Errors represents a series of errors encountered during parsing, compiling, etc.
func (Errors) Error ¶
type Expr ¶
type Expr struct { Location *Location `json:"-"` Index int Negated bool `json:",omitempty"` Terms interface{} }
Expr represents a single expression contained inside the body of a rule.
func MustParseExpr ¶
MustParseExpr returns a parsed expression. If an error occurs during parsing, panic.
func NewBuiltinExpr ¶
NewBuiltinExpr creates a new Expr object with the supplied terms. The builtin operator must be the first term.
func ParseExpr ¶
ParseExpr returns exactly one expression. If multiple expressions are parsed, an error is returned.
func (*Expr) Compare ¶
Compare returns an integer indicating whether expr is less than, equal to, or greater than other.
Expressions are compared as follows:
1. Negated expressions are always greater than than non-negated expressions. 2. Preceding expression (by Index) is always less than the other expression. 3. Single term expressions are always less than built-in expressions.
Otherwise, the expression terms are compared normally.
func (*Expr) Complement ¶
Complement returns a copy of this expression with the negation flag flipped.
func (*Expr) Equal ¶
Equal returns true if this Expr equals the other Expr.
func (*Expr) Hash ¶
Hash returns the hash code of the Expr.
func (*Expr) IsEquality ¶
IsEquality returns true if this is an equality expression.
func (*Expr) IsGround ¶
IsGround returns true if all of the expression terms are ground.
func (*Expr) OutputVars ¶
OutputVars returns a VarSet containing variables that would be bound by evaluating this expression.
func (*Expr) String ¶
func (*Expr) UnmarshalJSON ¶
UnmarshalJSON parses the byte array and stores the result in expr.
func (*Expr) Vars ¶
Vars returns a VarSet containing all of the variables in the expression. If skipClosures is true then variables contained inside closures within this expression will not be included in the VarSet.
type GenericTransformer ¶
type GenericTransformer struct {
// contains filtered or unexported fields
}
GenericTransformer implements the Transformer interface to provide a utility to transform AST nodes using a closure.
func (*GenericTransformer) Transform ¶
func (t *GenericTransformer) Transform(x interface{}) (interface{}, error)
Transform calls the function f on the GenericTransformer.
type GenericVisitor ¶
type GenericVisitor struct {
// contains filtered or unexported fields
}
GenericVisitor implements the Visitor interface to provide a utility to walk over AST nodes using a closure. If the closure returns true, the visitor will not walk over AST nodes under x.
func (*GenericVisitor) Visit ¶
func (vis *GenericVisitor) Visit(x interface{}) Visitor
Visit calls the function f on the GenericVisitor.
type Head ¶
Head represents the head of a rule. TODO(tsandall): refactor Rule to contain a Head.
func (*Head) String ¶
type Import ¶
Import represents a dependency on a document outside of the policy namespace. Imports are optional.
func (*Import) Compare ¶
Compare returns an integer indicating whether imp is less than, equal to, or greater than other.
func (*Import) Equal ¶
Equal returns true if imp is equal to other.
func (*Import) Loc ¶
Loc returns the location of the Import in the definition.
func (*Import) String ¶
type Location ¶
type Location struct { Text []byte `json:"-"` // The original text fragment from the source. File string // The name of the source file (which may be empty). Row int // The line in the source. Col int // The column in the row. }
Location records a position in source code
func NewLocation ¶
NewLocation returns a new Location object.
func (*Location) Errorf ¶
Errorf returns a new error value with a message formatted to include the location info (e.g., line, column, filename, etc.)
func (*Location) Format ¶
Format returns a formatted string prefixed with the location information.
func (*Location) Wrapf ¶
Wrapf returns a new error value that wraps an existing error with a message formatted to include the location info (e.g., line, column, filename, etc.)
type Module ¶
Module represents a collection of policies (defined by rules) within a namespace (defined by the package) and optional dependencies on external documents (defined by imports).
func MustParseModule ¶
MustParseModule returns a parsed module. If an error occurs during parsing, panic.
func ParseModule ¶
ParseModule returns a parsed Module object. For details on Module objects and their fields, see policy.go. Empty input will return nil, nil.
func (*Module) Compare ¶
Compare returns an integer indicating whether mod is less than, equal to, or greater than other.
func (*Module) Equal ¶
Equal returns true if mod equals other.
func (*Module) String ¶
type ModuleTreeNode ¶
type ModuleTreeNode struct { Key Value Modules []*Module Children map[Value]*ModuleTreeNode }
ModuleTreeNode represents a node in the module tree. The module tree is keyed by the package path.
func NewModuleTree ¶
func NewModuleTree(mods map[string]*Module) *ModuleTreeNode
NewModuleTree returns a new ModuleTreeNode that represents the root of the module tree populated with the given modules.
func (*ModuleTreeNode) Size ¶
func (n *ModuleTreeNode) Size() int
Size returns the number of modules in the tree.
type Null ¶
type Null struct{}
Null represents the null value defined by JSON.
func (Null) Equal ¶
Equal returns true if the other term Value is also Null.
func (Null) Hash ¶
Hash returns the hash code for the Value.
func (Null) IsGround ¶
IsGround always returns true.
func (Null) String ¶
type Number ¶
type Number float64
Number represents a numeric value as defined by JSON.
func (Number) Equal ¶
Equal returns true if the other Value is a Number and is equal.
func (Number) Hash ¶
Hash returns the hash code for the Value.
func (Number) IsGround ¶
IsGround always returns true.
func (Number) String ¶
type Object ¶
type Object [][2]*Term
Object represents an object as defined by the language. Objects are similar to the same types as defined by JSON with the exception that they can contain Vars and References.
func (Object) Diff ¶
Diff returns a new Object that contains only the key/value pairs that exist in obj.
func (Object) Equal ¶
Equal returns true if obj is equal to other.
func (Object) Get ¶
Get returns the value of k in obj if k exists, otherwise nil.
func (Object) Hash ¶
Hash returns the hash code for the Value.
func (Object) Intersect ¶
Intersect returns a slice of term triplets that represent the intersection of keys between obj and other. For each intersecting key, the values from obj and other are included as the last two terms in the triplet (respectively).
func (Object) IsGround ¶
IsGround returns true if all of the Object key/value pairs are ground.
func (Object) Keys ¶
Keys returns the keys of obj.
func (Object) Merge ¶
Merge returns a new Object containing the non-overlapping keys of obj and other. If there are overlapping keys between obj and other, the values of associated with the keys are merged. Only objects can be merged with other objects. If the values cannot be merged, the second turn value will be false.
func (Object) String ¶
type Option ¶
type Option func(*parser) Option
Option is a function that can set an option on the parser. It returns the previous setting as an Option.
func Debug ¶
Debug creates an Option to set the debug flag to b. When set to true, debugging information is printed to stdout while parsing.
The default is false.
func Memoize ¶
Memoize creates an Option to set the memoize flag to b. When set to true, the parser will cache all results so each expression is evaluated only once. This guarantees linear parsing time even for pathological cases, at the expense of more memory and slower times for typical cases.
The default is false.
func Recover ¶
Recover creates an Option to set the recover flag to b. When set to true, this causes the parser to recover from panics and convert it to an error. Setting it to false can be useful while debugging to access the full stack trace.
The default is true.
type Package ¶
Package represents the namespace of the documents produced by rules inside the module.
func (*Package) Compare ¶
Compare returns an integer indicating whether pkg is less than, equal to, or greater than other.
func (*Package) Equal ¶
Equal returns true if pkg is equal to other.
func (*Package) Loc ¶
Loc returns the location of the Package in the definition.
func (*Package) String ¶
type QueryIterator ¶
QueryIterator defines the interface for querying AST documents with references.
type Ref ¶
type Ref []*Term
Ref represents a reference as defined by the language.
func EmptyRef ¶
func EmptyRef() Ref
EmptyRef returns a new, empty reference.
func MustParseRef ¶
MustParseRef returns a parsed reference. If an error occurs during parsing, panic.
func ParseRef ¶
ParseRef returns exactly one reference.
func (Ref) Append ¶
Append returns a copy of ref with the term appended to the end.
func (Ref) Equal ¶
Equal returns true if ref is equal to other.
func (Ref) GroundPrefix ¶
GroundPrefix returns the ground portion of the ref starting from the head. By definition, the head of the reference is always ground.
func (Ref) HasPrefix ¶
HasPrefix returns true if the other ref is a prefix of this ref.
func (Ref) Hash ¶
Hash returns the hash code for the Value.
func (Ref) IsGround ¶
IsGround returns true if all of the parts of the Ref are ground.
func (Ref) IsNested ¶
IsNested returns true if this ref contains other Refs.
func (Ref) OutputVars ¶
OutputVars returns a VarSet containing variables that would be bound by evaluating
this expression in isolation.
func (Ref) String ¶
func (Ref) Underlying ¶
Underlying returns a slice of underlying Go values. If the slice is not ground, an error is returned.
type Rule ¶
type Rule struct { Location *Location `json:"-"` Name Var Key *Term `json:",omitempty"` Value *Term `json:",omitempty"` Body Body }
Rule represents a rule as defined in the language. Rules define the content of documents that represent policy decisions.
func MustParseRule ¶
MustParseRule returns a parsed rule. If an error occurs during parsing, panic.
func ParseConstantRule ¶
ParseConstantRule attempts to return a rule from a body. Equality expressions of the form <var> = <ground term> can be converted into rules of the form <var> = <ground term> :- true. This is a concise way of defining constants inside modules.
func ParseRule ¶
ParseRule returns exactly one rule. If multiple rules are parsed, an error is returned.
func (*Rule) Compare ¶
Compare returns an integer indicating whether rule is less than, equal to, or greater than other.
func (*Rule) DocKind ¶
DocKind returns the type of document produced by this rule.
func (*Rule) Equal ¶
Equal returns true if rule is equal to other.
func (*Rule) Head ¶
Head returns the rule's head.
func (*Rule) HeadVars ¶
HeadVars returns map where keys represent all of the variables found in the head of the rule. The values of the map are ignored.
func (*Rule) Loc ¶
Loc returns the location of the Rule in the definition.
func (*Rule) Path ¶
Path returns a reference that identifies the rule under ns.
func (*Rule) String ¶
type RuleTreeNode ¶
type RuleTreeNode struct { Key Value Rules []*Rule Children map[Value]*RuleTreeNode }
RuleTreeNode represents a node in the rule tree. The rule tree is keyed by rule path.
func NewRuleTree ¶
func NewRuleTree(mods map[string]*Module) *RuleTreeNode
NewRuleTree returns a new RuleTreeNode that represents the root of the rule tree populated with the given rules.
func (*RuleTreeNode) Size ¶
func (n *RuleTreeNode) Size() int
Size returns the number of rules in the tree.
type Set ¶
type Set []*Term
Set represents a set as defined by the language.
func (*Set) Add ¶
Add updates s to include t.
func (Set) Contains ¶
Contains returns true if t is in s.
func (*Set) Diff ¶
Diff returns elements in s that are not in other.
func (*Set) Equal ¶
Equal returns true if s is equal to v.
func (*Set) Hash ¶
Hash returns a hash code for s.
func (*Set) IsGround ¶
IsGround returns true if all terms in s are ground.
func (*Set) Map ¶
Map returns a new Set obtained by applying f to each value in s.
func (*Set) String ¶
type Statement ¶
type Statement interface { Loc() *Location }
Statement represents a single statement within a module.
type String ¶
type String string
String represents a string value as defined by JSON.
func (String) Equal ¶
Equal returns true if the other Value is a String and is equal.
func (String) Hash ¶
Hash returns the hash code for the Value.
func (String) IsGround ¶
IsGround always returns true.
func (String) String ¶
type Term ¶
type Term struct { Value Value // the value of the Term as represented in Go Location *Location `json:"-"` // the location of the Term in the source }
Term is an argument to a function.
func ArrayComprehensionTerm ¶
ArrayComprehensionTerm creates a new Term with an ArrayComprehension value.
func ArrayTerm ¶
ArrayTerm creates a new Term with an Array value.
func BooleanTerm ¶
BooleanTerm creates a new Term with a Boolean value.
func Item ¶
Item is a helper for constructing an tuple containing two Terms representing a key/value pair in an Object.
func MustParseTerm ¶
MustParseTerm returns a parsed term. If an error occurs during parsing, panic.
func NullTerm ¶
func NullTerm() *Term
NullTerm creates a new Term with a Null value.
func NumberTerm ¶
NumberTerm creates a new Term with a Number value.
func ObjectTerm ¶
ObjectTerm creates a new Term with an Object value.
func ParseTerm ¶
ParseTerm returns exactly one term. If multiple terms are parsed, an error is returned.
func RefTerm ¶
RefTerm creates a new Term with a Ref value.
func SetTerm ¶
SetTerm returns a new Term representing a set containing terms t.
func StringTerm ¶
StringTerm creates a new Term with a String value.
func VarTerm ¶
VarTerm creates a new Term with a Variable value.
func (*Term) Equal ¶
Equal returns true if this term equals the other term. Equality is defined for each kind of term.
func (*Term) Hash ¶
Hash returns the hash code of the Term's value.
func (*Term) IsGround ¶
IsGround returns true if this terms' Value is ground.
func (*Term) MarshalJSON ¶
MarshalJSON returns the JSON encoding of the term. Specialized marshalling logic is required to include a type hint for Value.
func (*Term) String ¶
func (*Term) UnmarshalJSON ¶
UnmarshalJSON parses the byte array and stores the result in term. Specialized unmarshalling is required to handle Value.
func (*Term) Vars ¶
Vars returns a VarSet with variables contained in this term.
type Transformer ¶
type Transformer interface { Transform(v interface{}) (interface{}, error) }
Transformer defines the interface for transforming AST elements. If the transformer returns nil and does not indicate an error, the AST element will be set to nil and no transformations will be applied to children of the element.
type Value ¶
type Value interface { // Equal returns true if this value equals the other value. Equal(other Value) bool // IsGround returns true if this value is not a variable or contains no variables. IsGround() bool // String returns a human readable string representation of the value. String() string // Returns hash code of the value. Hash() int }
Value declares the common interface for all Term values. Every kind of Term value in the language is represented as a type that implements this interface:
- Null, Boolean, Number, String - Object, Array - Variables - References - Array Comprehensions
func InterfaceToValue ¶
InterfaceToValue converts a native Go value x to a Value.
type ValueMap ¶
type ValueMap struct {
// contains filtered or unexported fields
}
ValueMap represents a key/value map between AST term values. Any type of term can be used as a key in the map.
func NewValueMap ¶
func NewValueMap() *ValueMap
NewValueMap returns a new ValueMap.
func (*ValueMap) Copy ¶
Copy returns a shallow copy of the ValueMap.
func (*ValueMap) Delete ¶
Delete removes a key k from the map.
func (*ValueMap) Equal ¶
Equal returns true if this ValueMap equals the other.
func (*ValueMap) Get ¶
Get returns the value in the map for k.
func (*ValueMap) Hash ¶
Hash returns a hash code for this ValueMap.
func (*ValueMap) Iter ¶
Iter calls the iter function for each key/value pair in the map. If the iter function returns true, iteration stops.
func (*ValueMap) Len ¶
Len returns the number of elements in the map.
func (*ValueMap) Put ¶
Put inserts a key k into the map with value v.
func (*ValueMap) String ¶
type Var ¶
type Var string
Var represents a variable as defined by the language.
func (Var) Equal ¶
Equal returns true if the other Value is a Variable and has the same value (name).
func (Var) Hash ¶
Hash returns the hash code for the Value.
func (Var) IsGround ¶
IsGround always returns false.
func (Var) IsWildcard ¶
IsWildcard returns true if this is a wildcard variable.
func (Var) String ¶
type VarSet ¶
type VarSet map[Var]struct{}
VarSet represents a set of variables.
func NewVarSet ¶
NewVarSet returns a new VarSet containing the specified variables.
func Unify ¶
Unify returns a set of variables that will be unified when the equality expression defined by terms a and b is evaluated. The unifier assumes that variables in the VarSet safe are already unified.
func (VarSet) Add ¶
Add updates the set to include the variable "v".
func (VarSet) Contains ¶
Contains returns true if the set contains the variable "v".
func (VarSet) Copy ¶
Copy returns a shallow copy of the VarSet.
func (VarSet) Diff ¶
Diff returns a VarSet containing variables in s that are not in vs.
func (VarSet) Intersect ¶
Intersect returns a VarSet containing variables in s that are in vs.
func (VarSet) String ¶
func (VarSet) Update ¶
Update merges the other VarSet into this VarSet.
type Visitor ¶
type Visitor interface { Visit(v interface{}) (w Visitor) }
Visitor defines the interface for iterating AST elements. The Visit function can return a Visitor w which will be used to visit the children of the AST element v. If the Visit function returns nil, the children will not be visited.
Source Files ¶
builtins.go compare.go compile.go doc.go errors.go map.go parser.go parser_ext.go policy.go term.go transform.go unify.go varset.go visit.go
- Version
- v0.2.0
- Published
- Nov 7, 2016
- Platform
- js/wasm
- Imports
- 19 packages
- Last checked
- 7 seconds ago –
Tools for package owners.