Documentation ¶
Overview ¶
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 ContainsComprehensions(v interface{}) bool
- func ContainsRefs(v interface{}) bool
- func IsConstant(v Value) bool
- func IsError(code string, err error) bool
- func IsKeyword(s string) bool
- func IsScalar(v Value) bool
- func IsValidImportPath(v Value) (err error)
- func JSON(v Value) (interface{}, error)
- func Parse(filename string, b []byte, opts ...Option) (interface{}, error)
- func ParseFile(filename string, opts ...Option) (i interface{}, err error)
- func ParseReader(filename string, r io.Reader, opts ...Option) (interface{}, error)
- func ParseStatements(filename, input string) ([]Statement, []*Comment, error)
- func RegisterBuiltin(b *Builtin)
- func Transform(t Transformer, x interface{}) (interface{}, error)
- func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error)
- func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error)
- func TypeName(x interface{}) string
- func ValueToInterface(v Value, resolver Resolver) (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 WalkExprs(x interface{}, f func(*Expr) bool)
- func WalkFuncs(x interface{}, f func(*Func) bool)
- func WalkRefs(x interface{}, f func(Ref) bool)
- func WalkRules(x interface{}, f func(*Rule) bool)
- func WalkVars(x interface{}, f func(Var) bool)
- func WalkWiths(x interface{}, f func(*With) bool)
- type ArgErrDetail
- type Args
- type Array
- func (arr Array) Compare(other Value) int
- func (arr Array) Copy() Array
- func (arr Array) Equal(other Value) bool
- func (arr Array) Find(path Ref) (Value, error)
- func (arr Array) Get(pos *Term) *Term
- func (arr Array) Hash() int
- func (arr Array) IsGround() bool
- func (arr Array) MarshalJSON() ([]byte, error)
- func (arr Array) String() string
- type ArrayComprehension
- func (ac *ArrayComprehension) Compare(other Value) int
- func (ac *ArrayComprehension) Copy() *ArrayComprehension
- func (ac *ArrayComprehension) Equal(other Value) bool
- func (ac *ArrayComprehension) Find(path Ref) (Value, error)
- func (ac *ArrayComprehension) Hash() int
- func (ac *ArrayComprehension) IsGround() bool
- func (ac *ArrayComprehension) String() string
- type Body
- func (body *Body) Append(expr *Expr)
- func (body Body) Compare(other Body) int
- func (body Body) Contains(x *Expr) bool
- func (body Body) Copy() Body
- 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(params VarVisitorParams) VarSet
- type Boolean
- type Builtin
- type Comment
- type Compiler
- func (c *Compiler) Compile(modules map[string]*Module)
- func (c *Compiler) Failed() bool
- func (c *Compiler) GetAllFuncs() map[String][]*Func
- func (c *Compiler) GetFunc(name String) []*Func
- func (c *Compiler) GetRules(ref Ref) (rules []*Rule)
- func (c *Compiler) GetRulesExact(ref Ref) (rules []*Rule)
- func (c *Compiler) GetRulesForVirtualDocument(ref Ref) (rules []*Rule)
- func (c *Compiler) GetRulesWithPrefix(ref Ref) (rules []*Rule)
- func (c *Compiler) QueryCompiler() QueryCompiler
- func (c *Compiler) RuleIndex(path Ref) RuleIndex
- func (c *Compiler) SetErrorLimit(limit int) *Compiler
- func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler
- type DocKind
- type Error
- type ErrorDetails
- type Errors
- type Expr
- func (expr *Expr) Compare(other *Expr) int
- func (expr *Expr) Complement() *Expr
- func (expr *Expr) Copy() *Expr
- func (expr *Expr) Equal(other *Expr) bool
- func (expr *Expr) Hash() int
- func (expr *Expr) IncludeWith(target *Term, value *Term) *Expr
- func (expr *Expr) IsBuiltin() bool
- func (expr *Expr) IsEquality() bool
- func (expr *Expr) IsGround() bool
- func (expr *Expr) Name() String
- func (expr *Expr) NoWith() *Expr
- func (expr *Expr) Operand(pos int) *Term
- func (expr *Expr) Operands() []*Term
- func (expr *Expr) OutputVars(safe VarSet) VarSet
- func (expr *Expr) SetLocation(loc *Location) *Expr
- func (expr *Expr) String() string
- func (expr *Expr) UnmarshalJSON(bs []byte) error
- func (expr *Expr) Vars(params VarVisitorParams) VarSet
- type Func
- type FuncHead
- func (h *FuncHead) ArgVars() VarSet
- func (h *FuncHead) Compare(other *FuncHead) int
- func (h *FuncHead) Copy() *FuncHead
- func (h *FuncHead) Equal(other *FuncHead) bool
- func (h *FuncHead) Loc() *Location
- func (h *FuncHead) OutVars() VarSet
- func (h *FuncHead) String() string
- func (h *FuncHead) Vars() VarSet
- type GenericTransformer
- type GenericVisitor
- type Graph
- type Head
- type Import
- type IndexResult
- type Location
- type Module
- type ModuleLoader
- type ModuleTreeNode
- type Null
- type Number
- func (num Number) Compare(other Value) int
- func (num Number) Equal(other Value) bool
- func (num Number) Find(path Ref) (Value, error)
- func (num Number) Hash() int
- func (num Number) Int() (int, bool)
- func (num Number) IsGround() bool
- func (num Number) MarshalJSON() ([]byte, error)
- func (num Number) String() string
- type Object
- func (obj Object) Compare(other Value) int
- func (obj Object) Copy() Object
- func (obj Object) Diff(other Object) Object
- func (obj Object) Equal(other Value) bool
- func (obj Object) Find(path Ref) (Value, error)
- 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) MarshalJSON() ([]byte, error)
- func (obj Object) Merge(other Object) (Object, bool)
- func (obj Object) String() string
- type ObjectComprehension
- func (oc *ObjectComprehension) Compare(other Value) int
- func (oc *ObjectComprehension) Copy() *ObjectComprehension
- func (oc *ObjectComprehension) Equal(other Value) bool
- func (oc *ObjectComprehension) Find(path Ref) (Value, error)
- func (oc *ObjectComprehension) Hash() int
- func (oc *ObjectComprehension) IsGround() bool
- func (oc *ObjectComprehension) String() string
- type Option
- type Package
- type QueryCompiler
- type QueryContext
- type QueryIterator
- type Ref
- func (ref Ref) Append(term *Term) Ref
- func (ref Ref) Compare(other Value) int
- func (ref Ref) ConstantPrefix() Ref
- func (ref Ref) Copy() Ref
- func (ref Ref) Dynamic() int
- func (ref Ref) Equal(other Value) bool
- func (ref Ref) Extend(other Ref) Ref
- func (ref Ref) Find(path Ref) (Value, error)
- 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
- type RefErrInvalidDetail
- type RefErrMissingDetail
- type RefErrUnsupportedDetail
- type Resolver
- type Rule
- func MustParseRule(input string) *Rule
- func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)
- func ParsePartialObjectDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)
- func ParsePartialSetDocRuleFromTerm(module *Module, term *Term) (*Rule, error)
- func ParseRule(input string) (*Rule, error)
- func ParseRuleFromBody(module *Module, body Body) (*Rule, error)
- func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error)
- type RuleIndex
- type RuleSet
- type Set
- func (s *Set) Add(t *Term)
- func (s *Set) Compare(other Value) int
- func (s Set) Contains(t *Term) bool
- func (s *Set) Copy() *Set
- func (s *Set) Diff(other *Set) *Set
- func (s *Set) Equal(v Value) bool
- func (s *Set) Find(path Ref) (Value, error)
- func (s *Set) Hash() int
- func (s *Set) Intersect(other *Set) *Set
- func (s *Set) IsGround() bool
- func (s *Set) Iter(f func(*Term) bool) (stop bool)
- func (s *Set) Map(f func(*Term) (*Term, error)) (*Set, error)
- func (s *Set) Reduce(i *Term, f func(*Term, *Term) (*Term, error)) (*Term, error)
- func (s *Set) String() string
- func (s *Set) Union(other *Set) *Set
- type SetComprehension
- func (sc *SetComprehension) Compare(other Value) int
- func (sc *SetComprehension) Copy() *SetComprehension
- func (sc *SetComprehension) Equal(other Value) bool
- func (sc *SetComprehension) Find(path Ref) (Value, error)
- func (sc *SetComprehension) Hash() int
- func (sc *SetComprehension) IsGround() bool
- func (sc *SetComprehension) String() string
- type Statement
- type String
- type Term
- func ArrayComprehensionTerm(term *Term, body Body) *Term
- func ArrayTerm(a ...*Term) *Term
- func BooleanTerm(b bool) *Term
- func FloatNumberTerm(f float64) *Term
- func IntNumberTerm(i int) *Term
- func Item(key, value *Term) [2]*Term
- func MustParseTerm(input string) *Term
- func NewTerm(v Value) *Term
- func NullTerm() *Term
- func NumberTerm(n json.Number) *Term
- func ObjectComprehensionTerm(key, value *Term, body Body) *Term
- func ObjectTerm(o ...[2]*Term) *Term
- func ParseTerm(input string) (*Term, error)
- func RefTerm(r ...*Term) *Term
- func SetComprehensionTerm(term *Term, body Body) *Term
- func SetTerm(t ...*Term) *Term
- func StringTerm(s string) *Term
- func VarTerm(v string) *Term
- func (term *Term) Copy() *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) SetLocation(loc *Location) *Term
- func (term *Term) String() string
- func (term *Term) UnmarshalJSON(bs []byte) error
- func (term *Term) Vars() VarSet
- type Transformer
- type TreeNode
- type TypeEnv
- type UnificationErrDetail
- type Value
- type 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 ValueResolver
- type Var
- type VarSet
- type VarVisitor
- type VarVisitorParams
- type Visitor
- type With
Examples ¶
Constants ¶
const ( // ParseErr indicates an unclassified parse error occurred. ParseErr = "rego_parse_error" // CompileErr indicates an unclassified compile error occurred. CompileErr = "rego_compile_error" // TypeErr indicates a type error was caught. TypeErr = "rego_type_error" // UnsafeVarErr indicates an unsafe variable was found during compilation. UnsafeVarErr = "rego_unsafe_var_error" // RecursionErr indicates recursion was found during compilation. RecursionErr = "rego_recursion_error" )
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 )
const ( NullTypeName = "null" BooleanTypeName = "boolean" StringTypeName = "string" NumberTypeName = "number" VarTypeName = "var" RefTypeName = "ref" ArrayTypeName = "array" ObjectTypeName = "object" SetTypeName = "set" ArrayComprehensionTypeName = "arraycomprehension" ExprTypeName = "expr" WithTypeName = "with" BodyTypeName = "body" HeadTypeName = "head" RuleTypeName = "rule" FuncTypeName = "func" FuncHeadTypeName = "funchead" ArgsTypeName = "args" ImportTypeName = "import" PackageTypeName = "package" )
The type names provide consistent strings for types in error messages.
const CompileErrorLimitDefault = 10
CompileErrorLimitDefault is the default number errors a compiler will allow before exiting.
Variables ¶
var Abs = &Builtin{ Name: String("abs"), Args: []types.Type{ types.N, types.N, }, TargetPos: []int{1}, }
Abs returns the number without its sign.
var And = &Builtin{ Name: String("and"), Infix: String("&"), Args: []types.Type{ types.NewSet(types.A), types.NewSet(types.A), types.NewSet(types.A), }, TargetPos: []int{2}, }
And performs an intersection operation on sets.
var Base64UrlDecode = &Builtin{ Name: String("base64url.decode"), Args: []types.Type{ types.S, types.S, }, TargetPos: []int{1}, }
Base64UrlDecode deserializes the base64url encoded input string.
var Base64UrlEncode = &Builtin{ Name: String("base64url.encode"), Args: []types.Type{ types.S, types.S, }, TargetPos: []int{1}, }
Base64UrlEncode serializes the input string into base64url encoding.
var BuiltinMap map[String]*Builtin
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.
var Concat = &Builtin{ Name: String("concat"), Args: []types.Type{ types.S, types.NewAny( types.NewSet(types.S), types.NewArray(nil, types.S), ), types.S, }, TargetPos: []int{2}, }
Concat joins an array of strings with an input string.
var Contains = &Builtin{ Name: String("contains"), Args: []types.Type{ types.S, types.S, }, }
Contains returns true if the search string is included in the base string
var Count = &Builtin{ Name: String("count"), Args: []types.Type{ types.NewAny( types.NewSet(types.A), types.NewArray(nil, types.A), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.S, ), types.N, }, TargetPos: []int{1}, }
Count takes a collection or string and counts the number of elements in it.
var DefaultBuiltins = [...]*Builtin{ Equality, GreaterThan, GreaterThanEq, LessThan, LessThanEq, NotEqual, Plus, Minus, Multiply, Divide, Round, Abs, And, Or, Count, Sum, Max, Min, ToNumber, RegexMatch, SetDiff, Concat, FormatInt, IndexOf, Substring, Lower, Upper, Contains, StartsWith, EndsWith, Split, Replace, Trim, Sprintf, JSONMarshal, JSONUnmarshal, Base64UrlEncode, Base64UrlDecode, YAMLMarshal, YAMLUnmarshal, JWTDecode, NowNanos, ParseNanos, ParseRFC3339Nanos, WalkBuiltin, }
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.
var DefaultRootRef = Ref{DefaultRootDocument}
DefaultRootRef is a reference to the root of the default document.
All refs to data in the policy engine's storage layer are prefixed with this ref.
var Divide = &Builtin{ Name: String("div"), Infix: String("/"), Args: []types.Type{ types.N, types.N, types.N, }, TargetPos: []int{2}, }
Divide divides the first number by the second number.
var EndsWith = &Builtin{ Name: String("endswith"), Args: []types.Type{ types.S, types.S, }, }
EndsWith returns true if the search string begins with the base string
var Equality = &Builtin{ Name: String("eq"), Infix: String("="), Args: []types.Type{ types.A, types.A, }, TargetPos: []int{0, 1}, }
Equality represents the "=" operator.
var FormatInt = &Builtin{ Name: String("format_int"), Args: []types.Type{ types.N, types.N, types.S, }, TargetPos: []int{2}, }
FormatInt returns the string representation of the number in the given base after converting it to an integer value.
var GreaterThan = &Builtin{ Name: String("gt"), Infix: String(">"), Args: []types.Type{ types.A, types.A, }, }
GreaterThan represents the ">" comparison operator.
var GreaterThanEq = &Builtin{ Name: String("gte"), Infix: String(">="), Args: []types.Type{ types.A, types.A, }, }
GreaterThanEq represents the ">=" comparison operator.
var IndexOf = &Builtin{ Name: String("indexof"), Args: []types.Type{ types.S, types.S, types.N, }, TargetPos: []int{2}, }
IndexOf returns the index of a substring contained inside a string
var InputRootDocument = VarTerm("input")
InputRootDocument names the document containing query arguments.
var InputRootRef = Ref{InputRootDocument}
InputRootRef is a reference to the root of the input document.
All refs to query arguments are prefixed with this ref.
var JSONMarshal = &Builtin{ Name: String("json.marshal"), Args: []types.Type{ types.A, types.S, }, TargetPos: []int{1}, }
JSONMarshal serializes the input term.
var JSONUnmarshal = &Builtin{ Name: String("json.unmarshal"), Args: []types.Type{ types.S, types.A, }, TargetPos: []int{1}, }
JSONUnmarshal deserializes the input string.
var JWTDecode = &Builtin{ Name: String("io.jwt.decode"), Args: []types.Type{ types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.S, }, TargetPos: []int{1, 2, 3}, }
JWTDecode decodes a JSON Web Token and outputs it as an Object.
var Keywords = [...]string{
"not",
"package",
"import",
"as",
"default",
"else",
"with",
"null",
"true",
"false",
}
Keywords contains strings that map to language keywords.
var LessThan = &Builtin{ Name: String("lt"), Infix: String("<"), Args: []types.Type{ types.A, types.A, }, }
LessThan represents the "<" comparison operator.
var LessThanEq = &Builtin{ Name: String("lte"), Infix: String("<="), Args: []types.Type{ types.A, types.A, }, }
LessThanEq represents the "<=" comparison operator.
var Lower = &Builtin{ Name: String("lower"), Args: []types.Type{ types.S, types.S, }, TargetPos: []int{1}, }
Lower returns the input string but with all characters in lower-case
var Max = &Builtin{ Name: String("max"), Args: []types.Type{ types.NewAny( types.NewSet(types.A), types.NewArray(nil, types.A), ), types.A, }, TargetPos: []int{1}, }
Max returns the maximum value in a collection.
var Min = &Builtin{ Name: String("min"), Args: []types.Type{ types.NewAny( types.NewSet(types.A), types.NewArray(nil, types.A), ), types.A, }, TargetPos: []int{1}, }
Min returns the minimum value in a collection.
var Minus = &Builtin{ Name: String("minus"), Infix: String("-"), Args: []types.Type{ types.NewAny(types.N, types.NewSet(types.A)), types.NewAny(types.N, types.NewSet(types.A)), types.NewAny(types.N, types.NewSet(types.A)), }, TargetPos: []int{2}, }
Minus subtracts the second number from the first number or computes the diff between two sets.
var Multiply = &Builtin{ Name: String("mul"), Infix: String("*"), Args: []types.Type{ types.N, types.N, types.N, }, TargetPos: []int{2}, }
Multiply multiplies two numbers together.
var NotEqual = &Builtin{ Name: String("neq"), Infix: String("!="), Args: []types.Type{ types.A, types.A, }, }
NotEqual represents the "!=" comparison operator.
var NowNanos = &Builtin{ Name: String("time.now_ns"), Args: []types.Type{ types.N, }, TargetPos: []int{0}, }
NowNanos returns the current time since epoch in nanoseconds.
var Or = &Builtin{ Name: String("or"), Infix: String("|"), Args: []types.Type{ types.NewSet(types.A), types.NewSet(types.A), types.NewSet(types.A), }, TargetPos: []int{2}, }
Or performs a union operation on sets.
var ParseNanos = &Builtin{ Name: String("time.parse_ns"), Args: []types.Type{ types.S, types.S, types.N, }, TargetPos: []int{2}, }
ParseNanos returns the time in nanoseconds parsed from the string in the given format.
var ParseRFC3339Nanos = &Builtin{ Name: String("time.parse_rfc3339_ns"), Args: []types.Type{ types.S, types.N, }, TargetPos: []int{1}, }
ParseRFC3339Nanos returns the time in nanoseconds parsed from the string in RFC3339 format.
var Plus = &Builtin{ Name: String("plus"), Infix: String("+"), Args: []types.Type{ types.N, types.N, types.N, }, TargetPos: []int{2}, }
Plus adds two numbers together.
var RegexMatch = &Builtin{ Name: String("re_match"), Args: []types.Type{ types.S, types.S, }, }
RegexMatch takes two strings and evaluates to true if the string in the second position matches the pattern in the first position.
var Replace = &Builtin{ Name: String("replace"), Args: []types.Type{ types.S, types.S, types.S, types.S, }, TargetPos: []int{3}, }
Replace returns the given string with all instances of the second argument replaced by the third.
var ReservedVars = NewVarSet( DefaultRootDocument.Value.(Var), InputRootDocument.Value.(Var), )
ReservedVars is the set of names that refer to implicitly ground vars.
var RootDocumentNames = &Set{ DefaultRootDocument, InputRootDocument, }
RootDocumentNames contains the names of top-level documents that can be referred to in modules and queries.
var RootDocumentRefs = &Set{ NewTerm(DefaultRootRef), NewTerm(InputRootRef), }
RootDocumentRefs contains the prefixes of top-level documents that all non-local references start with.
var Round = &Builtin{ Name: String("round"), Args: []types.Type{ types.N, types.N, }, TargetPos: []int{1}, }
Round rounds the number up to the nearest integer.
var SetDiff = &Builtin{ Name: String("set_diff"), Args: []types.Type{ types.NewSet(types.A), types.NewSet(types.A), types.NewSet(types.A), }, TargetPos: []int{2}, }
SetDiff has been replaced by the minus built-in.
var Split = &Builtin{ Name: String("split"), Args: []types.Type{ types.S, types.S, types.NewArray(nil, types.S), }, TargetPos: []int{2}, }
Split returns an array containing elements of the input string split on a delimiter.
var Sprintf = &Builtin{ Name: String("sprintf"), Args: []types.Type{ types.S, types.NewArray(nil, types.A), types.S, }, TargetPos: []int{2}, }
Sprintf returns the given string, formatted.
var StartsWith = &Builtin{ Name: String("startswith"), Args: []types.Type{ types.S, types.S, }, }
StartsWith returns true if the search string begins with the base string
var Substring = &Builtin{ Name: String("substring"), Args: []types.Type{ types.S, types.N, types.N, types.S, }, TargetPos: []int{3}, }
Substring returns the portion of a string for a given start index and a length.
If the length is less than zero, then substring returns the remainder of the string.
var Sum = &Builtin{ Name: String("sum"), Args: []types.Type{ types.NewAny( types.NewSet(types.N), types.NewArray(nil, types.N), ), types.N, }, TargetPos: []int{1}, }
Sum takes an array or set of numbers and sums them.
var SystemDocumentKey = String("system")
SystemDocumentKey is the name of the top-level key that identifies the system document.
var ToNumber = &Builtin{ Name: String("to_number"), Args: []types.Type{ types.NewAny( types.N, types.S, types.B, types.NewNull(), ), types.N, }, TargetPos: []int{1}, }
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.
var Trim = &Builtin{ Name: String("trim"), Args: []types.Type{ types.S, types.S, types.S, }, TargetPos: []int{2}, }
Trim returns the given string will all leading or trailing instances of the second argument removed.
var Upper = &Builtin{ Name: String("upper"), Args: []types.Type{ types.S, types.S, }, TargetPos: []int{1}, }
Upper returns the input string but with all characters in upper-case
var WalkBuiltin = &Builtin{ Name: String("walk"), Args: []types.Type{ types.A, types.NewArray( []types.Type{ types.NewArray(nil, types.A), types.A, }, nil, ), }, TargetPos: []int{1}, }
WalkBuiltin generates [path, value] tuples for all nested documents (recursively).
var Wildcard = &Term{Value: Var("_")}
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.
var YAMLMarshal = &Builtin{ Name: String("yaml.marshal"), Args: []types.Type{ types.A, types.S, }, TargetPos: []int{1}, }
YAMLMarshal serializes the input term.
var YAMLUnmarshal = &Builtin{ Name: String("yaml.unmarshal"), Args: []types.Type{ types.S, types.A, }, TargetPos: []int{1}, }
YAMLUnmarshal deserializes the input string.
Functions ¶
func Compare ¶ added in v0.2.0
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 ContainsComprehensions ¶ added in v0.5.8
func ContainsComprehensions(v interface{}) bool
ContainsComprehensions returns true if the Value v contains comprehensions.
func ContainsRefs ¶ added in v0.5.8
func ContainsRefs(v interface{}) bool
ContainsRefs returns true if the Value v contains refs.
func IsConstant ¶ added in v0.4.9
IsConstant returns true if the AST value is constant.
func IsValidImportPath ¶ added in v0.3.0
IsValidImportPath returns an error indicating if the import path is invalid. If the import path is invalid, err is nil.
func JSON ¶ added in v0.4.9
JSON returns the JSON representation of v. The value must not contain any refs or terms that require evaluation (e.g., vars, comprehensions, etc.)
func ParseReader ¶
ParseReader parses the data from r using filename as information in the error messages.
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 ¶ added in v0.2.0
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 TransformComprehensions ¶ added in v0.5.8
func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error)
TransformComprehensions calls the functio nf on all comprehensions under x.
func TransformRefs ¶ added in v0.2.0
TransformRefs calls the function f on all references under x.
func TypeName ¶ added in v0.3.0
func TypeName(x interface{}) string
TypeName returns a human readable name for the AST element type.
func ValueToInterface ¶ added in v0.4.9
ValueToInterface returns the Go representation of an AST value. The AST value should not contain any values that require evaluation (e.g., vars, comprehensions, etc.)
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 ¶ added in v0.2.0
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 WalkExprs ¶ added in v0.4.9
WalkExprs calls the function f on all expressions under x. If the function f returns true, AST nodes under the last node will not be visited.
func WalkFuncs ¶ added in v0.5.0
WalkFuncs calls the function f on all user functions 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.
func WalkRules ¶ added in v0.4.10
WalkRules calls the function f on all rules under x. If the function f returns true, AST nodes under the last node will not be visited.
Types ¶
type ArgErrDetail ¶ added in v0.4.9
ArgErrDetail represents a generic argument error.
func (*ArgErrDetail) Lines ¶ added in v0.4.9
func (d *ArgErrDetail) Lines() []string
Lines returns the string representation of the detail.
type Args ¶ added in v0.5.0
type Args []*Term
Args represents zero or more arguments to a user function.
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) Compare ¶ added in v0.5.0
Compare compares arr to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Array) MarshalJSON ¶ added in v0.3.0
MarshalJSON returns JSON encoded bytes representing arr.
type ArrayComprehension ¶
ArrayComprehension represents an array comprehension as defined in the language.
func (*ArrayComprehension) Compare ¶ added in v0.5.0
func (ac *ArrayComprehension) Compare(other Value) int
Compare compares ac to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (*ArrayComprehension) Copy ¶ added in v0.2.2
func (ac *ArrayComprehension) Copy() *ArrayComprehension
Copy returns a deep copy of ac.
func (*ArrayComprehension) Equal ¶
func (ac *ArrayComprehension) Equal(other Value) bool
Equal returns true if ac is equal to other.
func (*ArrayComprehension) Find ¶ added in v0.4.5
func (ac *ArrayComprehension) Find(path Ref) (Value, error)
Find returns the current value or a not found error.
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 expressions contained inside a rule or user function.
func MustParseBody ¶
MustParseBody returns a parsed body. If an error occurs during parsing, panic.
func NewBody ¶ added in v0.2.0
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) Append ¶ added in v0.4.1
Append adds the expr to the body and updates the expr's index accordingly.
func (Body) Compare ¶ added in v0.2.0
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) OutputVars ¶
OutputVars returns a VarSet containing the variables that would be bound by evaluating the body.
func (Body) Vars ¶
func (body Body) Vars(params VarVisitorParams) VarSet
Vars returns a VarSet containing variables in body. The params can be set to control which vars are included.
type Boolean ¶
type Boolean bool
Boolean represents a boolean value defined by JSON.
func (Boolean) Compare ¶ added in v0.5.0
Compare compares bol to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
type Builtin ¶
type Builtin struct { Name String // Unique name of built-in function, e.g., name(term,term,...,term) Infix String // Unique name of infix operator. Default should be unset. Args []types.Type // Built-in argument type declaration. 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) IsTargetPos ¶
IsTargetPos returns true if a variable in the i-th position will be bound when the expression is evaluated.
type Comment ¶ added in v0.4.0
Comment contains the raw text from the comment in the definition.
func NewComment ¶ added in v0.4.0
NewComment returns a new Comment object.
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 containing // 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 *TreeNode // FuncTree organizes user functions into a tree where each node is keyed // by an element in the logical path to the function. The logical path is // the concatenations of the containing package and the stringified function // name. Functions are only located at the lead nodes, each of which have // exactly 1 function. E.g., given the following module: // // package a.b // p(x) = y { y = x } // q(x) = y { y = 2*x } // // root // | // +--- a (no functions) // | // +--- b (no functions) // | // +--- p // | // +--- q FuncTree *TreeNode // FunctionMap is a map containing the user defined functions of this // compiler's modules. FuncMap map[String][]*Func // Graph represents the dependencies between rules and funcs (lets call // them targets). An edge (u,v) is added to the graph if target "u" // depends on target "v". A target "u" depends on target "v" if target // "u" refers to the virtual document (or function) defined by target "v". Graph *Graph // TypeEnv holds type information for values inferred by the compiler. TypeEnv *TypeEnv // contains filtered or unexported fields }
Compiler contains the state of a compilation process.
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.
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 input.bar p[x] { foo[x]; not bar[x]; x >= min_x } min_x = 100 { true }` // 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:", c.Modules["my_module"].Rules[0].Body[0]) fmt.Println("Expr 2:", c.Modules["my_module"].Rules[0].Body[1]) fmt.Println("Expr 3:", c.Modules["my_module"].Rules[0].Body[2]) }
Output: Expr 1: data.foo[x] Expr 2: not input.bar[x] Expr 3: x >= data.opa.example.min_x
func (*Compiler) GetAllFuncs ¶ added in v0.5.0
GetAllFuncs returns a map of functions that this compiler has discovered.
func (*Compiler) GetRules ¶ added in v0.4.0
GetRules returns a slice of rules that are referred to by ref.
E.g., given the following module:
package a.b.c p[x] = y { q[x] = y; ... } # rule1 q[x] = y { ... } # rule2
The following calls yield the rules on the right.
GetRules("data.a.b.c.p") => [rule1] GetRules("data.a.b.c.p.x") => [rule1] GetRules("data.a.b.c.q") => [rule2] GetRules("data.a.b.c") => [rule1, rule2] GetRules("data.a.b.d") => nil
func (*Compiler) GetRulesExact ¶ added in v0.2.0
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 ¶ added in v0.2.0
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 ¶ added in v0.2.0
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]
func (*Compiler) QueryCompiler ¶ added in v0.2.2
func (c *Compiler) QueryCompiler() QueryCompiler
QueryCompiler returns a new QueryCompiler object.
func (*Compiler) RuleIndex ¶ added in v0.4.9
RuleIndex returns a RuleIndex built for the rule set referred to by path. The path must refer to the rule set exactly, i.e., given a rule set at path data.a.b.c.p, refs data.a.b.c.p.x and data.a.b.c would not return a RuleIndex built for the rule.
func (*Compiler) SetErrorLimit ¶ added in v0.5.3
SetErrorLimit sets the number of errors the compiler can encounter before it quits. Zero or a negative number indicates no limit.
func (*Compiler) WithModuleLoader ¶ added in v0.3.0
func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler
WithModuleLoader sets f as the ModuleLoader on the compiler.
The compiler will invoke the ModuleLoader after resolving all references in the current set of input modules. The ModuleLoader can return a new collection of parsed modules that are to be included in the compilation process. This process will repeat until the ModuleLoader returns an empty collection or an error. If an error is returned, compilation will stop immediately.
type DocKind ¶
type DocKind int
DocKind represents the collection of document types that can be produced by rules.
type Error ¶ added in v0.2.0
type Error struct { Code string `json:"code"` Message string `json:"message"` Location *Location `json:"location,omitempty"` Details ErrorDetails `json:"details,omitempty"` }
Error represents a single error caught during parsing, compiling, etc.
type ErrorDetails ¶ added in v0.4.9
type ErrorDetails interface {
Lines() []string
}
ErrorDetails defines the interface for detailed error messages.
type Errors ¶ added in v0.2.0
type Errors []*Error
Errors represents a series of errors encountered during parsing, compiling, etc.
type Expr ¶
type Expr struct { Location *Location `json:"-"` Index int `json:"index"` Negated bool `json:"negated,omitempty"` Terms interface{} `json:"terms"` With []*With `json:"with,omitempty"` }
Expr represents a single expression contained inside the body of a rule.
func MustParseExpr ¶ added in v0.2.0
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 NewExpr ¶ added in v0.2.1
func NewExpr(terms interface{}) *Expr
NewExpr returns a new Expr object.
func ParseExpr ¶ added in v0.2.0
ParseExpr returns exactly one expression. If multiple expressions are parsed, an error is returned.
func (*Expr) Compare ¶ added in v0.2.0
Compare returns an integer indicating whether expr is less than, equal to, or greater than other.
Expressions are compared as follows:
1. Preceding expression (by Index) is always less than the other expression. 2. Non-negated expressions are always less than than negated expressions. 3. Single term expressions are always less than built-in expressions.
Otherwise, the expression terms are compared normally. If both expressions have the same terms, the modifiers are compared.
func (*Expr) Complement ¶
Complement returns a copy of this expression with the negation flag flipped.
func (*Expr) IncludeWith ¶ added in v0.4.1
IncludeWith returns a copy of expr with the with modifier appended.
func (*Expr) IsBuiltin ¶ added in v0.4.9
IsBuiltin returns true if this expression refers to a function.
func (*Expr) IsEquality ¶
IsEquality returns true if this is an equality expression.
func (*Expr) Name ¶ added in v0.5.0
Name returns the name of the user function or built-in this expression refers to. If this expression is not a function call, returns the empty string.
func (*Expr) NoWith ¶ added in v0.4.1
NoWith returns a copy of expr where the with modifier has been removed.
func (*Expr) Operand ¶ added in v0.4.9
Operand returns the term at the zero-based pos. If the expr does not include at least pos+1 terms, this function returns nil.
func (*Expr) OutputVars ¶
OutputVars returns a VarSet containing variables that would be bound by evaluating this expression.
func (*Expr) SetLocation ¶ added in v0.5.6
SetLocation sets the expr's location and returns the expr itself.
func (*Expr) UnmarshalJSON ¶
UnmarshalJSON parses the byte array and stores the result in expr.
func (*Expr) Vars ¶
func (expr *Expr) Vars(params VarVisitorParams) VarSet
Vars returns a VarSet containing variables in expr. The params can be set to control which vars are included.
type Func ¶ added in v0.5.0
type Func struct { Location *Location `json:"-"` Head *FuncHead `json:"head"` Body Body `json:"body"` // Module is a pointer to the module containing this func. If the func // was NOT created while parsing/constructing a module, this should be // left unset. The pointer is not included in any standard operations // on the func (e.g., printing, comparison, visiting, etc.) Module *Module `json:"-"` }
Func represents a user function as defined in the language. Funcs define reusable queries than can be called like built-ins, but have access to the data and input documents like rules.
func (*Func) Compare ¶ added in v0.5.0
Compare returns an integer indicating whether f is less than, equal to, or greater than other.
func (*Func) Path ¶ added in v0.5.0
Path returns a ref referring to the this Func. If f is not contained in a module, this function panics.
func (*Func) PathString ¶ added in v0.5.0
PathString returns a String type representing the full path of this Func.
type FuncHead ¶ added in v0.5.0
type FuncHead struct { Location *Location `json:"-"` Name Var `json:"name"` Args Args `json:"args,omitempty"` Output *Term `json:"output,omitempty"` }
FuncHead represents the head of a user function.
func NewFuncHead ¶ added in v0.5.0
NewFuncHead returns a new FuncHead objects. If args are provided, they denote the inputs to the function.
func (*FuncHead) ArgVars ¶ added in v0.5.0
ArgVars returns a set of vars found in the FuncHead's arguments.
func (*FuncHead) Compare ¶ added in v0.5.0
Compare returns an integer indicating whether h is less than, equal to, or greater than other.
type GenericTransformer ¶ added in v0.2.0
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 ¶ added in v0.2.0
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 NewGenericVisitor ¶ added in v0.4.1
func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor
NewGenericVisitor returns a new GenericVisitor that will invoke the function f on AST nodes.
func (*GenericVisitor) Visit ¶
func (vis *GenericVisitor) Visit(x interface{}) Visitor
Visit calls the function f on the GenericVisitor.
type Graph ¶ added in v0.5.0
type Graph struct {
// contains filtered or unexported fields
}
Graph represents the graph of dependencies between ast Rules and Funcs.
func NewGraph ¶ added in v0.5.0
func NewGraph(modules map[string]*Module, list func(Ref) []*Rule, resolve func(String) []*Func) *Graph
NewGraph returns a new Graph based on modules. The list function must return the rules or user functions referred to directly by the ref.
func (*Graph) Dependencies ¶ added in v0.5.0
Dependencies returns the set of rules and funcs that x depends on.
type Head ¶ added in v0.2.0
type Head struct { Location *Location `json:"-"` Name Var `json:"name"` Key *Term `json:"key,omitempty"` Value *Term `json:"value,omitempty"` }
Head represents the head of a rule.
func NewHead ¶ added in v0.4.1
NewHead returns a new Head object. If args are provided, the first will be used for the key and the second will be used for the value.
func (*Head) Compare ¶ added in v0.4.1
Compare returns an integer indicating whether head is less than, equal to, or greater than other.
type Import ¶
type Import struct { Location *Location `json:"-"` Path *Term `json:"path"` Alias Var `json:"alias,omitempty"` }
Import represents a dependency on a document outside of the policy namespace. Imports are optional.
func MustParseImports ¶ added in v0.2.2
MustParseImports returns a slice of imports. If an error occurs during parsing, panic.
func ParseImports ¶ added in v0.2.2
ParseImports returns a slice of Import objects.
func (*Import) Compare ¶ added in v0.2.0
Compare returns an integer indicating whether imp is less than, equal to, or greater than other.
type IndexResult ¶ added in v0.4.10
IndexResult contains the result of an index lookup.
func NewIndexResult ¶ added in v0.4.10
func NewIndexResult(kind DocKind) *IndexResult
NewIndexResult returns a new IndexResult object.
func (*IndexResult) Empty ¶ added in v0.4.10
func (ir *IndexResult) Empty() bool
Empty returns true if there are no rules to evaluate.
type Location ¶
type Location struct { Text []byte `json:"-"` // The original text fragment from the source. File string `json:"file"` // The name of the source file (which may be empty). Row int `json:"row"` // The line in the source. Col int `json:"col"` // 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.)
type Module ¶
type Module struct { Package *Package `json:"package"` Imports []*Import `json:"imports,omitempty"` Rules []*Rule `json:"rules,omitempty"` Funcs []*Func `json:"funcs,omitempty"` Comments []*Comment `json:"comments,omitempty"` }
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 ¶ added in v0.2.0
Compare returns an integer indicating whether mod is less than, equal to, or greater than other.
type ModuleLoader ¶ added in v0.3.0
ModuleLoader defines the interface that callers can implement to enable lazy loading of modules during compilation.
type ModuleTreeNode ¶
type ModuleTreeNode struct { Key Value Modules []*Module Children map[Value]*ModuleTreeNode Hide bool }
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) DepthFirst ¶ added in v0.2.2
func (n *ModuleTreeNode) DepthFirst(f func(node *ModuleTreeNode) bool)
DepthFirst performs a depth-first traversal of the module tree rooted at n. If f returns true, traversal will not continue to the children of n.
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) Compare ¶ added in v0.5.0
Compare compares null to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
type Number ¶
Number represents a numeric value as defined by JSON.
func (Number) Compare ¶ added in v0.5.0
Compare compares num to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Number) MarshalJSON ¶ added in v0.3.0
MarshalJSON returns JSON encoded bytes representing num.
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) Compare ¶ added in v0.5.0
Compare compares obj to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Object) Diff ¶
Diff returns a new Object that contains only the key/value pairs that exist in obj.
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) MarshalJSON ¶ added in v0.3.0
MarshalJSON returns JSON encoded bytes representing 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.
type ObjectComprehension ¶ added in v0.5.2
type ObjectComprehension struct { Key *Term `json:"key"` Value *Term `json:"value"` Body Body `json:"body"` }
ObjectComprehension represents an object comprehension as defined in the language.
func (*ObjectComprehension) Compare ¶ added in v0.5.2
func (oc *ObjectComprehension) Compare(other Value) int
Compare compares oc to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (*ObjectComprehension) Copy ¶ added in v0.5.2
func (oc *ObjectComprehension) Copy() *ObjectComprehension
Copy returns a deep copy of oc.
func (*ObjectComprehension) Equal ¶ added in v0.5.2
func (oc *ObjectComprehension) Equal(other Value) bool
Equal returns true if oc is equal to other.
func (*ObjectComprehension) Find ¶ added in v0.5.2
func (oc *ObjectComprehension) Find(path Ref) (Value, error)
Find returns the current value or a not found error.
func (*ObjectComprehension) Hash ¶ added in v0.5.2
func (oc *ObjectComprehension) Hash() int
Hash returns the hash code of the Value.
func (*ObjectComprehension) IsGround ¶ added in v0.5.2
func (oc *ObjectComprehension) IsGround() bool
IsGround returns true if the Key, Value and Body are ground.
func (*ObjectComprehension) String ¶ added in v0.5.2
func (oc *ObjectComprehension) String() 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 CommentsOption ¶ added in v0.5.0
func CommentsOption() Option
CommentsOption returns a parser option to initialize the comments store within the parser.
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 GlobalStore ¶ added in v0.5.0
GlobalStore creates an Option to set a key to a certain value in the globalStore.
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.
type Package ¶
Package represents the namespace of the documents produced by rules inside the module.
func MustParsePackage ¶ added in v0.2.2
MustParsePackage returns a Package. If an error occurs during parsing, panic.
func ParsePackage ¶ added in v0.2.2
ParsePackage returns exactly one Package. If multiple statements are parsed, an error is returned.
func (*Package) Compare ¶ added in v0.2.0
Compare returns an integer indicating whether pkg is less than, equal to, or greater than other.
type QueryCompiler ¶ added in v0.2.2
type QueryCompiler interface { // Compile should be called to compile ad-hoc queries. The return value is // the compiled version of the query. Compile(q Body) (Body, error) // TypeEnv returns the type environment built after running type checking // on the query. TypeEnv() *TypeEnv // WithContext sets the QueryContext on the QueryCompiler. Subsequent calls // to Compile will take the QueryContext into account. WithContext(qctx *QueryContext) QueryCompiler }
QueryCompiler defines the interface for compiling ad-hoc queries.
type QueryContext ¶ added in v0.2.2
QueryContext contains contextual information for running an ad-hoc query.
Ad-hoc queries can be run in the context of a package and imports may be included to provide concise access to data.
func NewQueryContext ¶ added in v0.2.2
func NewQueryContext() *QueryContext
NewQueryContext returns a new QueryContext object.
func (*QueryContext) Copy ¶ added in v0.2.2
func (qc *QueryContext) Copy() *QueryContext
Copy returns a deep copy of qc.
func (*QueryContext) InputDefined ¶ added in v0.4.1
func (qc *QueryContext) InputDefined() bool
InputDefined returns true if the input document is defined in qc.
func (*QueryContext) WithImports ¶ added in v0.4.0
func (qc *QueryContext) WithImports(imports []*Import) *QueryContext
WithImports sets the imports on qc.
func (*QueryContext) WithInput ¶ added in v0.4.0
func (qc *QueryContext) WithInput(input Value) *QueryContext
WithInput sets the input on qc.
func (*QueryContext) WithPackage ¶ added in v0.4.0
func (qc *QueryContext) WithPackage(pkg *Package) *QueryContext
WithPackage sets the pkg on qc.
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 MustParseRef ¶
MustParseRef returns a parsed reference. If an error occurs during parsing, panic.
func (Ref) Compare ¶ added in v0.5.0
Compare compares ref to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Ref) ConstantPrefix ¶ added in v0.5.3
ConstantPrefix returns the constant portion of the ref starting from the head.
func (Ref) Dynamic ¶ added in v0.4.9
Dynamic returns the offset of the first non-constant operand of ref.
func (Ref) Extend ¶ added in v0.3.0
Extend returns a copy of ref with the terms from other appended. The head of other will be converted to a string.
func (Ref) GroundPrefix ¶ added in v0.2.0
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 ¶ added in v0.2.0
HasPrefix returns true if the other ref is a prefix of this ref.
func (Ref) OutputVars ¶
OutputVars returns a VarSet containing variables that would be bound by evaluating
this expression in isolation.
type RefErrInvalidDetail ¶ added in v0.5.2
type RefErrInvalidDetail struct { Ref Ref `json:"ref"` // invalid ref Pos int `json:"pos"` // invalid element Have types.Type `json:"have,omitempty"` // type of invalid element (for var/ref elements) Want types.Type `json:"want"` // allowed type (for non-object values) OneOf []Value `json:"oneOf"` // allowed values (e.g., for object keys) }
RefErrInvalidDetail describes an undefined reference error where the referenced value does not support the reference operand (e.g., missing object key, invalid key type, etc.)
func (*RefErrInvalidDetail) Lines ¶ added in v0.5.2
func (r *RefErrInvalidDetail) Lines() []string
Lines returns the string representation of the detail.
type RefErrMissingDetail ¶ added in v0.5.2
type RefErrMissingDetail struct {
Ref Ref
}
RefErrMissingDetail describes an undefined reference error where the type information for the head of the reference is missing.
func (*RefErrMissingDetail) Lines ¶ added in v0.5.2
func (r *RefErrMissingDetail) Lines() []string
Lines returns the string representation of the detail.
type RefErrUnsupportedDetail ¶ added in v0.5.2
type RefErrUnsupportedDetail struct { Ref Ref `json:"ref"` // invalid ref Pos int `json:"pos"` // invalid element Have types.Type `json:"have"` // referenced type }
RefErrUnsupportedDetail describes an undefined reference error where the referenced value does not support dereferencing (e.g., scalars).
func (*RefErrUnsupportedDetail) Lines ¶ added in v0.5.2
func (r *RefErrUnsupportedDetail) Lines() []string
Lines returns the string representation of the detail.
type Resolver ¶ added in v0.4.9
Resolver defines the interface for resolving references to native Go values.
type Rule ¶
type Rule struct { Location *Location `json:"-"` Default bool `json:"default,omitempty"` Head *Head `json:"head"` Body Body `json:"body"` Else *Rule `json:"else,omitempty"` // Module is a pointer to the module containing this rule. If the rule // was NOT created while parsing/constructing a module, this should be // left unset. The pointer is not included in any standard operations // on the rule (e.g., printing, comparison, visiting, etc.) Module *Module `json:"-"` }
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 ParseCompleteDocRuleFromEqExpr ¶ added in v0.5.6
ParseCompleteDocRuleFromEqExpr returns a rule if the expression can be interpreted as a complete document definition.
func ParsePartialObjectDocRuleFromEqExpr ¶ added in v0.5.6
ParsePartialObjectDocRuleFromEqExpr returns a rule if the expression can be interpreted as a partial object document definition.
func ParsePartialSetDocRuleFromTerm ¶ added in v0.5.6
ParsePartialSetDocRuleFromTerm returns a rule if the term can be interpreted as a partial set document definition.
func ParseRule ¶
ParseRule returns exactly one rule. If multiple rules are parsed, an error is returned.
func ParseRuleFromBody ¶ added in v0.3.0
ParseRuleFromBody returns a rule if the body can be interpreted as a rule definition. Otherwise, an error is returned.
func ParseRuleFromExpr ¶ added in v0.5.6
ParseRuleFromExpr returns a rule if the expression can be interpreted as a rule definition.
func (*Rule) Compare ¶ added in v0.2.0
Compare returns an integer indicating whether rule is less than, equal to, or greater than other.
type RuleIndex ¶ added in v0.4.9
type RuleIndex interface { // Build tries to construct an index for the given rules. If the index was // constructed, ok is true, otherwise false. Build(rules []*Rule) (ok bool) // Lookup searches the index for rules that will match the provided // resolver. If the resolver returns an error, it is returned via err. Lookup(resolver ValueResolver) (result *IndexResult, err error) }
RuleIndex defines the interface for rule indices.
type RuleSet ¶ added in v0.4.9
type RuleSet []*Rule
RuleSet represents a collection of rules that produce a virtual document.
func NewRuleSet ¶ added in v0.4.9
NewRuleSet returns a new RuleSet containing the given rules.
func (RuleSet) Diff ¶ added in v0.4.9
Diff returns a new RuleSet containing rules in rs that are not in other.
type Set ¶ added in v0.2.0
type Set []*Term
Set represents a set as defined by the language.
func (*Set) Compare ¶ added in v0.5.0
Compare compares s to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (*Set) Intersect ¶ added in v0.4.2
Intersect returns the set containing elements in both s and other.
func (*Set) Iter ¶ added in v0.4.0
Iter calls f on each element in s. If f returns true, iteration stops and the return value is true.
type SetComprehension ¶ added in v0.5.2
SetComprehension represents a set comprehension as defined in the language.
func (*SetComprehension) Compare ¶ added in v0.5.2
func (sc *SetComprehension) Compare(other Value) int
Compare compares sc to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (*SetComprehension) Copy ¶ added in v0.5.2
func (sc *SetComprehension) Copy() *SetComprehension
Copy returns a deep copy of sc.
func (*SetComprehension) Equal ¶ added in v0.5.2
func (sc *SetComprehension) Equal(other Value) bool
Equal returns true if sc is equal to other.
func (*SetComprehension) Find ¶ added in v0.5.2
func (sc *SetComprehension) Find(path Ref) (Value, error)
Find returns the current value or a not found error.
func (*SetComprehension) Hash ¶ added in v0.5.2
func (sc *SetComprehension) Hash() int
Hash returns the hash code of the Value.
func (*SetComprehension) IsGround ¶ added in v0.5.2
func (sc *SetComprehension) IsGround() bool
IsGround returns true if the Term and Body are ground.
func (*SetComprehension) String ¶ added in v0.5.2
func (sc *SetComprehension) String() string
type Statement ¶
type Statement interface {
Loc() *Location
}
Statement represents a single statement in a policy module.
func MustParseStatement ¶
MustParseStatement returns exactly one statement. If an error occurs during parsing, panic.
func MustParseStatements ¶
MustParseStatements returns a slice of parsed statements. If an error occurs during parsing, panic.
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.
type String ¶
type String string
String represents a string value as defined by JSON.
func (String) Compare ¶ added in v0.5.0
Compare compares str to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
type Term ¶
type Term struct { Value Value `json:"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 BooleanTerm ¶
BooleanTerm creates a new Term with a Boolean value.
func FloatNumberTerm ¶ added in v0.3.0
FloatNumberTerm creates a new Term with a floating point Number value.
func IntNumberTerm ¶ added in v0.3.0
IntNumberTerm creates a new Term with an integer Number 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 NumberTerm ¶
NumberTerm creates a new Term with a Number value.
func ObjectComprehensionTerm ¶ added in v0.5.2
ObjectComprehensionTerm creates a new Term with an ObjectComprehension 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 SetComprehensionTerm ¶ added in v0.5.2
SetComprehensionTerm creates a new Term with an SetComprehension value.
func StringTerm ¶
StringTerm creates a new Term with a String value.
func (*Term) Equal ¶
Equal returns true if this term equals the other term. Equality is defined for each kind of term.
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) SetLocation ¶ added in v0.5.0
SetLocation updates the term's Location and returns the term itself.
func (*Term) UnmarshalJSON ¶
UnmarshalJSON parses the byte array and stores the result in term. Specialized unmarshalling is required to handle Value.
type Transformer ¶ added in v0.2.0
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 TreeNode ¶ added in v0.5.0
TreeNode represents a node in the rule tree. The rule tree is keyed by rule path.
func NewFuncTree ¶ added in v0.5.0
func NewFuncTree(mtree *ModuleTreeNode) *TreeNode
NewFuncTree returns a new TreeNode that represents the root of the function tree populated with the given functions.
func NewRuleTree ¶ added in v0.2.0
func NewRuleTree(mtree *ModuleTreeNode) *TreeNode
NewRuleTree returns a new TreeNode that represents the root of the rule tree populated with the given rules.
func (*TreeNode) DepthFirst ¶ added in v0.5.0
DepthFirst performs a depth-first traversal of the rule tree rooted at n. If f returns true, traversal will not continue to the children of n.
type TypeEnv ¶ added in v0.4.9
type TypeEnv struct {
// contains filtered or unexported fields
}
TypeEnv contains type info for static analysis such as type checking.
type UnificationErrDetail ¶ added in v0.4.9
UnificationErrDetail describes a type mismatch error when two values are unified (e.g., x = [1,2,y]).
func (*UnificationErrDetail) Lines ¶ added in v0.4.9
func (a *UnificationErrDetail) Lines() []string
Lines returns the string representation of the detail.
type Value ¶
type Value interface { Compare(other Value) int // Compare returns <0, 0, or >0 if this Value is less than, equal to, or greater than other, respectively. Find(path Ref) (Value, error) // Find returns value referred to by path or an error if path is not found. Hash() int // Returns hash code of the value. IsGround() bool // IsGround returns true if this value is not a variable or contains no variables. String() string // String returns a human readable string representation of the value. }
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, Set - Variables, References - Array Comprehensions
func InterfaceToValue ¶
InterfaceToValue converts a native Go value x to a Value.
func MustInterfaceToValue ¶ added in v0.4.5
func MustInterfaceToValue(x interface{}) Value
MustInterfaceToValue converts a native Go value x to a Value. If the conversion fails, this function will panic. This function is mostly for test purposes.
type ValueMap ¶ added in v0.2.0
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 (*ValueMap) Iter ¶ added in v0.2.0
Iter calls the iter function for each key/value pair in the map. If the iter function returns true, iteration stops.
type ValueResolver ¶ added in v0.4.9
ValueResolver defines the interface for resolving references to AST values.
type Var ¶
type Var string
Var represents a variable as defined by the language.
func (Var) Compare ¶ added in v0.5.0
Compare compares v to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Var) Equal ¶
Equal returns true if the other Value is a Variable and has the same value (name).
func (Var) IsWildcard ¶ added in v0.2.0
IsWildcard returns true if this is a wildcard variable.
type VarSet ¶
type VarSet map[Var]struct{}
VarSet represents a set of 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) Equal ¶ added in v0.2.1
Equal returns true if s contains exactly the same elements as vs.
type VarVisitor ¶ added in v0.3.0
type VarVisitor struct {
// contains filtered or unexported fields
}
VarVisitor walks AST nodes under a given node and collects all encountered variables. The collected variables can be controlled by specifying VarVisitorParams when creating the visitor.
func NewVarVisitor ¶ added in v0.3.0
func NewVarVisitor() *VarVisitor
NewVarVisitor returns a new VarVisitor object.
func (*VarVisitor) Vars ¶ added in v0.3.0
func (vis *VarVisitor) Vars() VarSet
Vars returns a VarSet that contains collected vars.
func (*VarVisitor) Visit ¶ added in v0.3.0
func (vis *VarVisitor) Visit(v interface{}) Visitor
Visit is called to walk the AST node v.
func (*VarVisitor) WithParams ¶ added in v0.3.0
func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor
WithParams sets the parameters in params on vis.
type VarVisitorParams ¶ added in v0.3.0
type VarVisitorParams struct { SkipRefHead bool SkipObjectKeys bool SkipClosures bool SkipWithTarget bool SkipSets bool SkipFuncVars bool }
VarVisitorParams contains settings for a VarVisitor.
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.
type With ¶ added in v0.4.1
type With struct { Location *Location `json:"-"` Target *Term `json:"target"` Value *Term `json:"value"` }
With represents a modifier on an expression.
func (*With) Compare ¶ added in v0.4.1
Compare returns an integer indicating whether w is less than, equal to, or greater than other.