package ast
import "github.com/open-policy-agent/opa/v1/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 | Variable Declaration)
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.
nolint: deadcode // Public API.
Index ¶
- Constants
- Variables
- func As(v Value, x any) error
- func BuildAnnotationSet(modules []*Module) (*AnnotationSet, Errors)
- func Compare(a, b any) int
- func ContainsClosures(v any) bool
- func ContainsComprehensions(v any) bool
- func ContainsRefs(v any) bool
- func Copy(x any) any
- func HasInternedIntNumberTerm(i int) bool
- func InternStringTerm(str ...string)
- func IsComprehension(x Value) bool
- func IsConstant(v Value) bool
- func IsError(code string, err error) bool
- func IsFutureKeyword(s string) bool
- func IsFutureKeywordForRegoVersion(s string, v RegoVersion) bool
- func IsInKeywords(s string, keywords []string) bool
- func IsKeyword(s string) bool
- func IsKeywordInRegoVersion(s string, regoVersion RegoVersion) bool
- func IsScalar(v Value) bool
- func IsUnknownValueErr(err error) bool
- func IsValidImportPath(v Value) (err error)
- func IsVarCompatibleString(s string) bool
- func JSON(v Value) (any, error)
- func JSONWithOpt(v Value, opt JSONOpt) (any, error)
- func KeywordsForRegoVersion(v RegoVersion) []string
- func LoadCapabilitiesVersions() ([]string, error)
- func MustJSON(v Value) any
- func ParseStatements(filename, input string) ([]Statement, []*Comment, error)
- func ParseStatementsWithOpts(filename, input string, popts ParserOptions) ([]Statement, []*Comment, error)
- func Pretty(w io.Writer, x any)
- func RefCompare(a, b Ref) int
- func RefEqual(a, b Ref) bool
- func RegisterBuiltin(b *Builtin)
- func SetModuleRegoVersion(mod *Module, v RegoVersion)
- func TermValueCompare(a, b *Term) int
- func TermValueEqual(a, b *Term) bool
- func Transform(t Transformer, x any) (any, error)
- func TransformComprehensions(x any, f func(any) (Value, error)) (any, error)
- func TransformRefs(x any, f func(Ref) (Value, error)) (any, error)
- func TransformVars(x any, f func(Var) (Value, error)) (any, error)
- func TypeName(x any) string
- func ValueEqual(a, b Value) bool
- func ValueName(x Value) string
- func ValueToInterface(v Value, resolver Resolver) (any, error)
- func VarCompare(a, b Var) int
- func Walk(v Visitor, x any)
- func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any)
- func WalkBodies(x any, f func(Body) bool)
- func WalkClosures(x any, f func(any) bool)
- func WalkExprs(x any, f func(*Expr) bool)
- func WalkNodes(x any, f func(Node) bool)
- func WalkRefs(x any, f func(Ref) bool)
- func WalkRules(x any, f func(*Rule) bool)
- func WalkTerms(x any, f func(*Term) bool)
- func WalkVars(x any, f func(Var) bool)
- func WalkWiths(x any, f func(*With) bool)
- type AnnotationSet
- func (as *AnnotationSet) Chain(rule *Rule) AnnotationsRefSet
- func (as *AnnotationSet) Flatten() FlatAnnotationsRefSet
- func (as *AnnotationSet) GetDocumentScope(path Ref) *Annotations
- func (as *AnnotationSet) GetPackageScope(pkg *Package) *Annotations
- func (as *AnnotationSet) GetRuleScope(r *Rule) []*Annotations
- func (as *AnnotationSet) GetSubpackagesScope(path Ref) []*Annotations
- type Annotations
- func (a *Annotations) Compare(other *Annotations) int
- func (a *Annotations) Copy(node Node) *Annotations
- func (a *Annotations) EndLoc() *Location
- func (a *Annotations) GetTargetPath() Ref
- func (a *Annotations) Loc() *Location
- func (a *Annotations) MarshalJSON() ([]byte, error)
- func (a *Annotations) SetLoc(l *Location)
- func (a *Annotations) String() string
- type AnnotationsRef
- func NewAnnotationsRef(a *Annotations) *AnnotationsRef
- func (ar *AnnotationsRef) Compare(other *AnnotationsRef) int
- func (ar *AnnotationsRef) GetPackage() *Package
- func (ar *AnnotationsRef) GetRule() *Rule
- func (ar *AnnotationsRef) MarshalJSON() ([]byte, error)
- type AnnotationsRefSet
- type ArgErrDetail
- type Args
- func (a Args) Copy() Args
- func (a Args) Loc() *Location
- func (a Args) SetLoc(loc *Location)
- func (a Args) String() string
- func (a Args) Vars() VarSet
- type Array
- func NewArray(a ...*Term) *Array
- func (arr *Array) Append(v *Term) *Array
- func (arr *Array) Compare(other Value) int
- func (arr *Array) Copy() *Array
- func (arr *Array) Elem(i int) *Term
- func (arr *Array) Equal(other Value) bool
- func (arr *Array) Find(path Ref) (Value, error)
- func (arr *Array) Foreach(f func(*Term))
- func (arr *Array) Get(pos *Term) *Term
- func (arr *Array) Hash() int
- func (arr *Array) IsGround() bool
- func (arr *Array) Iter(f func(*Term) error) error
- func (arr *Array) Len() int
- func (arr *Array) MarshalJSON() ([]byte, error)
- func (arr *Array) Set(i int, v *Term)
- func (arr *Array) Slice(i, j int) *Array
- func (arr *Array) Sorted() *Array
- func (arr *Array) String() string
- func (arr *Array) Until(f func(*Term) bool) bool
- 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 AuthorAnnotation
- func (a *AuthorAnnotation) Compare(other *AuthorAnnotation) int
- func (a *AuthorAnnotation) Copy() *AuthorAnnotation
- func (a *AuthorAnnotation) String() string
- type BeforeAfterVisitor
- func NewBeforeAfterVisitor(before func(x any) bool, after func(x any)) *BeforeAfterVisitor
- func (vis *BeforeAfterVisitor) Walk(x any)
- type BeforeAndAfterVisitor
- type Body
- func MustParseBody(input string) Body
- func MustParseBodyWithOpts(input string, opts ParserOptions) Body
- func NewBody(exprs ...*Expr) Body
- func ParseBody(input string) (Body, error)
- func ParseBodyWithOpts(input string, popts ParserOptions) (Body, error)
- 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) MarshalJSON() ([]byte, error)
- func (body Body) Set(expr *Expr, pos int)
- func (body Body) SetLoc(loc *Location)
- func (body Body) String() string
- func (body Body) Vars(params VarVisitorParams) VarSet
- type Boolean
- func (bol Boolean) Compare(other Value) int
- func (bol Boolean) Equal(other Value) bool
- func (bol Boolean) Find(path Ref) (Value, error)
- func (bol Boolean) Hash() int
- func (Boolean) IsGround() bool
- func (bol Boolean) String() string
- type Builtin
- func (b *Builtin) Call(operands ...*Term) *Term
- func (b *Builtin) Expr(operands ...*Term) *Expr
- func (b *Builtin) IsDeprecated() bool
- func (b *Builtin) IsNondeterministic() bool
- func (b *Builtin) IsTargetPos(i int) bool
- func (b *Builtin) Minimal() *Builtin
- func (b *Builtin) Ref() Ref
- type Call
- func (c Call) Compare(other Value) int
- func (c Call) Copy() Call
- func (Call) Find(Ref) (Value, error)
- func (c Call) Hash() int
- func (c Call) IsGround() bool
- func (c Call) MakeExpr(output *Term) *Expr
- func (c Call) String() string
- type Capabilities
- func CapabilitiesForThisVersion(opts ...CapabilitiesOption) *Capabilities
- func LoadCapabilitiesFile(file string) (*Capabilities, error)
- func LoadCapabilitiesJSON(r io.Reader) (*Capabilities, error)
- func LoadCapabilitiesVersion(version string) (*Capabilities, error)
- func (c *Capabilities) ContainsFeature(feature string) bool
- func (c *Capabilities) MinimumCompatibleVersion() (string, bool)
- type CapabilitiesOption
- type CapabilitiesOptions
- type Comment
- func NewComment(text []byte) *Comment
- func (c *Comment) Copy() *Comment
- func (c *Comment) Equal(other *Comment) bool
- func (c *Comment) Loc() *Location
- func (c *Comment) SetLoc(loc *Location)
- func (c *Comment) String() string
- type CompileOpts
- type Compiler
- func CompileModules(modules map[string]string) (*Compiler, error)
- func CompileModulesWithOpt(modules map[string]string, opts CompileOpts) (*Compiler, error)
- func MustCompileModules(modules map[string]string) *Compiler
- func MustCompileModulesWithOpts(modules map[string]string, opts CompileOpts) *Compiler
- func NewCompiler() *Compiler
- func (c *Compiler) Capabilities() *Capabilities
- func (c *Compiler) Compile(modules map[string]*Module)
- func (c *Compiler) ComprehensionIndex(term *Term) *ComprehensionIndex
- func (c *Compiler) DefaultRegoVersion() RegoVersion
- func (c *Compiler) Failed() bool
- func (c *Compiler) GetAnnotationSet() *AnnotationSet
- func (c *Compiler) GetArity(ref Ref) int
- func (c *Compiler) GetRules(ref Ref) (rules []*Rule)
- func (c *Compiler) GetRulesDynamic(ref Ref) []*Rule
- func (c *Compiler) GetRulesDynamicWithOpts(ref Ref, opts RulesOptions) []*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) ParsedModules() map[string]*Module
- func (c *Compiler) PassesTypeCheck(body Body) bool
- func (c *Compiler) PassesTypeCheckRules(rules []*Rule) Errors
- func (c *Compiler) QueryCompiler() QueryCompiler
- func (c *Compiler) RuleIndex(path Ref) RuleIndex
- func (c *Compiler) SetErrorLimit(limit int) *Compiler
- func (c *Compiler) WithAllowUndefinedFunctionCalls(allow bool) *Compiler
- func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler
- func (c *Compiler) WithCapabilities(capabilities *Capabilities) *Compiler
- func (c *Compiler) WithDebug(sink io.Writer) *Compiler
- func (c *Compiler) WithDefaultRegoVersion(regoVersion RegoVersion) *Compiler
- func (c *Compiler) WithEnablePrintStatements(yes bool) *Compiler
- func (c *Compiler) WithEvalMode(e CompilerEvalMode) *Compiler
- func (c *Compiler) WithKeepModules(y bool) *Compiler
- func (c *Compiler) WithMetrics(metrics metrics.Metrics) *Compiler
- func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler
- func (c *Compiler) WithPathConflictsCheck(fn func([]string) (bool, error)) *Compiler
- func (c *Compiler) WithPathConflictsCheckRoots(rootPaths []string) *Compiler
- func (c *Compiler) WithRewriteTestRules(rewrite bool) *Compiler
- func (c *Compiler) WithSchemas(schemas *SchemaSet) *Compiler
- func (c *Compiler) WithStageAfter(after string, stage CompilerStageDefinition) *Compiler
- func (c *Compiler) WithStrict(strict bool) *Compiler
- func (c *Compiler) WithUnsafeBuiltins(unsafeBuiltins map[string]struct{}) *Compiler
- func (c *Compiler) WithUseTypeCheckAnnotations(enabled bool) *Compiler
- type CompilerEvalMode
- type CompilerStage
- type CompilerStageDefinition
- type ComprehensionIndex
- type DocKind
- type Error
- type ErrorDetails
- type Errors
- func CheckPathConflicts(c *Compiler, exists func([]string) (bool, error)) Errors
- func CheckRegoV1(x any) Errors
- func CheckRegoV1WithOptions(x any, opts RegoCheckOptions) Errors
- func (e Errors) Error() string
- func (e Errors) Sort()
- type Every
- func (q *Every) Compare(other *Every) int
- func (q *Every) Copy() *Every
- func (q *Every) KeyValueVars() VarSet
- func (q *Every) Loc() *Location
- func (q *Every) MarshalJSON() ([]byte, error)
- func (q *Every) SetLoc(l *Location)
- func (q *Every) String() string
- type Expr
- func MustParseExpr(input string) *Expr
- func NewBuiltinExpr(terms ...*Term) *Expr
- func NewExpr(terms any) *Expr
- func ParseExpr(input string) (*Expr, error)
- func (expr *Expr) BaseCogeneratedExpr() *Expr
- func (expr *Expr) CogeneratedExprs() []*Expr
- func (expr *Expr) Compare(other *Expr) int
- func (expr *Expr) Complement() *Expr
- func (expr *Expr) ComplementNoWith() *Expr
- func (expr *Expr) Copy() *Expr
- func (expr *Expr) CopyWithoutTerms() *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) IsAssignment() bool
- func (expr *Expr) IsCall() bool
- func (expr *Expr) IsEquality() bool
- func (expr *Expr) IsEvery() bool
- func (expr *Expr) IsGround() bool
- func (expr *Expr) IsSome() bool
- func (expr *Expr) Loc() *Location
- func (expr *Expr) MarshalJSON() ([]byte, error)
- func (expr *Expr) NoWith() *Expr
- func (expr *Expr) Operand(pos int) *Term
- func (expr *Expr) Operands() []*Term
- func (expr *Expr) Operator() Ref
- func (expr *Expr) OperatorTerm() *Term
- func (expr *Expr) SetLoc(loc *Location)
- func (expr *Expr) SetLocation(loc *Location) *Expr
- func (expr *Expr) SetOperator(term *Term) *Expr
- func (expr *Expr) String() string
- func (expr *Expr) UnmarshalJSON(bs []byte) error
- func (expr *Expr) Vars(params VarVisitorParams) VarSet
- type FlatAnnotationsRefSet
- type GenericTransformer
- func NewGenericTransformer(f func(x any) (any, error)) *GenericTransformer
- func (t *GenericTransformer) Transform(x any) (any, error)
- type GenericVisitor
- type Graph
- func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph
- func (g *Graph) Dependencies(x util.T) map[util.T]struct{}
- func (g *Graph) Dependents(x util.T) map[util.T]struct{}
- func (g *Graph) Sort() (sorted []util.T, ok bool)
- type GraphTraversal
- func NewGraphTraversal(graph *Graph) *GraphTraversal
- func (g *GraphTraversal) Edges(x util.T) []util.T
- func (g *GraphTraversal) Visited(u util.T) bool
- type Head
- func NewHead(name Var, args ...*Term) *Head
- func RefHead(ref Ref, args ...*Term) *Head
- func VarHead(name Var, location *Location, _ *astJSON.Options) *Head
- func (head *Head) Compare(other *Head) int
- func (head *Head) Copy() *Head
- func (head *Head) DocKind() DocKind
- func (head *Head) Equal(other *Head) bool
- func (head *Head) HasDynamicRef() bool
- func (head *Head) Loc() *Location
- func (head *Head) MarshalJSON() ([]byte, error)
- func (head *Head) Ref() Ref
- func (head *Head) RuleKind() RuleKind
- func (head *Head) SetLoc(loc *Location)
- func (head *Head) SetRef(r Ref)
- func (head *Head) String() string
- func (head *Head) Vars() VarSet
- type Import
- func MustParseImports(input string) []*Import
- func ParseImports(input string) ([]*Import, error)
- func (imp *Import) Compare(other *Import) int
- func (imp *Import) Copy() *Import
- func (imp *Import) Equal(other *Import) bool
- func (imp *Import) Loc() *Location
- func (imp *Import) MarshalJSON() ([]byte, error)
- func (imp *Import) Name() Var
- func (imp *Import) SetLoc(loc *Location)
- func (imp *Import) String() string
- type IndexResult
- type JSONOpt
- type Location
- type Module
- func MustParseModule(input string) *Module
- func MustParseModuleWithOpts(input string, opts ParserOptions) *Module
- func ParseModule(filename, input string) (*Module, error)
- func ParseModuleWithOpts(filename, input string, popts ParserOptions) (*Module, error)
- func (mod *Module) Compare(other *Module) int
- func (mod *Module) Copy() *Module
- func (mod *Module) Equal(other *Module) bool
- func (mod *Module) RegoVersion() RegoVersion
- func (mod *Module) RuleSet(name Var) RuleSet
- func (mod *Module) SetRegoVersion(v RegoVersion)
- func (mod *Module) String() string
- func (mod *Module) UnmarshalJSON(bs []byte) error
- type ModuleLoader
- type ModuleTreeNode
- func NewModuleTree(mods map[string]*Module) *ModuleTreeNode
- func (n *ModuleTreeNode) DepthFirst(f func(*ModuleTreeNode) bool)
- func (n *ModuleTreeNode) Size() int
- func (n *ModuleTreeNode) String() string
- type Node
- type Null
- func (Null) Compare(other Value) int
- func (Null) Equal(other Value) bool
- func (Null) Find(path Ref) (Value, error)
- func (Null) Hash() int
- func (Null) IsGround() bool
- func (Null) String() string
- 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) Float64() (float64, bool)
- func (num Number) Hash() int
- func (num Number) Int() (int, bool)
- func (num Number) Int64() (int64, bool)
- func (Number) IsGround() bool
- func (num Number) MarshalJSON() ([]byte, error)
- func (num Number) String() string
- type Object
- 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 ObjectKeysIterator
- type Package
- func MustParsePackage(input string) *Package
- func ParsePackage(input string) (*Package, error)
- func (pkg *Package) Compare(other *Package) int
- func (pkg *Package) Copy() *Package
- func (pkg *Package) Equal(other *Package) bool
- func (pkg *Package) Loc() *Location
- func (pkg *Package) MarshalJSON() ([]byte, error)
- func (pkg *Package) SetLoc(loc *Location)
- func (pkg *Package) String() string
- type Parser
- func NewParser() *Parser
- func (p *Parser) Parse() ([]Statement, []*Comment, Errors)
- func (p *Parser) WithAllFutureKeywords(yes bool) *Parser
- func (p *Parser) WithCapabilities(c *Capabilities) *Parser
- func (p *Parser) WithFilename(filename string) *Parser
- func (p *Parser) WithFutureKeywords(kws ...string) *Parser
- func (p *Parser) WithJSONOptions(_ *astJSON.Options) *Parser
- func (p *Parser) WithMaxRecursionDepth(depth int) *Parser
- func (p *Parser) WithProcessAnnotation(processAnnotation bool) *Parser
- func (p *Parser) WithReader(r io.Reader) *Parser
- func (p *Parser) WithRegoVersion(version RegoVersion) *Parser
- func (p *Parser) WithSkipRules(skip bool) *Parser
- type ParserErrorDetail
- type ParserOptions
- type QueryCompiler
- type QueryCompilerStage
- type QueryCompilerStageDefinition
- type QueryContext
- func NewQueryContext() *QueryContext
- func (qc *QueryContext) Copy() *QueryContext
- func (qc *QueryContext) WithImports(imports []*Import) *QueryContext
- func (qc *QueryContext) WithPackage(pkg *Package) *QueryContext
- type QueryIterator
- type Ref
- func EmptyRef() Ref
- func MustParseRef(input string) Ref
- func ParseRef(input string) (Ref, error)
- func PtrRef(head *Term, s string) (Ref, error)
- func (ref Ref) Append(term *Term) Ref
- func (ref Ref) Compare(other Value) int
- func (ref Ref) Concat(terms []*Term) Ref
- func (ref Ref) ConstantPrefix() Ref
- func (ref Ref) Copy() Ref
- func (ref Ref) CopyNonGround() Ref
- func (ref Ref) Dynamic() int
- func (ref Ref) DynamicSuffix() Ref
- 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) Insert(x *Term, pos int) Ref
- func (ref Ref) IsGround() bool
- func (ref Ref) IsNested() bool
- func (ref Ref) OutputVars() VarSet
- func (ref Ref) Ptr() (string, error)
- func (ref Ref) String() string
- func (ref Ref) StringPrefix() Ref
- type RefErrInvalidDetail
- type RefErrUnsupportedDetail
- type RegoCheckOptions
- type RegoVersion
- func RegoVersionFromInt(i int) RegoVersion
- func (v RegoVersion) Int() int
- func (v RegoVersion) String() string
- type RelatedResourceAnnotation
- func (rr *RelatedResourceAnnotation) Compare(other *RelatedResourceAnnotation) int
- func (rr *RelatedResourceAnnotation) Copy() *RelatedResourceAnnotation
- func (rr *RelatedResourceAnnotation) MarshalJSON() ([]byte, error)
- func (rr *RelatedResourceAnnotation) String() string
- type Resolver
- type Rule
- func MustParseRule(input string) *Rule
- func MustParseRuleWithOpts(input string, opts ParserOptions) *Rule
- func ParseCompleteDocRuleFromAssignmentExpr(module *Module, lhs, rhs *Term) (*Rule, error)
- func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)
- func ParseCompleteDocRuleWithDotsFromTerm(module *Module, term *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 ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)
- func ParseRuleFromCallExpr(module *Module, terms []*Term) (*Rule, error)
- func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error)
- func ParseRuleWithOpts(input string, opts ParserOptions) (*Rule, error)
- func (rule *Rule) Compare(other *Rule) int
- func (rule *Rule) Copy() *Rule
- func (rule *Rule) Equal(other *Rule) bool
- func (rule *Rule) Loc() *Location
- func (rule *Rule) MarshalJSON() ([]byte, error)
- func (rule *Rule) Path() Ref
- func (rule *Rule) Ref() Ref
- func (rule *Rule) SetLoc(loc *Location)
- func (rule *Rule) String() string
- type RuleIndex
- type RuleKind
- type RuleSet
- func NewRuleSet(rules ...*Rule) RuleSet
- func (rs *RuleSet) Add(rule *Rule)
- func (rs RuleSet) Contains(rule *Rule) bool
- func (rs RuleSet) Diff(other RuleSet) RuleSet
- func (rs RuleSet) Equal(other RuleSet) bool
- func (rs RuleSet) Merge(other RuleSet) RuleSet
- func (rs RuleSet) String() string
- type RulesOptions
- type SchemaAnnotation
- func (s *SchemaAnnotation) Compare(other *SchemaAnnotation) int
- func (s *SchemaAnnotation) Copy() *SchemaAnnotation
- func (s *SchemaAnnotation) String() string
- type SchemaSet
- func NewSchemaSet() *SchemaSet
- func (ss *SchemaSet) Get(path Ref) any
- func (ss *SchemaSet) Put(path Ref, raw any)
- type 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 SomeDecl
- func (d *SomeDecl) Compare(other *SomeDecl) int
- func (d *SomeDecl) Copy() *SomeDecl
- func (d *SomeDecl) Hash() int
- func (d *SomeDecl) Loc() *Location
- func (d *SomeDecl) MarshalJSON() ([]byte, error)
- func (d *SomeDecl) SetLoc(loc *Location)
- func (d *SomeDecl) String() string
- type Statement
- func MustParseStatement(input string) Statement
- func MustParseStatementWithOpts(input string, popts ParserOptions) Statement
- func MustParseStatements(input string) []Statement
- func ParseStatement(input string) (Statement, error)
- func ParseStatementWithOpts(input string, popts ParserOptions) (Statement, error)
- type String
- func (str String) Compare(other Value) int
- func (str String) Equal(other Value) bool
- func (str String) Find(path Ref) (Value, error)
- func (str String) Hash() int
- func (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 CallTerm(terms ...*Term) *Term
- func FloatNumberTerm(f float64) *Term
- func IntNumberTerm(i int) *Term
- func InternedBooleanTerm(b bool) *Term
- func InternedIntNumberTerm(i int) *Term
- func InternedIntNumberTermFromString(s string) *Term
- func InternedIntegerString(i int) *Term
- func InternedStringTerm(s string) *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 UIntNumberTerm(u uint64) *Term
- func VarTerm(v string) *Term
- func (term *Term) Copy() *Term
- func (term *Term) Equal(other *Term) bool
- func (term *Term) Get(name *Term) *Term
- func (term *Term) Hash() int
- func (term *Term) IsGround() bool
- func (term *Term) Loc() *Location
- func (term *Term) MarshalJSON() ([]byte, error)
- func (term *Term) SetLoc(loc *Location)
- 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
- func NewRuleTree(mtree *ModuleTreeNode) *TreeNode
- func (n *TreeNode) Child(k Value) *TreeNode
- func (n *TreeNode) DepthFirst(f func(*TreeNode) bool)
- func (n *TreeNode) Find(ref Ref) *TreeNode
- func (n *TreeNode) Size() int
- func (n *TreeNode) String() string
- type TypeEnv
- func (env *TypeEnv) Get(x any) types.Type
- func (env *TypeEnv) GetByRef(ref Ref) types.Type
- func (env *TypeEnv) GetByValue(v Value) types.Type
- type UnificationErrDetail
- type UnknownValueErr
- type Value
- func InterfaceToValue(x any) (Value, error)
- func MustInterfaceToValue(x any) Value
- func ValueFromReader(r io.Reader) (Value, error)
- type ValueMap
- func NewValueMap() *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) MarshalJSON() ([]byte, error)
- func (vs *ValueMap) Put(k, v Value)
- func (vs *ValueMap) String() string
- type ValueResolver
- type Var
- func (v Var) Compare(other Value) int
- func (v Var) Equal(other Value) bool
- func (v Var) Find(path Ref) (Value, error)
- func (v Var) Hash() int
- func (v Var) IsGenerated() bool
- func (Var) IsGround() bool
- func (v Var) IsWildcard() bool
- func (v Var) String() string
- type VarSet
- func NewVarSet(vs ...Var) VarSet
- func NewVarSetOfSize(size int) VarSet
- func OutputVarsFromBody(c *Compiler, body Body, safe VarSet) VarSet
- func OutputVarsFromExpr(c *Compiler, expr *Expr, safe VarSet) 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) Equal(vs VarSet) bool
- func (s VarSet) Intersect(vs VarSet) VarSet
- func (s VarSet) Sorted() []Var
- func (s VarSet) String() string
- func (s VarSet) Update(vs VarSet)
- type VarVisitor
- func NewVarVisitor() *VarVisitor
- func (vis *VarVisitor) Vars() VarSet
- func (vis *VarVisitor) Walk(x any)
- func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor
- type VarVisitorParams
- type VersionIndex
- type Visitor
- type WasmABIVersion
- type With
- func (w *With) Compare(other *With) int
- func (w *With) Copy() *With
- func (w *With) Equal(other *With) bool
- func (w With) Hash() int
- func (w *With) Loc() *Location
- func (w *With) MarshalJSON() ([]byte, error)
- func (w *With) SetLoc(loc *Location)
- func (w *With) SetLocation(loc *Location) *With
- func (w *With) String() string
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" // FormatErr indicates an error occurred during formatting. FormatErr = "rego_format_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 // PartialObjectDoc represents an object document that is partially defined by the rule. PartialObjectDoc )
const ( SingleValue = iota MultiValue )
const CompileErrorLimitDefault = 10
CompileErrorLimitDefault is the default number errors a compiler will allow before exiting.
const DefaultMaxParsingRecursionDepth = 100000
DefaultMaxParsingRecursionDepth is the default maximum recursion depth for the parser
const DefaultRegoVersion = RegoV1
const FeatureRefHeadStringPrefixes = "rule_head_ref_string_prefixes"
In the compiler, we used this to check that we're OK working with ref heads. If this isn't present, we'll fail. This is to ensure that older versions of OPA can work with policies that we're compiling -- if they don't know ref heads, they wouldn't be able to parse them.
const FeatureRefHeads = "rule_head_refs"
const FeatureRegoV1 = "rego_v1"
const FeatureRegoV1Import = "rego_v1_import"
const LocalVarPrefix = "__local"
TODO: Move to internal package?
const SystemDocumentKey = String("system")
SystemDocumentKey is the name of the top-level key that identifies the system document.
const WildcardPrefix = "$"
WildcardPrefix is the special character that all wildcard variables are prefixed with when the statement they are contained in is parsed.
Variables ¶
var ( InternedNullTerm = &Term{Value: Null{}} InternedEmptyString = StringTerm("") InternedEmptyObject = ObjectTerm() InternedEmptyArray = ArrayTerm() InternedEmptySet = SetTerm() InternedEmptyArrayValue = NewArray() )
var Abs = &Builtin{ Name: "abs", Description: "Returns the number without its sign.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the number to take the absolute value of"), ), types.Named("y", types.N).Description("the absolute value of `x`"), ), Categories: number, }
var AddDate = &Builtin{ Name: "time.add_date", Description: "" /* 325 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("ns", types.N).Description("nanoseconds since the epoch"), types.Named("years", types.N).Description("number of years to add"), types.Named("months", types.N).Description("number of months to add"), types.Named("days", types.N).Description("number of days to add"), ), types.Named("output", types.N).Description("nanoseconds since the epoch representing the input time, with years, months and days added"), ), }
var All = &Builtin{ Name: "all", Decl: types.NewFunction( types.Args( types.NewAny( types.SetOfAny, types.NewArray(nil, types.A), ), ), types.B, ), deprecated: true, }
All takes a list and returns true if all of the items are true. A collection of length 0 returns true.
var And = &Builtin{ Name: "and", Infix: "&", Description: "Returns the intersection of two sets.", Decl: types.NewFunction( types.Args( types.Named("x", types.SetOfAny).Description("the first set"), types.Named("y", types.SetOfAny).Description("the second set"), ), types.Named("z", types.SetOfAny).Description("the intersection of `x` and `y`"), ), Categories: sets, }
var Any = &Builtin{ Name: "any", Decl: types.NewFunction( types.Args( types.NewAny( types.SetOfAny, types.NewArray(nil, types.A), ), ), types.B, ), deprecated: true, }
Any takes a collection and returns true if any of the items is true. A collection of length 0 returns false.
var AnyPrefixMatch = &Builtin{ Name: "strings.any_prefix_match", Description: "Returns true if any of the search strings begins with any of the base strings.", Decl: types.NewFunction( types.Args( types.Named("search", types.NewAny( types.S, types.SetOfStr, types.NewArray(nil, types.S), )).Description("search string(s)"), types.Named("base", types.NewAny( types.S, types.SetOfStr, types.NewArray(nil, types.S), )).Description("base string(s)"), ), types.Named("result", types.B).Description("result of the prefix check"), ), Categories: stringsCat, }
var AnySuffixMatch = &Builtin{ Name: "strings.any_suffix_match", Description: "Returns true if any of the search strings ends with any of the base strings.", Decl: types.NewFunction( types.Args( types.Named("search", types.NewAny( types.S, types.SetOfStr, types.NewArray(nil, types.S), )).Description("search string(s)"), types.Named("base", types.NewAny( types.S, types.SetOfStr, types.NewArray(nil, types.S), )).Description("base string(s)"), ), types.Named("result", types.B).Description("result of the suffix check"), ), Categories: stringsCat, }
var ArrayConcat = &Builtin{ Name: "array.concat", Description: "Concatenates two arrays.", Decl: types.NewFunction( types.Args( types.Named("x", types.NewArray(nil, types.A)).Description("the first array"), types.Named("y", types.NewArray(nil, types.A)).Description("the second array"), ), types.Named("z", types.NewArray(nil, types.A)).Description("the concatenation of `x` and `y`"), ), }
var ArrayReverse = &Builtin{ Name: "array.reverse", Description: "Returns the reverse of a given array.", Decl: types.NewFunction( types.Args( types.Named("arr", types.NewArray(nil, types.A)).Description("the array to be reversed"), ), types.Named("rev", types.NewArray(nil, types.A)).Description("an array containing the elements of `arr` in reverse order"), ), }
var ArraySlice = &Builtin{ Name: "array.slice", Description: "Returns a slice of a given array. If `start` is greater or equal than `stop`, `slice` is `[]`.", Decl: types.NewFunction( types.Args( types.Named("arr", types.NewArray(nil, types.A)).Description("the array to be sliced"), types.Named("start", types.N).Description("the start index of the returned slice; if less than zero, it's clamped to 0"), types.Named("stop", types.N).Description("the stop index of the returned slice; if larger than `count(arr)`, it's clamped to `count(arr)`"), ), types.Named("slice", types.NewArray(nil, types.A)).Description("the subslice of `array`, from `start` to `end`, including `arr[start]`, but excluding `arr[end]`"), ), } // NOTE(sr): this function really needs examples
var Assign = &Builtin{ Name: "assign", Infix: ":=", Decl: types.NewFunction( types.Args(types.A, types.A), types.B, ), }
Assign represents the assignment (":=") operator.
var Base64Decode = &Builtin{ Name: "base64.decode", Description: "Deserializes the base64 encoded input string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to decode"), ), types.Named("y", types.S).Description("base64 deserialization of `x`"), ), Categories: encoding, }
var Base64Encode = &Builtin{ Name: "base64.encode", Description: "Serializes the input string into base64 encoding.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("base64 serialization of `x`"), ), Categories: encoding, }
var Base64IsValid = &Builtin{ Name: "base64.is_valid", Description: "Verifies the input string is base64 encoded.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to check"), ), types.Named("result", types.B).Description("`true` if `x` is valid base64 encoded value, `false` otherwise"), ), Categories: encoding, }
var Base64UrlDecode = &Builtin{ Name: "base64url.decode", Description: "Deserializes the base64url encoded input string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to decode"), ), types.Named("y", types.S).Description("base64url deserialization of `x`"), ), Categories: encoding, }
var Base64UrlEncode = &Builtin{ Name: "base64url.encode", Description: "Serializes the input string into base64url encoding.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("base64url serialization of `x`"), ), Categories: encoding, }
var Base64UrlEncodeNoPad = &Builtin{ Name: "base64url.encode_no_pad", Description: "Serializes the input string into base64url encoding without padding.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("base64url serialization of `x`"), ), Categories: encoding, }
var BitsAnd = &Builtin{ Name: "bits.and", Description: "Returns the bitwise \"AND\" of two integers.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the first integer"), types.Named("y", types.N).Description("the second integer"), ), types.Named("z", types.N).Description("the bitwise AND of `x` and `y`"), ), }
var BitsNegate = &Builtin{ Name: "bits.negate", Description: "Returns the bitwise negation (flip) of an integer.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the integer to negate"), ), types.Named("z", types.N).Description("the bitwise negation of `x`"), ), }
var BitsOr = &Builtin{ Name: "bits.or", Description: "Returns the bitwise \"OR\" of two integers.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the first integer"), types.Named("y", types.N).Description("the second integer"), ), types.Named("z", types.N).Description("the bitwise OR of `x` and `y`"), ), }
var BitsShiftLeft = &Builtin{ Name: "bits.lsh", Description: "Returns a new integer with its bits shifted `s` bits to the left.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the integer to shift"), types.Named("s", types.N).Description("the number of bits to shift"), ), types.Named("z", types.N).Description("the result of shifting `x` `s` bits to the left"), ), }
var BitsShiftRight = &Builtin{ Name: "bits.rsh", Description: "Returns a new integer with its bits shifted `s` bits to the right.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the integer to shift"), types.Named("s", types.N).Description("the number of bits to shift"), ), types.Named("z", types.N).Description("the result of shifting `x` `s` bits to the right"), ), }
var BitsXOr = &Builtin{ Name: "bits.xor", Description: "Returns the bitwise \"XOR\" (exclusive-or) of two integers.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the first integer"), types.Named("y", types.N).Description("the second integer"), ), types.Named("z", types.N).Description("the bitwise XOR of `x` and `y`"), ), }
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 CastArray = &Builtin{ Name: "cast_array", Decl: types.NewFunction( types.Args(types.A), types.NewArray(nil, types.A), ), deprecated: true, }
CastArray checks the underlying type of the input. If it is array or set, an array containing the values is returned. If it is not an array, an error is thrown.
var CastBoolean = &Builtin{ Name: "cast_boolean", Decl: types.NewFunction( types.Args(types.A), types.B, ), deprecated: true, }
CastBoolean returns input if it is a boolean; if not returns error.
var CastNull = &Builtin{ Name: "cast_null", Decl: types.NewFunction( types.Args(types.A), types.NewNull(), ), deprecated: true, }
CastNull returns null if input is null; if not returns error.
var CastObject = &Builtin{ Name: "cast_object", Decl: types.NewFunction( types.Args(types.A), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), ), deprecated: true, }
CastObject returns the given object if it is null; throws an error otherwise
var CastSet = &Builtin{ Name: "cast_set", Decl: types.NewFunction( types.Args(types.A), types.SetOfAny, ), deprecated: true, }
CastSet checks the underlying type of the input. If it is a set, the set is returned. If it is an array, the array is returned in set form (all duplicates removed) If neither, an error is thrown
var CastString = &Builtin{ Name: "cast_string", Decl: types.NewFunction( types.Args(types.A), types.S, ), deprecated: true, }
CastString returns input if it is a string; if not returns error. For formatting variables, see sprintf
var Ceil = &Builtin{ Name: "ceil", Description: "Rounds the number _up_ to the nearest integer.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the number to round"), ), types.Named("y", types.N).Description("the result of rounding `x` _up_"), ), Categories: number, }
var Clock = &Builtin{ Name: "time.clock", Description: "Returns the `[hour, minute, second]` of the day for the nanoseconds since epoch.", Decl: types.NewFunction( types.Args( types.Named("x", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), )).Description("a number representing the nanoseconds since the epoch (UTC); or a two-element array of the nanoseconds, and a timezone string"), ), types.Named("output", types.NewArray([]types.Type{types.N, types.N, types.N}, nil)). Description("" /* 145 byte string literal not displayed */), ), }
var Concat = &Builtin{ Name: "concat", Description: "Joins a set or array of strings with a delimiter.", Decl: types.NewFunction( types.Args( types.Named("delimiter", types.S).Description("string to use as a delimiter"), types.Named("collection", types.NewAny( types.SetOfStr, types.NewArray(nil, types.S), )).Description("strings to join"), ), types.Named("output", types.S).Description("the joined string"), ), Categories: stringsCat, }
var Contains = &Builtin{ Name: "contains", Description: "Returns `true` if the search string is included in the base string", Decl: types.NewFunction( types.Args( types.Named("haystack", types.S).Description("string to search in"), types.Named("needle", types.S).Description("substring to look for"), ), types.Named("result", types.B).Description("result of the containment check"), ), Categories: stringsCat, }
var Count = &Builtin{ Name: "count", Description: " Count takes a collection or string and returns the number of elements (or characters) in it.", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.SetOfAny, types.NewArray(nil, types.A), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.S, )).Description("the set/array/object/string to be counted"), ), types.Named("n", types.N).Description("the count of elements, key/val pairs, or characters, respectively."), ), Categories: aggregates, }
var CryptoHmacEqual = &Builtin{ Name: "crypto.hmac.equal", Description: "Returns a boolean representing the result of comparing two MACs for equality without leaking timing information.", Decl: types.NewFunction( types.Args( types.Named("mac1", types.S).Description("mac1 to compare"), types.Named("mac2", types.S).Description("mac2 to compare"), ), types.Named("result", types.B).Description("`true` if the MACs are equals, `false` otherwise"), ), }
var CryptoHmacMd5 = &Builtin{ Name: "crypto.hmac.md5", Description: "Returns a string representing the MD5 HMAC of the input message using the input key.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), types.Named("key", types.S).Description("key to use"), ), types.Named("y", types.S).Description("MD5-HMAC of `x`"), ), }
var CryptoHmacSha1 = &Builtin{ Name: "crypto.hmac.sha1", Description: "Returns a string representing the SHA1 HMAC of the input message using the input key.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), types.Named("key", types.S).Description("key to use"), ), types.Named("y", types.S).Description("SHA1-HMAC of `x`"), ), }
var CryptoHmacSha256 = &Builtin{ Name: "crypto.hmac.sha256", Description: "Returns a string representing the SHA256 HMAC of the input message using the input key.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), types.Named("key", types.S).Description("key to use"), ), types.Named("y", types.S).Description("SHA256-HMAC of `x`"), ), }
var CryptoHmacSha512 = &Builtin{ Name: "crypto.hmac.sha512", Description: "Returns a string representing the SHA512 HMAC of the input message using the input key.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), types.Named("key", types.S).Description("key to use"), ), types.Named("y", types.S).Description("SHA512-HMAC of `x`"), ), }
var CryptoMd5 = &Builtin{ Name: "crypto.md5", Description: "Returns a string representing the input string hashed with the MD5 function", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), ), types.Named("y", types.S).Description("MD5-hash of `x`"), ), }
var CryptoParsePrivateKeys = &Builtin{ Name: "crypto.parse_private_keys", Description: "" /* 304 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("keys", types.S).Description("PEM encoded data containing one or more private keys as concatenated blocks. Optionally Base64 encoded."), ), types.Named("output", types.NewArray(nil, types.NewObject(nil, types.NewDynamicProperty(types.S, types.A)))).Description("parsed private keys represented as objects"), ), }
var CryptoSha1 = &Builtin{ Name: "crypto.sha1", Description: "Returns a string representing the input string hashed with the SHA1 function", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), ), types.Named("y", types.S).Description("SHA1-hash of `x`"), ), }
var CryptoSha256 = &Builtin{ Name: "crypto.sha256", Description: "Returns a string representing the input string hashed with the SHA256 function", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("input string"), ), types.Named("y", types.S).Description("SHA256-hash of `x`"), ), }
var CryptoX509ParseAndVerifyCertificates = &Builtin{ Name: "crypto.x509.parse_and_verify_certificates", Description: "" /* 337 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("certs", types.S).Description("" /* 166 byte string literal not displayed */), ), types.Named("output", types.NewArray([]types.Type{ types.B, types.NewArray(nil, types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))), }, nil)).Description("" /* 267 byte string literal not displayed */), ), }
var CryptoX509ParseAndVerifyCertificatesWithOptions = &Builtin{ Name: "crypto.x509.parse_and_verify_certificates_with_options", Description: "" /* 437 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("certs", types.S).Description("" /* 166 byte string literal not displayed */), types.Named("options", types.NewObject( nil, types.NewDynamicProperty(types.S, types.A), )).Description("" /* 824 byte string literal not displayed */), ), types.Named("output", types.NewArray([]types.Type{ types.B, types.NewArray(nil, types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))), }, nil)).Description("" /* 267 byte string literal not displayed */), ), }
var CryptoX509ParseCertificateRequest = &Builtin{ Name: "crypto.x509.parse_certificate_request", Description: "Returns a PKCS #10 certificate signing request from the given PEM-encoded PKCS#10 certificate signing request.", Decl: types.NewFunction( types.Args( types.Named("csr", types.S).Description("base64 string containing either a PEM encoded or DER CSR or a string containing a PEM CSR"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("X.509 CSR represented as an object"), ), }
var CryptoX509ParseCertificates = &Builtin{ Name: "crypto.x509.parse_certificates", Description: "" /* 304 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("certs", types.S).Description("base64 encoded DER or PEM data containing one or more certificates or a PEM string of one or more certificates"), ), types.Named("output", types.NewArray(nil, types.NewObject(nil, types.NewDynamicProperty(types.S, types.A)))).Description("parsed X.509 certificates represented as objects"), ), }
var CryptoX509ParseKeyPair = &Builtin{ Name: "crypto.x509.parse_keypair", Description: "Returns a valid key pair", Decl: types.NewFunction( types.Args( types.Named("cert", types.S).Description("string containing PEM or base64 encoded DER certificates"), types.Named("pem", types.S).Description("string containing PEM or base64 encoded DER keys"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("" /* 167 byte string literal not displayed */), ), }
var CryptoX509ParseRSAPrivateKey = &Builtin{ Name: "crypto.x509.parse_rsa_private_key", Description: "Returns a JWK for signing a JWT from the given PEM-encoded RSA private key.", Decl: types.NewFunction( types.Args( types.Named("pem", types.S).Description("base64 string containing a PEM encoded RSA private key"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("JWK as an object"), ), }
var Date = &Builtin{ Name: "time.date", Description: "Returns the `[year, month, day]` for the nanoseconds since epoch.", Decl: types.NewFunction( types.Args( types.Named("x", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), )).Description("a number representing the nanoseconds since the epoch (UTC); or a two-element array of the nanoseconds, and a timezone string"), ), types.Named("date", types.NewArray([]types.Type{types.N, types.N, types.N}, nil)).Description("an array of `year`, `month` (1-12), and `day` (1-31)"), ), }
var DefaultBuiltins = [...]*Builtin{ /* 200 elements not displayed */ }
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 Diff = &Builtin{ Name: "time.diff", Description: "Returns the difference between two unix timestamps in nanoseconds (with optional timezone strings).", Decl: types.NewFunction( types.Args( types.Named("ns1", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), )).Description("nanoseconds since the epoch; or a two-element array of the nanoseconds, and a timezone string"), types.Named("ns2", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), )).Description("nanoseconds since the epoch; or a two-element array of the nanoseconds, and a timezone string"), ), types.Named("output", types.NewArray([]types.Type{types.N, types.N, types.N, types.N, types.N, types.N}, nil)).Description("" /* 157 byte string literal not displayed */), ), }
var Divide = &Builtin{ Name: "div", Infix: "/", Description: "Divides the first number by the second number.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the dividend"), types.Named("y", types.N).Description("the divisor"), ), types.Named("z", types.N).Description("the result of `x` divided by `y`"), ), Categories: number, }
var EndsWith = &Builtin{ Name: "endswith", Description: "Returns true if the search string ends with the base string.", Decl: types.NewFunction( types.Args( types.Named("search", types.S).Description("search string"), types.Named("base", types.S).Description("base string"), ), types.Named("result", types.B).Description("result of the suffix check"), ), Categories: stringsCat, }
var Equal = &Builtin{ Name: "equal", Infix: "==", Categories: comparison, Decl: types.NewFunction( types.Args( types.Named("x", types.A), types.Named("y", types.A), ), types.Named("result", types.B).Description("true if `x` is equal to `y`; false otherwise"), ), }
Equal represents the "==" comparison operator.
var Equality = &Builtin{ Name: "eq", Infix: "=", Decl: types.NewFunction( types.Args(types.A, types.A), types.B, ), }
Equality represents the "=" operator.
ErrMaxParsingRecursionDepthExceeded is returned when the parser recursion exceeds the maximum allowed depth
var Floor = &Builtin{ Name: "floor", Description: "Rounds the number _down_ to the nearest integer.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the number to round"), ), types.Named("y", types.N).Description("the result of rounding `x` _down_"), ), Categories: number, }
var Format = &Builtin{ Name: "time.format", Description: "Returns the formatted timestamp for the nanoseconds since epoch.", Decl: types.NewFunction( types.Args( types.Named("x", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), types.NewArray([]types.Type{types.N, types.S, types.S}, nil), )).Description("" /* 270 byte string literal not displayed */), ), types.Named("formatted timestamp", types.S).Description("the formatted timestamp represented for the nanoseconds since the epoch in the supplied timezone (or UTC)"), ), }
var FormatInt = &Builtin{ Name: "format_int", Description: "Returns the string representation of the number in the given base after rounding it down to an integer value.", Decl: types.NewFunction( types.Args( types.Named("number", types.N).Description("number to format"), types.Named("base", types.N).Description("base of number representation to use"), ), types.Named("output", types.S).Description("formatted number"), ), Categories: stringsCat, }
var FunctionArgRootDocument = VarTerm("args")
FunctionArgRootDocument names the document containing function arguments. It's only for internal usage, for referencing function arguments between the index and topdown.
var FutureRootDocument = VarTerm("future")
FutureRootDocument names the document containing new, to-become-default, features.
var GlobMatch = &Builtin{ Name: "glob.match", Description: "Parses and matches strings against the glob notation. Not to be confused with `regex.globs_match`.", Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("glob pattern"), types.Named("delimiters", types.NewAny( types.NewArray(nil, types.S), types.NewNull(), )).Description("" /* 138 byte string literal not displayed */), types.Named("match", types.S).Description("string to match against `pattern`"), ), types.Named("result", types.B).Description("true if `match` can be found in `pattern` which is separated by `delimiters`"), ), }
var GlobQuoteMeta = &Builtin{ Name: "glob.quote_meta", Description: "Returns a string which represents a version of the pattern where all asterisks have been escaped.", Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("glob pattern"), ), types.Named("output", types.S).Description("the escaped string of `pattern`"), ), }
var GlobsMatch = &Builtin{ Name: "regex.globs_match", Description: "" /* 172 byte string literal not displayed */+ "`.`, `*`, `+`, `[`, `-`, `]` and `\\` are treated as special symbols.", Decl: types.NewFunction( types.Args( types.Named("glob1", types.S).Description("first glob-style regular expression"), types.Named("glob2", types.S).Description("second glob-style regular expression"), ), types.Named("result", types.B).Description("true if the intersection of `glob1` and `glob2` matches a non-empty set of non-empty strings"), ), }
GlobsMatch takes two strings regexp-style strings and evaluates to true if their intersection matches a non-empty set of non-empty strings. Examples:
- "a.a." and ".b.b" -> true.
- "[a-z]*" and [0-9]+" -> not true.
var GraphQLIsValid = &Builtin{ Name: "graphql.is_valid", Description: "" /* 173 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the GraphQL query"), types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the GraphQL schema"), ), types.Named("output", types.B).Description("`true` if the query is valid under the given schema. `false` otherwise."), ), }
GraphQLIsValid returns true if a GraphQL query is valid with a given schema, and returns false for all other inputs.
var GraphQLParse = &Builtin{ Name: "graphql.parse", Description: "" /* 291 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the GraphQL query"), types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the GraphQL schema"), ), types.Named("output", types.NewArray([]types.Type{ types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), }, nil)).Description("" /* 201 byte string literal not displayed */), ), }
GraphQLParse returns a pair of AST objects from parsing/validation.
var GraphQLParseAndVerify = &Builtin{ Name: "graphql.parse_and_verify", Description: "" /* 270 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("query", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the GraphQL query"), types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the GraphQL schema"), ), types.Named("output", types.NewArray([]types.Type{ types.B, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), }, nil)).Description("" /* 305 byte string literal not displayed */), ), }
GraphQLParseAndVerify returns a boolean and a pair of AST object from parsing/validation.
var GraphQLParseQuery = &Builtin{ Name: "graphql.parse_query", Description: "Returns an AST object for a GraphQL query.", Decl: types.NewFunction( types.Args( types.Named("query", types.S).Description("GraphQL query string"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))).Description("AST object for the GraphQL query."), ), }
GraphQLParseQuery parses the input GraphQL query and returns a JSON representation of its AST.
var GraphQLParseSchema = &Builtin{ Name: "graphql.parse_schema", Description: "Returns an AST object for a GraphQL schema.", Decl: types.NewFunction( types.Args( types.Named("schema", types.S).Description("GraphQL schema string"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))).Description("AST object for the GraphQL schema."), ), }
GraphQLParseSchema parses the input GraphQL schema and returns a JSON representation of its AST.
var GraphQLSchemaIsValid = &Builtin{ Name: "graphql.schema_is_valid", Description: "" /* 151 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the schema to verify"), ), types.Named("output", types.B).Description("`true` if the schema is a valid GraphQL schema. `false` otherwise."), ), }
GraphQLSchemaIsValid returns true if the input is valid GraphQL schema, and returns false for all other inputs.
var GreaterThan = &Builtin{ Name: "gt", Infix: ">", Categories: comparison, Decl: types.NewFunction( types.Args( types.Named("x", types.A), types.Named("y", types.A), ), types.Named("result", types.B).Description("true if `x` is greater than `y`; false otherwise"), ), }
var GreaterThanEq = &Builtin{ Name: "gte", Infix: ">=", Categories: comparison, Decl: types.NewFunction( types.Args( types.Named("x", types.A), types.Named("y", types.A), ), types.Named("result", types.B).Description("true if `x` is greater or equal to `y`; false otherwise"), ), }
var HTTPSend = &Builtin{ Name: "http.send", Description: "Returns a HTTP response to the given HTTP request.", Decl: types.NewFunction( types.Args( types.Named("request", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). Description("the HTTP request object"), ), types.Named("response", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))). Description("the HTTP response object"), ), Nondeterministic: true, }
Marked non-deterministic because HTTP request results can be non-deterministic.
var HexDecode = &Builtin{ Name: "hex.decode", Description: "Deserializes the hex-encoded input string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("a hex-encoded string"), ), types.Named("y", types.S).Description("deserialized from `x`"), ), Categories: encoding, }
var HexEncode = &Builtin{ Name: "hex.encode", Description: "Serializes the input string using hex-encoding.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to encode"), ), types.Named("y", types.S).Description("serialization of `x` using hex-encoding"), ), Categories: encoding, }
var IgnoreDuringPartialEval = []*Builtin{ RandIntn, UUIDRFC4122, JWTDecodeVerify, JWTEncodeSignRaw, JWTEncodeSign, NowNanos, HTTPSend, OPARuntime, NetLookupIPAddr, }
Deprecated: Builtins can now be directly annotated with the Nondeterministic property, and when set to true, will be ignored for partial evaluation.
var IndexOf = &Builtin{ Name: "indexof", Description: "Returns the index of a substring contained inside a string.", Decl: types.NewFunction( types.Args( types.Named("haystack", types.S).Description("string to search in"), types.Named("needle", types.S).Description("substring to look for"), ), types.Named("output", types.N).Description("index of first occurrence, `-1` if not found"), ), Categories: stringsCat, }
var IndexOfN = &Builtin{ Name: "indexof_n", Description: "Returns a list of all the indexes of a substring contained inside a string.", Decl: types.NewFunction( types.Args( types.Named("haystack", types.S).Description("string to search in"), types.Named("needle", types.S).Description("substring to look for"), ), types.Named("output", types.NewArray(nil, types.N)).Description("all indices at which `needle` occurs in `haystack`, may be empty"), ), Categories: stringsCat, }
var IndexResultPool = &indexResultPool{ pool: sync.Pool{ New: func() any { return &IndexResult{} }, }, }
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 InternalPrint = &Builtin{ Name: "internal.print", Decl: types.NewFunction([]types.Type{types.NewArray(nil, types.SetOfAny)}, nil), }
InternalPrint represents the internal implementation of the print() function. The compiler rewrites print() calls to refer to the internal implementation.
var InternalTestCase = &Builtin{ Name: "internal.test_case", Decl: types.NewFunction([]types.Type{types.NewArray(nil, types.A)}, nil), }
var Intersection = &Builtin{ Name: "intersection", Description: "Returns the intersection of the given input sets.", Decl: types.NewFunction( types.Args( types.Named("xs", types.NewSet(types.SetOfAny)).Description("set of sets to intersect"), ), types.Named("y", types.SetOfAny).Description("the intersection of all `xs` sets"), ), Categories: sets, }
var IsArray = &Builtin{ Name: "is_array", Description: "Returns `true` if the input value is an array.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is an array, `false` otherwise."), ), Categories: typesCat, }
var IsBoolean = &Builtin{ Name: "is_boolean", Description: "Returns `true` if the input value is a boolean.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is an boolean, `false` otherwise."), ), Categories: typesCat, }
var IsNull = &Builtin{ Name: "is_null", Description: "Returns `true` if the input value is null.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is null, `false` otherwise."), ), Categories: typesCat, }
var IsNumber = &Builtin{ Name: "is_number", Description: "Returns `true` if the input value is a number.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is a number, `false` otherwise."), ), Categories: typesCat, }
var IsObject = &Builtin{ Name: "is_object", Description: "Returns true if the input value is an object", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is an object, `false` otherwise."), ), Categories: typesCat, }
var IsSet = &Builtin{ Name: "is_set", Description: "Returns `true` if the input value is a set.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is a set, `false` otherwise."), ), Categories: typesCat, }
var IsString = &Builtin{ Name: "is_string", Description: "Returns `true` if the input value is a string.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("result", types.B).Description("`true` if `x` is a string, `false` otherwise."), ), Categories: typesCat, }
var JSONFilter = &Builtin{ Name: "json.filter", Description: "Filters the object. " + "For example: `json.filter({\"a\": {\"b\": \"x\", \"c\": \"y\"}}, [\"a/b\"])` will result in `{\"a\": {\"b\": \"x\"}}`). " + "Paths are not filtered in-order and are deduplicated before being evaluated.", Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), )).Description("object to filter"), types.Named("paths", types.NewAny( types.NewArray( nil, types.NewAny( types.S, types.NewArray( nil, types.A, ), ), ), types.NewSet( types.NewAny( types.S, types.NewArray( nil, types.A, ), ), ), )).Description("JSON string paths"), ), types.Named("filtered", types.A).Description("remaining data from `object` with only keys specified in `paths`"), ), Categories: objectCat, }
var JSONIsValid = &Builtin{ Name: "json.is_valid", Description: "Verifies the input string is a valid JSON document.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("a JSON string"), ), types.Named("result", types.B).Description("`true` if `x` is valid JSON, `false` otherwise"), ), Categories: encoding, }
var JSONMarshal = &Builtin{ Name: "json.marshal", Description: "Serializes the input term to JSON.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("the term to serialize"), ), types.Named("y", types.S).Description("the JSON string representation of `x`"), ), Categories: encoding, }
var JSONMarshalWithOptions = &Builtin{ Name: "json.marshal_with_options", Description: "Serializes the input term JSON, with additional formatting options via the `opts` parameter. " + "" /* 180 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("the term to serialize"), types.Named("opts", types.NewObject( []*types.StaticProperty{ types.NewStaticProperty("pretty", types.B), types.NewStaticProperty("indent", types.S), types.NewStaticProperty("prefix", types.S), }, types.NewDynamicProperty(types.S, types.A), )).Description("encoding options"), ), types.Named("y", types.S).Description("the JSON string representation of `x`, with configured prefix/indent string(s) as appropriate"), ), Categories: encoding, }
var JSONMatchSchema = &Builtin{ Name: "json.match_schema", Description: "Checks that the document matches the JSON schema.", Decl: types.NewFunction( types.Args( types.Named("document", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("document to verify by schema"), types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("schema to verify document by"), ), types.Named("output", types.NewArray([]types.Type{ types.B, types.NewArray( nil, types.NewObject( []*types.StaticProperty{ {Key: "error", Value: types.S}, {Key: "type", Value: types.S}, {Key: "field", Value: types.S}, {Key: "desc", Value: types.S}, }, nil, ), ), }, nil)). Description("" /* 234 byte string literal not displayed */), ), Categories: objectCat, }
JSONMatchSchema returns empty array if the document matches the JSON schema, and returns non-empty array with error objects otherwise.
var JSONPatch = &Builtin{ Name: "json.patch", Description: "Patches an object according to RFC6902. " + "" /* 155 byte string literal not displayed */ + "The patches are applied atomically: if any of them fails, the result will be undefined. " + "Additionally works on sets, where a value contained in the set is considered to be its path.", Decl: types.NewFunction( types.Args( types.Named("object", types.A).Description("the object to patch"), types.Named("patches", types.NewArray( nil, types.NewObject( []*types.StaticProperty{ {Key: "op", Value: types.S}, {Key: "path", Value: types.A}, }, types.NewDynamicProperty(types.A, types.A), ), )).Description("the JSON patches to apply"), ), types.Named("output", types.A).Description("result obtained after consecutively applying all patch operations in `patches`"), ), Categories: objectCat, }
var JSONRemove = &Builtin{ Name: "json.remove", Description: "Removes paths from an object. " + "For example: `json.remove({\"a\": {\"b\": \"x\", \"c\": \"y\"}}, [\"a/b\"])` will result in `{\"a\": {\"c\": \"y\"}}`. " + "Paths are not removed in-order and are deduplicated before being evaluated.", Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), )).Description("object to remove paths from"), types.Named("paths", types.NewAny( types.NewArray( nil, types.NewAny( types.S, types.NewArray( nil, types.A, ), ), ), types.NewSet( types.NewAny( types.S, types.NewArray( nil, types.A, ), ), ), )).Description("JSON string paths"), ), types.Named("output", types.A).Description("result of removing all keys specified in `paths`"), ), Categories: objectCat, }
var JSONSchemaVerify = &Builtin{ Name: "json.verify_schema", Description: "Checks that the input is a valid JSON schema object. The schema can be either a JSON string or an JSON object.", Decl: types.NewFunction( types.Args( types.Named("schema", types.NewAny(types.S, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)))). Description("the schema to verify"), ), types.Named("output", types.NewArray([]types.Type{ types.B, types.NewAny(types.S, types.Null{}), }, nil)). Description("" /* 190 byte string literal not displayed */), ), Categories: objectCat, }
JSONSchemaVerify returns empty string if the input is valid JSON schema and returns error string for all other inputs.
var JSONUnmarshal = &Builtin{ Name: "json.unmarshal", Description: "Deserializes the input string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("a JSON string"), ), types.Named("y", types.A).Description("the term deserialized from `x`"), ), Categories: encoding, }
var JWTDecode = &Builtin{ Name: "io.jwt.decode", Description: "Decodes a JSON Web Token and outputs it as an object.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token to decode"), ), types.Named("output", types.NewArray([]types.Type{ types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.S, }, nil)).Description("" /* 140 byte string literal not displayed */), ), Categories: tokensCat, }
var JWTDecodeVerify = &Builtin{ Name: "io.jwt.decode_verify", Description: "" /* 219 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified and whose claims are to be checked"), types.Named("constraints", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("claim verification constraints"), ), types.Named("output", types.NewArray([]types.Type{ types.B, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), }, nil)).Description("" /* 277 byte string literal not displayed */), ), Categories: tokensCat, Nondeterministic: true, }
Marked non-deterministic because it relies on time internally.
var JWTEncodeSign = &Builtin{ Name: "io.jwt.encode_sign", Description: "" /* 129 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("headers", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("JWS Protected Header"), types.Named("payload", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("JWS Payload"), types.Named("key", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("JSON Web Key (RFC7517)"), ), types.Named("output", types.S).Description("signed JWT"), ), Categories: tokenSign, Nondeterministic: true, }
Marked non-deterministic because it relies on RNG internally.
var JWTEncodeSignRaw = &Builtin{ Name: "io.jwt.encode_sign_raw", Description: "Encodes and optionally signs a JSON Web Token.", Decl: types.NewFunction( types.Args( types.Named("headers", types.S).Description("JWS Protected Header"), types.Named("payload", types.S).Description("JWS Payload"), types.Named("key", types.S).Description("JSON Web Key (RFC7517)"), ), types.Named("output", types.S).Description("signed JWT"), ), Categories: tokenSign, Nondeterministic: true, }
Marked non-deterministic because it relies on RNG internally.
var JWTVerifyES256 = &Builtin{ Name: "io.jwt.verify_es256", Description: "Verifies if a ES256 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyES384 = &Builtin{ Name: "io.jwt.verify_es384", Description: "Verifies if a ES384 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyES512 = &Builtin{ Name: "io.jwt.verify_es512", Description: "Verifies if a ES512 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyHS256 = &Builtin{ Name: "io.jwt.verify_hs256", Description: "Verifies if a HS256 (secret) JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("secret", types.S).Description("plain text secret used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyHS384 = &Builtin{ Name: "io.jwt.verify_hs384", Description: "Verifies if a HS384 (secret) JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("secret", types.S).Description("plain text secret used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyHS512 = &Builtin{ Name: "io.jwt.verify_hs512", Description: "Verifies if a HS512 (secret) JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("secret", types.S).Description("plain text secret used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyPS256 = &Builtin{ Name: "io.jwt.verify_ps256", Description: "Verifies if a PS256 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyPS384 = &Builtin{ Name: "io.jwt.verify_ps384", Description: "Verifies if a PS384 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyPS512 = &Builtin{ Name: "io.jwt.verify_ps512", Description: "Verifies if a PS512 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyRS256 = &Builtin{ Name: "io.jwt.verify_rs256", Description: "Verifies if a RS256 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyRS384 = &Builtin{ Name: "io.jwt.verify_rs384", Description: "Verifies if a RS384 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var JWTVerifyRS512 = &Builtin{ Name: "io.jwt.verify_rs512", Description: "Verifies if a RS512 JWT signature is valid.", Decl: types.NewFunction( types.Args( types.Named("jwt", types.S).Description("JWT token whose signature is to be verified"), types.Named("certificate", types.S).Description("PEM encoded certificate, PEM encoded public key, or the JWK key (set) used to verify the signature"), ), types.Named("result", types.B).Description("`true` if the signature is valid, `false` otherwise"), ), Categories: tokensCat, }
var Keywords = KeywordsForRegoVersion(DefaultRegoVersion)
Keywords contains strings that map to language keywords.
var KeywordsV0 = [...]string{ "not", "package", "import", "as", "default", "else", "with", "null", "true", "false", "some", }
var KeywordsV1 = [...]string{ "not", "package", "import", "as", "default", "else", "with", "null", "true", "false", "some", "if", "contains", "in", "every", }
var LessThan = &Builtin{ Name: "lt", Infix: "<", Categories: comparison, Decl: types.NewFunction( types.Args( types.Named("x", types.A), types.Named("y", types.A), ), types.Named("result", types.B).Description("true if `x` is less than `y`; false otherwise"), ), }
LessThan represents the "<" comparison operator.
var LessThanEq = &Builtin{ Name: "lte", Infix: "<=", Categories: comparison, Decl: types.NewFunction( types.Args( types.Named("x", types.A), types.Named("y", types.A), ), types.Named("result", types.B).Description("true if `x` is less than or equal to `y`; false otherwise"), ), }
var Lower = &Builtin{ Name: "lower", Description: "Returns the input string but with all characters in lower-case.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string that is converted to lower-case"), ), types.Named("y", types.S).Description("lower-case of x"), ), Categories: stringsCat, }
var Max = &Builtin{ Name: "max", Description: "Returns the maximum value in a collection.", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.SetOfAny, types.NewArray(nil, types.A), )).Description("the set or array to be searched"), ), types.Named("n", types.A).Description("the maximum of all elements"), ), Categories: aggregates, }
var Member = &Builtin{ Name: "internal.member_2", Infix: "in", Decl: types.NewFunction( types.Args( types.A, types.A, ), types.B, ), }
Member represents the `in` (infix) operator.
var MemberWithKey = &Builtin{ Name: "internal.member_3", Infix: "in", Decl: types.NewFunction( types.Args( types.A, types.A, types.A, ), types.B, ), }
MemberWithKey represents the `in` (infix) operator when used with two terms on the lhs, i.e., `k, v in obj`.
var Min = &Builtin{ Name: "min", Description: "Returns the minimum value in a collection.", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.SetOfAny, types.NewArray(nil, types.A), )).Description("the set or array to be searched"), ), types.Named("n", types.A).Description("the minimum of all elements"), ), Categories: aggregates, }
var Minus = &Builtin{ Name: "minus", Infix: "-", Description: "Minus subtracts the second number from the first number or computes the difference between two sets.", Decl: types.NewFunction( types.Args( types.Named("x", types.NewAny(types.N, types.SetOfAny)), types.Named("y", types.NewAny(types.N, types.SetOfAny)), ), types.Named("z", types.NewAny(types.N, types.SetOfAny)).Description("the difference of `x` and `y`"), ), Categories: category("sets", "numbers"), }
var Multiply = &Builtin{ Name: "mul", Infix: "*", Description: "Multiplies two numbers.", Decl: types.NewFunction( types.Args( types.Named("x", types.N), types.Named("y", types.N), ), types.Named("z", types.N).Description("the product of `x` and `y`"), ), Categories: number, }
var NetCIDRContains = &Builtin{ Name: "net.cidr_contains", Description: "" /* 242 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("cidr", types.S).Description("CIDR to check against"), types.Named("cidr_or_ip", types.S).Description("CIDR or IP to check"), ), types.Named("result", types.B).Description("`true` if `cidr_or_ip` is contained within `cidr`"), ), }
var NetCIDRContainsMatches = &Builtin{ Name: "net.cidr_contains_matches", Description: "Checks if collections of cidrs or ips are contained within another collection of cidrs and returns matches. " + "" /* 222 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("cidrs", netCidrContainsMatchesOperandType).Description("CIDRs to check against"), types.Named("cidrs_or_ips", netCidrContainsMatchesOperandType).Description("CIDRs or IPs to check"), ), types.Named("output", types.NewSet(types.NewArray([]types.Type{types.A, types.A}, nil))).Description("tuples identifying matches where `cidrs_or_ips` are contained within `cidrs`"), ), }
var NetCIDRExpand = &Builtin{ Name: "net.cidr_expand", Description: "" /* 168 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("cidr", types.S).Description("CIDR to expand"), ), types.Named("hosts", types.SetOfStr).Description("set of IP addresses the CIDR `cidr` expands to"), ), }
var NetCIDRIntersects = &Builtin{ Name: "net.cidr_intersects", Description: "" /* 142 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("cidr1", types.S).Description("first CIDR"), types.Named("cidr2", types.S).Description("second CIDR"), ), types.Named("result", types.B).Description("`true` if `cidr1` intersects with `cidr2`"), ), }
var NetCIDRIsValid = &Builtin{ Name: "net.cidr_is_valid", Description: "Parses an IPv4/IPv6 CIDR and returns a boolean indicating if the provided CIDR is valid.", Decl: types.NewFunction( types.Args( types.Named("cidr", types.S).Description("CIDR to validate"), ), types.Named("result", types.B).Description("`true` if `cidr` is a valid CIDR"), ), }
var NetCIDRMerge = &Builtin{ Name: "net.cidr_merge", Description: "" /* 174 byte string literal not displayed */ + "" /* 205 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("addrs", types.NewAny( types.NewArray(nil, types.NewAny(types.S)), types.SetOfStr, )).Description("CIDRs or IP addresses"), ), types.Named("output", types.SetOfStr).Description("smallest possible set of CIDRs obtained after merging the provided list of IP addresses and subnets in `addrs`"), ), }
var NetCIDROverlap = &Builtin{ Name: "net.cidr_overlap", Decl: types.NewFunction( types.Args( types.S, types.S, ), types.B, ), deprecated: true, }
NetCIDROverlap has been replaced by the `net.cidr_contains` built-in.
var NetLookupIPAddr = &Builtin{ Name: "net.lookup_ip_addr", Description: "" /* 145 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("name", types.S).Description("domain name to resolve"), ), types.Named("addrs", types.SetOfStr).Description("IP addresses (v4 and v6) that `name` resolves to"), ), Nondeterministic: true, }
Marked non-deterministic because DNS resolution results can be non-deterministic.
var NotEqual = &Builtin{ Name: "neq", Infix: "!=", Categories: comparison, Decl: types.NewFunction( types.Args( types.Named("x", types.A), types.Named("y", types.A), ), types.Named("result", types.B).Description("true if `x` is not equal to `y`; false otherwise"), ), }
var NowNanos = &Builtin{ Name: "time.now_ns", Description: "Returns the current time since epoch in nanoseconds.", Decl: types.NewFunction( nil, types.Named("now", types.N).Description("nanoseconds since epoch"), ), Nondeterministic: true, }
Marked non-deterministic because it relies on time directly.
var NumbersRange = &Builtin{ Name: "numbers.range", Description: "" /* 142 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("a", types.N).Description("the start of the range"), types.Named("b", types.N).Description("the end of the range (inclusive)"), ), types.Named("range", types.NewArray(nil, types.N)).Description("the range between `a` and `b`"), ), }
var NumbersRangeStep = &Builtin{ Name: "numbers.range_step", Description: "" /* 330 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("a", types.N).Description("the start of the range"), types.Named("b", types.N).Description("the end of the range (inclusive)"), types.Named("step", types.N).Description("the step between numbers in the range"), ), types.Named("range", types.NewArray(nil, types.N)).Description("the range between `a` and `b` in `step` increments"), ), }
var OPARuntime = &Builtin{ Name: "opa.runtime", Description: "Returns an object that describes the runtime environment where OPA is deployed.", Decl: types.NewFunction( nil, types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). Description("" /* 245 byte string literal not displayed */), ), Nondeterministic: true, }
Marked non-deterministic because of unpredictable config/environment-dependent results.
var ObjectFilter = &Builtin{ Name: "object.filter", Description: "Filters the object by keeping only specified keys. " + "" /* 149 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), )).Description("object to filter keys"), types.Named("keys", types.NewAny( types.NewArray(nil, types.A), types.SetOfAny, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), )).Description("keys to keep in `object`"), ), types.Named("filtered", types.A).Description("remaining data from `object` with only keys specified in `keys`"), ), }
var ObjectGet = &Builtin{ Name: "object.get", Description: "Returns value of an object's key if present, otherwise a default. " + "If the supplied `key` is an `array`, then `object.get` will search through a nested object or array using each key in turn. " + "For example: `object.get({\"a\": [{ \"b\": true }]}, [\"a\", 0, \"b\"], false)` results in `true`.", Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))).Description("object to get `key` from"), types.Named("key", types.A).Description("key to lookup in `object`"), types.Named("default", types.A).Description("default to use when lookup fails"), ), types.Named("value", types.A).Description("`object[key]` if present, otherwise `default`"), ), }
var ObjectKeys = &Builtin{ Name: "object.keys", Description: "Returns a set of an object's keys. " + "For example: `object.keys({\"a\": 1, \"b\": true, \"c\": \"d\")` results in `{\"a\", \"b\", \"c\"}`.", Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))).Description("object to get keys from"), ), types.Named("value", types.SetOfAny).Description("set of `object`'s keys"), ), }
var ObjectRemove = &Builtin{ Name: "object.remove", Description: "Removes specified keys from an object.", Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), )).Description("object to remove keys from"), types.Named("keys", types.NewAny( types.NewArray(nil, types.A), types.SetOfAny, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), )).Description("keys to remove from x"), ), types.Named("output", types.A).Description("result of removing the specified `keys` from `object`"), ), }
var ObjectSubset = &Builtin{ Name: "object.subset", Description: "Determines if an object `sub` is a subset of another object `super`." + "Object `sub` is a subset of object `super` if and only if every key in `sub` is also in `super`, " + "**and** for all keys which `sub` and `super` share, they have the same value. " + "This function works with objects, sets, arrays and a set of array and set." + "If both arguments are objects, then the operation is recursive, e.g. " + "`{\"c\": {\"x\": {10, 15, 20}}` is a subset of `{\"a\": \"b\", \"c\": {\"x\": {10, 15, 20, 25}, \"y\": \"z\"}`. " + "If both arguments are sets, then this function checks if every element of `sub` is a member of `super`, " + "but does not attempt to recurse. If both arguments are arrays, " + "then this function checks if `sub` appears contiguously in order within `super`, " + "and also does not attempt to recurse. If `super` is array and `sub` is set, " + "then this function checks if `super` contains every element of `sub` with no consideration of ordering, " + "and also does not attempt to recurse.", Decl: types.NewFunction( types.Args( types.Named("super", types.NewAny(types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), ), types.SetOfAny, types.NewArray(nil, types.A), )).Description("object to test if sub is a subset of"), types.Named("sub", types.NewAny(types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), ), types.SetOfAny, types.NewArray(nil, types.A), )).Description("object to test if super is a superset of"), ), types.Named("result", types.A).Description("`true` if `sub` is a subset of `super`"), ), }
var ObjectUnion = &Builtin{ Name: "object.union", Description: "Creates a new object of the asymmetric union of two objects. " + "" /* 179 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("a", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), )).Description("left-hand object"), types.Named("b", types.NewObject( nil, types.NewDynamicProperty(types.A, types.A), )).Description("right-hand object"), ), types.Named("output", types.A).Description("" /* 162 byte string literal not displayed */), ), }
var ObjectUnionN = &Builtin{ Name: "object.union_n", Description: "Creates a new object that is the asymmetric union of all objects merged from left to right. " + "For example: `object.union_n([{\"a\": 1}, {\"b\": 2}, {\"a\": 3}])` will result in `{\"b\": 2, \"a\": 3}`.", Decl: types.NewFunction( types.Args( types.Named("objects", types.NewArray( nil, types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)), )).Description("list of objects to merge"), ), types.Named("output", types.A).Description("" /* 160 byte string literal not displayed */), ), }
var Or = &Builtin{ Name: "or", Infix: "|", Description: "Returns the union of two sets.", Decl: types.NewFunction( types.Args( types.Named("x", types.SetOfAny), types.Named("y", types.SetOfAny), ), types.Named("z", types.SetOfAny).Description("the union of `x` and `y`"), ), Categories: sets, }
Or performs a union operation on sets.
var ParseDurationNanos = &Builtin{ Name: "time.parse_duration_ns", Description: "Returns the duration in nanoseconds represented by a string.", Decl: types.NewFunction( types.Args( types.Named("duration", types.S).Description("a duration like \"3m\"; see the [Go `time` package documentation](https://golang.org/pkg/time/#ParseDuration) for more details"), ), types.Named("ns", types.N).Description("the `duration` in nanoseconds"), ), }
var ParseNanos = &Builtin{ Name: "time.parse_ns", Description: "" /* 173 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("layout", types.S).Description("format used for parsing, see the [Go `time` package documentation](https://golang.org/pkg/time/#Parse) for more details"), types.Named("value", types.S).Description("input to parse according to `layout`"), ), types.Named("ns", types.N).Description("`value` in nanoseconds since epoch"), ), }
var ParseRFC3339Nanos = &Builtin{ Name: "time.parse_rfc3339_ns", Description: "" /* 171 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("input string to parse in RFC3339 format"), ), types.Named("ns", types.N).Description("`value` in nanoseconds since epoch"), ), }
var Plus = &Builtin{ Name: "plus", Infix: "+", Description: "Plus adds two numbers together.", Decl: types.NewFunction( types.Args( types.Named("x", types.N), types.Named("y", types.N), ), types.Named("z", types.N).Description("the sum of `x` and `y`"), ), Categories: number, }
Print is a special built-in function that writes zero or more operands to a message buffer. The caller controls how the buffer is displayed. The operands may be of any type. Furthermore, unlike other built-in functions, undefined operands DO NOT cause the print() function to fail during evaluation.
var Product = &Builtin{ Name: "product", Description: "Multiplies elements of an array or set of numbers", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.SetOfNum, types.NewArray(nil, types.N), )).Description("the set or array of numbers to multiply"), ), types.Named("n", types.N).Description("the product of all elements"), ), Categories: aggregates, }
var ProvidersAWSSignReqObj = &Builtin{ Name: "providers.aws.sign_req", Description: "" /* 241 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("request", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). Description("HTTP request object"), types.Named("aws_config", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). Description("AWS configuration object"), types.Named("time_ns", types.N).Description("nanoseconds since the epoch"), ), types.Named("signed_request", types.NewObject(nil, types.NewDynamicProperty(types.A, types.A))). Description("HTTP request object with `Authorization` header"), ), Categories: providersAWSCat, }
var RandIntn = &Builtin{ Name: "rand.intn", Description: "" /* 205 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("str", types.S).Description("seed string for the random number"), types.Named("n", types.N).Description("upper bound of the random number (exclusive)"), ), types.Named("y", types.N).Description("random integer in the range `[0, abs(n))`"), ), Categories: number, Nondeterministic: true, }
RandIntn returns a random number 0 - n Marked non-deterministic because it relies on RNG internally.
var ReachableBuiltin = &Builtin{ Name: "graph.reachable", Description: "Computes the set of reachable nodes in the graph from a set of starting nodes.", Decl: types.NewFunction( types.Args( types.Named("graph", types.NewObject( nil, types.NewDynamicProperty( types.A, types.NewAny( types.SetOfAny, types.NewArray(nil, types.A)), )), ).Description("object containing a set or array of neighboring vertices"), types.Named("initial", types.NewAny(types.SetOfAny, types.NewArray(nil, types.A))).Description("set or array of root vertices"), ), types.Named("output", types.SetOfAny).Description("set of vertices reachable from the `initial` vertices in the directed `graph`"), ), }
var ReachablePathsBuiltin = &Builtin{ Name: "graph.reachable_paths", Description: "Computes the set of reachable paths in the graph from a set of starting nodes.", Decl: types.NewFunction( types.Args( types.Named("graph", types.NewObject( nil, types.NewDynamicProperty( types.A, types.NewAny( types.SetOfAny, types.NewArray(nil, types.A)), )), ).Description("object containing a set or array of root vertices"), types.Named("initial", types.NewAny(types.SetOfAny, types.NewArray(nil, types.A))).Description("initial paths"), ), types.Named("output", types.NewSet(types.NewArray(nil, types.A))).Description("paths reachable from the `initial` vertices in the directed `graph`"), ), }
var RegexFind = &Builtin{ Name: "regex.find_n", Description: "Returns the specified number of matches when matching the input against the pattern.", Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("regular expression"), types.Named("value", types.S).Description("string to match"), types.Named("number", types.N).Description("number of matches to return, if `-1`, returns all matches"), ), types.Named("output", types.NewArray(nil, types.S)).Description("collected matches"), ), }
RegexFind takes two strings and a number, the pattern, the value and number of match values to return, -1 means all match values.
var RegexFindAllStringSubmatch = &Builtin{ Name: "regex.find_all_string_submatch_n", Description: "Returns all successive matches of the expression.", Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("regular expression"), types.Named("value", types.S).Description("string to match"), types.Named("number", types.N).Description("number of matches to return; `-1` means all matches"), ), types.Named("output", types.NewArray(nil, types.NewArray(nil, types.S))).Description("array of all matches"), ), }
var RegexIsValid = &Builtin{ Name: "regex.is_valid", Description: "" /* 141 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("regular expression"), ), types.Named("result", types.B).Description("true if `pattern` is a valid regular expression"), ), }
var RegexMatch = &Builtin{ Name: "regex.match", Description: "Matches a string against a regular expression.", Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("regular expression"), types.Named("value", types.S).Description("value to match against `pattern`"), ), types.Named("result", types.B).Description("true if `value` matches `pattern`"), ), }
var RegexMatchDeprecated = &Builtin{ Name: "re_match", Decl: types.NewFunction( types.Args( types.S, types.S, ), types.B, ), deprecated: true, }
RegexMatchDeprecated declares `re_match` which has been deprecated. Use `regex.match` instead.
var RegexReplace = &Builtin{ Name: "regex.replace", Description: `Find and replaces the text using the regular expression pattern.`, Decl: types.NewFunction( types.Args( types.Named("s", types.S).Description("string being processed"), types.Named("pattern", types.S).Description("regex pattern to be applied"), types.Named("value", types.S).Description("regex value"), ), types.Named("output", types.S).Description("string with replaced substrings"), ), }
var RegexSplit = &Builtin{ Name: "regex.split", Description: "Splits the input string by the occurrences of the given pattern.", Decl: types.NewFunction( types.Args( types.Named("pattern", types.S).Description("regular expression"), types.Named("value", types.S).Description("string to match"), ), types.Named("output", types.NewArray(nil, types.S)).Description("the parts obtained by splitting `value`"), ), }
var RegexTemplateMatch = &Builtin{ Name: "regex.template_match", Description: "Matches a string against a pattern, where there pattern may be glob-like", Decl: types.NewFunction( types.Args( types.Named("template", types.S).Description("template expression containing `0..n` regular expressions"), types.Named("value", types.S).Description("string to match"), types.Named("delimiter_start", types.S).Description("start delimiter of the regular expression in `template`"), types.Named("delimiter_end", types.S).Description("end delimiter of the regular expression in `template`"), ), types.Named("result", types.B).Description("true if `value` matches the `template`"), ), } // TODO(sr): example:`regex.template_match("urn:foo:{.*}", "urn:foo:bar:baz", "{", "}")`` returns ``true``.
var RegoMetadataChain = &Builtin{ Name: "rego.metadata.chain", Description: "" /* 500 byte string literal not displayed */, Decl: types.NewFunction( types.Args(), types.Named("chain", types.NewArray(nil, types.A)).Description("each array entry represents a node in the path ancestry (chain) of the active rule that also has declared annotations"), ), }
var RegoMetadataRule = &Builtin{ Name: "rego.metadata.rule", Description: "Returns annotations declared for the active rule and using the _rule_ scope.", Decl: types.NewFunction( types.Args(), types.Named("output", types.A).Description("\"rule\" scope annotations for this rule; empty object if no annotations exist"), ), }
RegoMetadataRule returns the metadata for the active rule
var RegoParseModule = &Builtin{ Name: "rego.parse_module", Description: "Parses the input Rego string and returns an object representation of the AST.", Decl: types.NewFunction( types.Args( types.Named("filename", types.S).Description("file name to attach to AST nodes' locations"), types.Named("rego", types.S).Description("Rego module"), ), types.Named("output", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))). Description("AST object for the Rego module"), ), }
var RegoRootDocument = VarTerm("rego")
RegoRootDocument names the document containing new, to-become-default, features in a future versioned release.
var RegoV1CompatibleRef = Ref{VarTerm("rego"), InternedStringTerm("v1")}
var Rem = &Builtin{ Name: "rem", Infix: "%", Description: "Returns the remainder for of `x` divided by `y`, for `y != 0`.", Decl: types.NewFunction( types.Args( types.Named("x", types.N), types.Named("y", types.N), ), types.Named("z", types.N).Description("the remainder"), ), Categories: number, }
var RenderTemplate = &Builtin{ Name: "strings.render_template", Description: "" /* 269 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("a templated string"), types.Named("vars", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("a mapping of template variable keys to values"), ), types.Named("result", types.S).Description("rendered template with template variables injected"), ), Categories: stringsCat, }
var Replace = &Builtin{ Name: "replace", Description: "Replace replaces all instances of a sub-string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string being processed"), types.Named("old", types.S).Description("substring to replace"), types.Named("new", types.S).Description("string to replace `old` with"), ), types.Named("y", types.S).Description("string with replaced substrings"), ), Categories: stringsCat, }
var ReplaceN = &Builtin{ Name: "strings.replace_n", Description: "" /* 215 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("patterns", types.NewObject( nil, types.NewDynamicProperty( types.S, types.S)), ).Description("replacement pairs"), types.Named("value", types.S).Description("string to replace substring matches in"), ), types.Named("output", types.S).Description("string with replaced substrings"), ), }
ReservedVars is the set of names that refer to implicitly ground vars.
var RootDocumentNames = NewSet(
DefaultRootDocument,
InputRootDocument,
)
RootDocumentNames contains the names of top-level documents that can be referred to in modules and queries.
Note, the schema document is not currently implemented in the evaluator so it is not registered as a root document name (yet).
var RootDocumentRefs = NewSet(
NewTerm(DefaultRootRef),
NewTerm(InputRootRef),
)
RootDocumentRefs contains the prefixes of top-level documents that all non-local references start with.
var Round = &Builtin{ Name: "round", Description: "Rounds the number to the nearest integer.", Decl: types.NewFunction( types.Args( types.Named("x", types.N).Description("the number to round"), ), types.Named("y", types.N).Description("the result of rounding `x`"), ), Categories: number, }
var SafetyCheckVisitorParams = VarVisitorParams{ SkipRefCallHead: true, SkipClosures: true, }
SafetyCheckVisitorParams defines the AST visitor parameters to use for collecting variables during the safety check. This has to be exported because it's relied on by the copy propagation implementation in topdown.
var SchemaRootDocument = VarTerm("schema")
SchemaRootDocument names the document containing external data schemas.
var SchemaRootRef = Ref{SchemaRootDocument}
SchemaRootRef is a reference to the root of the schema document.
All refs to schema documents are prefixed with this ref. Note, the schema document is not currently implemented in the evaluator so it is not registered as a root document ref (yet).
var SemVerCompare = &Builtin{ Name: "semver.compare", Description: "Compares valid SemVer formatted version strings.", Decl: types.NewFunction( types.Args( types.Named("a", types.S).Description("first version string"), types.Named("b", types.S).Description("second version string"), ), types.Named("result", types.N).Description("`-1` if `a < b`; `1` if `a > b`; `0` if `a == b`"), ), }
var SemVerIsValid = &Builtin{ Name: "semver.is_valid", Description: "Validates that the input is a valid SemVer string.", Decl: types.NewFunction( types.Args( types.Named("vsn", types.A).Description("input to validate"), ), types.Named("result", types.B).Description("`true` if `vsn` is a valid SemVer; `false` otherwise"), ), }
var SetDiff = &Builtin{ Name: "set_diff", Decl: types.NewFunction( types.Args( types.SetOfAny, types.SetOfAny, ), types.SetOfAny, ), deprecated: true, }
SetDiff has been replaced by the minus built-in.
var Sort = &Builtin{ Name: "sort", Description: "Returns a sorted array.", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.NewArray(nil, types.A), types.SetOfAny, )).Description("the array or set to be sorted"), ), types.Named("n", types.NewArray(nil, types.A)).Description("the sorted array"), ), Categories: aggregates, }
var Split = &Builtin{ Name: "split", Description: "Split returns an array containing elements of the input string split on a delimiter.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string that is split"), types.Named("delimiter", types.S).Description("delimiter used for splitting"), ), types.Named("ys", types.NewArray(nil, types.S)).Description("split parts"), ), Categories: stringsCat, }
var Sprintf = &Builtin{ Name: "sprintf", Description: "Returns the given string, formatted.", Decl: types.NewFunction( types.Args( types.Named("format", types.S).Description("string with formatting verbs"), types.Named("values", types.NewArray(nil, types.A)).Description("arguments to format into formatting verbs"), ), types.Named("output", types.S).Description("`format` formatted by the values in `values`"), ), Categories: stringsCat, }
var StartsWith = &Builtin{ Name: "startswith", Description: "Returns true if the search string begins with the base string.", Decl: types.NewFunction( types.Args( types.Named("search", types.S).Description("search string"), types.Named("base", types.S).Description("base string"), ), types.Named("result", types.B).Description("result of the prefix check"), ), Categories: stringsCat, }
var StringCount = &Builtin{ Name: "strings.count", Description: "Returns the number of non-overlapping instances of a substring in a string.", Decl: types.NewFunction( types.Args( types.Named("search", types.S).Description("string to search in"), types.Named("substring", types.S).Description("substring to look for"), ), types.Named("output", types.N).Description("count of occurrences, `0` if not found"), ), Categories: stringsCat, }
var StringReverse = &Builtin{ Name: "strings.reverse", Description: "Reverses a given string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string to reverse"), ), types.Named("y", types.S).Description("reversed string"), ), Categories: stringsCat, }
var Substring = &Builtin{ Name: "substring", Description: "" /* 130 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to extract substring from"), types.Named("offset", types.N).Description("offset, must be positive"), types.Named("length", types.N).Description("length of the substring starting from `offset`"), ), types.Named("output", types.S).Description("substring of `value` from `offset`, of length `length`"), ), Categories: stringsCat, }
var Sum = &Builtin{ Name: "sum", Description: "Sums elements of an array or set of numbers.", Decl: types.NewFunction( types.Args( types.Named("collection", types.NewAny( types.SetOfNum, types.NewArray(nil, types.N), )).Description("the set or array of numbers to sum"), ), types.Named("n", types.N).Description("the sum of all elements"), ), Categories: aggregates, }
var ToNumber = &Builtin{ Name: "to_number", Description: "" /* 174 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("x", types.NewAny( types.N, types.S, types.B, types.NewNull(), )).Description("value to convert"), ), types.Named("num", types.N).Description("the numeric representation of `x`"), ), Categories: conversions, }
var Trace = &Builtin{ Name: "trace", Description: "" /* 441 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("note", types.S).Description("the note to include"), ), types.Named("result", types.B).Description("always `true`"), ), Categories: tracing, }
var Trim = &Builtin{ Name: "trim", Description: "Returns `value` with all leading or trailing instances of the `cutset` characters removed.", Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to trim"), types.Named("cutset", types.S).Description("string of characters that are cut off"), ), types.Named("output", types.S).Description("string trimmed of `cutset` characters"), ), Categories: stringsCat, }
var TrimLeft = &Builtin{ Name: "trim_left", Description: "Returns `value` with all leading instances of the `cutset` characters removed.", Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to trim"), types.Named("cutset", types.S).Description("string of characters that are cut off on the left"), ), types.Named("output", types.S).Description("string left-trimmed of `cutset` characters"), ), Categories: stringsCat, }
var TrimPrefix = &Builtin{ Name: "trim_prefix", Description: "Returns `value` without the prefix. If `value` doesn't start with `prefix`, it is returned unchanged.", Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to trim"), types.Named("prefix", types.S).Description("prefix to cut off"), ), types.Named("output", types.S).Description("string with `prefix` cut off"), ), Categories: stringsCat, }
var TrimRight = &Builtin{ Name: "trim_right", Description: "Returns `value` with all trailing instances of the `cutset` characters removed.", Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to trim"), types.Named("cutset", types.S).Description("string of characters that are cut off on the right"), ), types.Named("output", types.S).Description("string right-trimmed of `cutset` characters"), ), Categories: stringsCat, }
var TrimSpace = &Builtin{ Name: "trim_space", Description: "Return the given string with all leading and trailing white space removed.", Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to trim"), ), types.Named("output", types.S).Description("string leading and trailing white space cut off"), ), Categories: stringsCat, }
var TrimSuffix = &Builtin{ Name: "trim_suffix", Description: "Returns `value` without the suffix. If `value` doesn't end with `suffix`, it is returned unchanged.", Decl: types.NewFunction( types.Args( types.Named("value", types.S).Description("string to trim"), types.Named("suffix", types.S).Description("suffix to cut off"), ), types.Named("output", types.S).Description("string with `suffix` cut off"), ), Categories: stringsCat, }
var TypeNameBuiltin = &Builtin{ Name: "type_name", Description: "Returns the type of its input value.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("input value"), ), types.Named("type", types.S).Description(`one of "null", "boolean", "number", "string", "array", "object", "set"`), ), Categories: typesCat, }
TypeNameBuiltin returns the type of the input.
var URLQueryDecode = &Builtin{ Name: "urlquery.decode", Description: "Decodes a URL-encoded input string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the URL-encoded string"), ), types.Named("y", types.S).Description("URL-encoding deserialization of `x`"), ), Categories: encoding, }
var URLQueryDecodeObject = &Builtin{ Name: "urlquery.decode_object", Description: "Decodes the given URL query string into an object.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the query string"), ), types.Named("object", types.NewObject(nil, types.NewDynamicProperty( types.S, types.NewArray(nil, types.S)))).Description("the resulting object"), ), Categories: encoding, }
var URLQueryEncode = &Builtin{ Name: "urlquery.encode", Description: "Encodes the input string into a URL-encoded string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the string to encode"), ), types.Named("y", types.S).Description("URL-encoding serialization of `x`"), ), Categories: encoding, }
var URLQueryEncodeObject = &Builtin{ Name: "urlquery.encode_object", Description: "Encodes the given object into a URL encoded query string.", Decl: types.NewFunction( types.Args( types.Named("object", types.NewObject( nil, types.NewDynamicProperty( types.S, types.NewAny( types.S, types.NewArray(nil, types.S), types.SetOfStr, ), ), ), ).Description("the object to encode"), ), types.Named("y", types.S).Description("the URL-encoded serialization of `object`"), ), Categories: encoding, }
var UUIDParse = &Builtin{ Name: "uuid.parse", Description: "Parses the string value as an UUID and returns an object with the well-defined fields of the UUID if valid.", Categories: nil, Decl: types.NewFunction( types.Args( types.Named("uuid", types.S).Description("UUID string to parse"), ), types.Named("result", types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))).Description("Properties of UUID if valid (version, variant, etc). Undefined otherwise."), ), Relation: false, }
var UUIDRFC4122 = &Builtin{ Name: "uuid.rfc4122", Description: "Returns a new UUIDv4.", Decl: types.NewFunction( types.Args( types.Named("k", types.S).Description("seed string"), ), types.Named("output", types.S).Description("a version 4 UUID; for any given `k`, the output will be consistent throughout a query evaluation"), ), Nondeterministic: true, }
UUIDRFC4122 returns a version 4 UUID string. Marked non-deterministic because it relies on RNG internally.
var Union = &Builtin{ Name: "union", Description: "Returns the union of the given input sets.", Decl: types.NewFunction( types.Args( types.Named("xs", types.NewSet(types.SetOfAny)).Description("set of sets to merge"), ), types.Named("y", types.SetOfAny).Description("the union of all `xs` sets"), ), Categories: sets, }
var UnitsParse = &Builtin{ Name: "units.parse", Description: "" /* 590 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the unit to parse"), ), types.Named("y", types.N).Description("the parsed number"), ), }
var UnitsParseBytes = &Builtin{ Name: "units.parse_bytes", Description: "" /* 481 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("the byte unit to parse"), ), types.Named("y", types.N).Description("the parsed number"), ), }
var Upper = &Builtin{ Name: "upper", Description: "Returns the input string but with all characters in upper-case.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("string that is converted to upper-case"), ), types.Named("y", types.S).Description("upper-case of x"), ), Categories: stringsCat, }
var WalkBuiltin = &Builtin{ Name: "walk", Relation: true, Description: "" /* 145 byte string literal not displayed */, Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("value to walk"), ), types.Named("output", types.NewArray( []types.Type{ types.NewArray(nil, types.A), types.A, }, nil, )).Description("" /* 209 byte string literal not displayed */), ), Categories: graphs, }
var Weekday = &Builtin{ Name: "time.weekday", Description: "Returns the day of the week (Monday, Tuesday, ...) for the nanoseconds since epoch.", Decl: types.NewFunction( types.Args( types.Named("x", types.NewAny( types.N, types.NewArray([]types.Type{types.N, types.S}, nil), )).Description("a number representing the nanoseconds since the epoch (UTC); or a two-element array of the nanoseconds, and a timezone string"), ), types.Named("day", types.S).Description("the weekday represented by `ns` nanoseconds since the epoch in the supplied timezone (or UTC)"), ), }
Wildcard represents the wildcard variable as defined in the language.
var YAMLIsValid = &Builtin{ Name: "yaml.is_valid", Description: "Verifies the input string is a valid YAML document.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("a YAML string"), ), types.Named("result", types.B).Description("`true` if `x` is valid YAML, `false` otherwise"), ), Categories: encoding, }
YAMLIsValid verifies the input string is a valid YAML document.
var YAMLMarshal = &Builtin{ Name: "yaml.marshal", Description: "Serializes the input term to YAML.", Decl: types.NewFunction( types.Args( types.Named("x", types.A).Description("the term to serialize"), ), types.Named("y", types.S).Description("the YAML string representation of `x`"), ), Categories: encoding, }
var YAMLUnmarshal = &Builtin{ Name: "yaml.unmarshal", Description: "Deserializes the input string.", Decl: types.NewFunction( types.Args( types.Named("x", types.S).Description("a YAML string"), ), types.Named("y", types.A).Description("the term deserialized from `x`"), ), Categories: encoding, }
Functions ¶
func As ¶
As converts v into a Go native type referred to by x.
func BuildAnnotationSet ¶
func BuildAnnotationSet(modules []*Module) (*AnnotationSet, Errors)
func Compare ¶
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 < ObjectComprehension < SetComprehension < Expr < SomeDecl < With < Body < Rule < Import < Package < Module.
Arrays and Refs are equal if and only if 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 if and only if 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 if and only if the symmetric difference of a and b is empty. Other comparisons are consistent but not defined.
func ContainsClosures ¶
ContainsClosures returns true if the Value v contains closures.
func ContainsComprehensions ¶
ContainsComprehensions returns true if the Value v contains comprehensions.
func ContainsRefs ¶
ContainsRefs returns true if the Value v contains refs.
func Copy ¶
Copy returns a deep copy of the AST node x. If x is not an AST node, x is returned unmodified.
func HasInternedIntNumberTerm ¶
HasInternedIntNumberTerm returns true if the given integer value maps to an interned term, otherwise false.
func InternStringTerm ¶
func InternStringTerm(str ...string)
InternStringTerm interns the given strings as terms. Note that Interning is considered experimental and should not be relied upon by external code. WARNING: This must **only** be called at initialization time, as the interned terms are shared globally, and the underlying map is not thread-safe.
func IsComprehension ¶
IsComprehension returns true if the supplied value is a comprehension.
func IsConstant ¶
IsConstant returns true if the AST value is constant.
func IsError ¶
IsError returns true if err is an AST error with code.
func IsFutureKeyword ¶
func IsFutureKeywordForRegoVersion ¶
func IsFutureKeywordForRegoVersion(s string, v RegoVersion) bool
func IsInKeywords ¶
func IsKeyword ¶
IsKeyword returns true if s is a language keyword.
func IsKeywordInRegoVersion ¶
func IsKeywordInRegoVersion(s string, regoVersion RegoVersion) bool
IsKeywordInRegoVersion returns true if s is a language keyword.
func IsScalar ¶
IsScalar returns true if the AST value is a scalar.
func IsUnknownValueErr ¶
IsUnknownValueErr returns true if the err is an UnknownValueErr.
func IsValidImportPath ¶
IsValidImportPath returns an error indicating if the import path is invalid. If the import path is valid, err is nil.
func IsVarCompatibleString ¶
func JSON ¶
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 JSONWithOpt ¶
JSONWithOpt returns the JSON representation of v. The value must not contain any refs or terms that require evaluation (e.g., vars, comprehensions, etc.)
func KeywordsForRegoVersion ¶
func KeywordsForRegoVersion(v RegoVersion) []string
func LoadCapabilitiesVersions ¶
LoadCapabilitiesVersions loads all capabilities versions
func MustJSON ¶
MustJSON returns the JSON representation of v. The value must not contain any refs or terms that require evaluation (e.g., vars, comprehensions, etc.) If the conversion fails, this function will panic. This function is mostly for test purposes.
func ParseStatements ¶
ParseStatements is deprecated. Use ParseStatementWithOpts instead.
func ParseStatementsWithOpts ¶
func ParseStatementsWithOpts(filename, input string, popts ParserOptions) ([]Statement, []*Comment, error)
ParseStatementsWithOpts returns a slice of parsed statements. This is the default return value from the parser.
func Pretty ¶
Pretty writes a pretty representation of the AST rooted at x to w.
This is function is intended for debug purposes when inspecting ASTs.
func RefCompare ¶
func RefEqual ¶
func RegisterBuiltin ¶
func RegisterBuiltin(b *Builtin)
RegisterBuiltin adds a new built-in function to the registry.
func SetModuleRegoVersion ¶
func SetModuleRegoVersion(mod *Module, v RegoVersion)
SetModuleRegoVersion sets the RegoVersion for the Module.
func TermValueCompare ¶
func TermValueEqual ¶
func Transform ¶
func Transform(t Transformer, x any) (any, error)
Transform iterates the AST and calls the Transform function on the Transformer t for x before recursing.
func TransformComprehensions ¶
TransformComprehensions calls the functio nf on all comprehensions under x.
func TransformRefs ¶
TransformRefs calls the function f on all references under x.
func TransformVars ¶
TransformVars calls the function f on all vars under x.
func TypeName ¶
TypeName returns a human readable name for the AST element type.
func ValueEqual ¶
func ValueName ¶
ValueName returns a human readable name for the AST Value type. This is preferrable over calling TypeName when the argument is known to be a Value, as this doesn't require reflection (= heap allocations).
func ValueToInterface ¶
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 VarCompare ¶
func Walk ¶
Walk iterates the AST by calling the Visit function on the Visitor v for x before recursing. Deprecated: use GenericVisitor.Walk
func WalkBeforeAndAfter ¶
func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x any)
WalkBeforeAndAfter iterates the AST by calling the Visit function on the Visitor v for x before recursing. Deprecated: use GenericVisitor.Walk
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 ¶
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 ¶
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 WalkNodes ¶
WalkNodes calls the function f on all nodes 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 ¶
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.
func WalkTerms ¶
WalkTerms calls the function f on all terms under x. If the function f returns true, AST nodes under the last node will not be visited.
func WalkVars ¶
WalkVars calls the function f on all vars under x. If the function f returns true, AST nodes under the last node will not be visited.
func WalkWiths ¶
WalkWiths calls the function f on all with modifiers under x. If the function f returns true, AST nodes under the last node will not be visited.
Types ¶
type AnnotationSet ¶
type AnnotationSet struct {
// contains filtered or unexported fields
}
func (*AnnotationSet) Chain ¶
func (as *AnnotationSet) Chain(rule *Rule) AnnotationsRefSet
Chain returns the chain of annotations leading up to the given rule.
The returned slice is ordered as follows
0. Entries for the given rule, ordered from the METADATA block declared immediately above the rule, to the block declared farthest away (always at least one entry)
1. The 'document' scope entry, if any
2. The 'package' scope entry, if any
3. Entries for the 'subpackages' scope, if any; ordered from the closest package path to the fartest. E.g.: 'do.re.mi', 'do.re', 'do'
The returned slice is guaranteed to always contain at least one entry, corresponding to the given rule.
Test of example code in docs/content/annotations.md
Code:
Output:Example¶
{
modules := [][]string{
{
"foo.rego", `# METADATA
# scope: subpackages
# organizations:
# - Acme Corp.
package foo`},
{
"mod", `# METADATA
# description: A couple of useful rules
package foo.bar
# METADATA
# title: My Rule P
p := 7`},
}
parsed := make([]*Module, 0, len(modules))
for _, entry := range modules {
pm, err := ParseModuleWithOpts(entry[0], entry[1], ParserOptions{ProcessAnnotation: true})
if err != nil {
panic(err)
}
parsed = append(parsed, pm)
}
as, err := BuildAnnotationSet(parsed)
if err != nil {
panic(err)
}
rule := parsed[1].Rules[0]
flattened := as.Chain(rule)
for _, entry := range flattened {
fmt.Printf("%v at %v has annotations %v\n",
entry.Path,
entry.Location,
entry.Annotations)
}
// Output:
// data.foo.bar.p at mod:7 has annotations {"scope":"rule","title":"My Rule P"}
// data.foo.bar at mod:3 has annotations {"description":"A couple of useful rules","scope":"package"}
// data.foo at foo.rego:5 has annotations {"organizations":["Acme Corp."],"scope":"subpackages"}
}
data.foo.bar.p at mod:7 has annotations {"scope":"rule","title":"My Rule P"}
data.foo.bar at mod:3 has annotations {"description":"A couple of useful rules","scope":"package"}
data.foo at foo.rego:5 has annotations {"organizations":["Acme Corp."],"scope":"subpackages"}
func (*AnnotationSet) Flatten ¶
func (as *AnnotationSet) Flatten() FlatAnnotationsRefSet
Flatten returns a flattened list view of this AnnotationSet.
The returned slice is sorted, first by the annotations' target path, then by their target location
Test of example code in docs/content/annotations.md
Code:
Output:Example¶
{
modules := [][]string{
{
"foo.rego", `# METADATA
# scope: subpackages
# organizations:
# - Acme Corp.
package foo`},
{
"mod", `# METADATA
# description: A couple of useful rules
package foo.bar
# METADATA
# title: My Rule P
p := 7`},
}
parsed := make([]*Module, 0, len(modules))
for _, entry := range modules {
pm, err := ParseModuleWithOpts(entry[0], entry[1], ParserOptions{ProcessAnnotation: true})
if err != nil {
panic(err)
}
parsed = append(parsed, pm)
}
as, err := BuildAnnotationSet(parsed)
if err != nil {
panic(err)
}
flattened := as.Flatten()
for _, entry := range flattened {
fmt.Printf("%v at %v has annotations %v\n",
entry.Path,
entry.Location,
entry.Annotations)
}
// Output:
// data.foo at foo.rego:5 has annotations {"organizations":["Acme Corp."],"scope":"subpackages"}
// data.foo.bar at mod:3 has annotations {"description":"A couple of useful rules","scope":"package"}
// data.foo.bar.p at mod:7 has annotations {"scope":"rule","title":"My Rule P"}
}
data.foo at foo.rego:5 has annotations {"organizations":["Acme Corp."],"scope":"subpackages"}
data.foo.bar at mod:3 has annotations {"description":"A couple of useful rules","scope":"package"}
data.foo.bar.p at mod:7 has annotations {"scope":"rule","title":"My Rule P"}
func (*AnnotationSet) GetDocumentScope ¶
func (as *AnnotationSet) GetDocumentScope(path Ref) *Annotations
func (*AnnotationSet) GetPackageScope ¶
func (as *AnnotationSet) GetPackageScope(pkg *Package) *Annotations
func (*AnnotationSet) GetRuleScope ¶
func (as *AnnotationSet) GetRuleScope(r *Rule) []*Annotations
func (*AnnotationSet) GetSubpackagesScope ¶
func (as *AnnotationSet) GetSubpackagesScope(path Ref) []*Annotations
type Annotations ¶
type Annotations struct { Scope string `json:"scope"` Title string `json:"title,omitempty"` Entrypoint bool `json:"entrypoint,omitempty"` Description string `json:"description,omitempty"` Organizations []string `json:"organizations,omitempty"` RelatedResources []*RelatedResourceAnnotation `json:"related_resources,omitempty"` Authors []*AuthorAnnotation `json:"authors,omitempty"` Schemas []*SchemaAnnotation `json:"schemas,omitempty"` Custom map[string]any `json:"custom,omitempty"` Location *Location `json:"location,omitempty"` // contains filtered or unexported fields }
Annotations represents metadata attached to other AST nodes such as rules.
func (*Annotations) Compare ¶
func (a *Annotations) Compare(other *Annotations) int
Compare returns an integer indicating if a is less than, equal to, or greater than other.
func (*Annotations) Copy ¶
func (a *Annotations) Copy(node Node) *Annotations
Copy returns a deep copy of s.
func (*Annotations) EndLoc ¶
func (a *Annotations) EndLoc() *Location
EndLoc returns the location of this annotation's last comment line.
func (*Annotations) GetTargetPath ¶
func (a *Annotations) GetTargetPath() Ref
GetTargetPath returns the path of the node these Annotations are applied to (the target)
func (*Annotations) Loc ¶
func (a *Annotations) Loc() *Location
Loc returns the location of this annotation.
func (*Annotations) MarshalJSON ¶
func (a *Annotations) MarshalJSON() ([]byte, error)
func (*Annotations) SetLoc ¶
func (a *Annotations) SetLoc(l *Location)
SetLoc updates the location of this annotation.
func (*Annotations) String ¶
func (a *Annotations) String() string
type AnnotationsRef ¶
type AnnotationsRef struct { Path Ref `json:"path"` // The path of the node the annotations are applied to Annotations *Annotations `json:"annotations,omitempty"` Location *Location `json:"location,omitempty"` // The location of the node the annotations are applied to // contains filtered or unexported fields }
func NewAnnotationsRef ¶
func NewAnnotationsRef(a *Annotations) *AnnotationsRef
func (*AnnotationsRef) Compare ¶
func (ar *AnnotationsRef) Compare(other *AnnotationsRef) int
func (*AnnotationsRef) GetPackage ¶
func (ar *AnnotationsRef) GetPackage() *Package
func (*AnnotationsRef) GetRule ¶
func (ar *AnnotationsRef) GetRule() *Rule
func (*AnnotationsRef) MarshalJSON ¶
func (ar *AnnotationsRef) MarshalJSON() ([]byte, error)
type AnnotationsRefSet ¶
type AnnotationsRefSet []*AnnotationsRef
type ArgErrDetail ¶
ArgErrDetail represents a generic argument error.
func (*ArgErrDetail) Lines ¶
func (d *ArgErrDetail) Lines() []string
Lines returns the string representation of the detail.
type Args ¶
type Args []*Term
Args represents zero or more arguments to a rule.
func (Args) Copy ¶
Copy returns a deep copy of a.
func (Args) Loc ¶
Loc returns the Location of a.
func (Args) SetLoc ¶
SetLoc sets the location on a.
func (Args) String ¶
func (Args) Vars ¶
Vars returns a set of vars that appear in a.
type Array ¶
type Array struct {
// contains filtered or unexported fields
}
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 NewArray ¶
NewArray creates an Array with the terms provided. The array will use the provided term slice.
func (*Array) Append ¶
Append appends a term to arr, returning the appended array.
func (*Array) Compare ¶
Compare compares arr to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (*Array) Copy ¶
Copy returns a deep copy of arr.
func (*Array) Elem ¶
Elem returns the element i of arr.
func (*Array) Equal ¶
Equal returns true if arr is equal to other.
func (*Array) Find ¶
Find returns the value at the index or an out-of-range error.
func (*Array) Foreach ¶
Foreach calls f on each element in arr.
func (*Array) Get ¶
Get returns the element at pos or nil if not possible.
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) Iter ¶
Iter calls f on each element in arr. If f returns an error, iteration stops and the return value is the error.
func (*Array) Len ¶
Len returns the number of elements in the array.
func (*Array) MarshalJSON ¶
MarshalJSON returns JSON encoded bytes representing arr.
func (*Array) Set ¶
Set sets the element i of arr.
func (*Array) Slice ¶
Slice returns a slice of arr starting from i index to j. -1 indicates the end of the array. The returned value array is not a copy and any modifications to either of arrays may be reflected to the other.
func (*Array) Sorted ¶
Sorted returns a new Array that contains the sorted elements of arr.
func (*Array) String ¶
func (*Array) Until ¶
Until calls f on each element in arr. If f returns true, iteration stops.
type ArrayComprehension ¶
ArrayComprehension represents an array comprehension as defined in the language.
func (*ArrayComprehension) Compare ¶
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 ¶
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 ¶
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 AuthorAnnotation ¶
func (*AuthorAnnotation) Compare ¶
func (a *AuthorAnnotation) Compare(other *AuthorAnnotation) int
Compare returns an integer indicating if s is less than, equal to, or greater than other.
func (*AuthorAnnotation) Copy ¶
func (a *AuthorAnnotation) Copy() *AuthorAnnotation
Copy returns a deep copy of a.
func (*AuthorAnnotation) String ¶
func (a *AuthorAnnotation) String() string
type BeforeAfterVisitor ¶
type BeforeAfterVisitor struct {
// contains filtered or unexported fields
}
BeforeAfterVisitor provides a utility to walk over AST nodes using closures. If the before closure returns true, the visitor will not walk over AST nodes under x. The after closure is invoked always after visiting a node.
func NewBeforeAfterVisitor ¶
func NewBeforeAfterVisitor(before func(x any) bool, after func(x any)) *BeforeAfterVisitor
NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that will invoke the functions before and after AST nodes.
func (*BeforeAfterVisitor) Walk ¶
func (vis *BeforeAfterVisitor) Walk(x any)
Walk iterates the AST by calling the functions on the BeforeAndAfterVisitor before and after recursing. Contrary to the generic Walk, this does not require allocating the visitor from heap.
type BeforeAndAfterVisitor ¶
BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before and after the AST has been visited. Deprecated: use GenericVisitor or another visitor implementation
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 MustParseBodyWithOpts ¶
func MustParseBodyWithOpts(input string, opts ParserOptions) Body
MustParseBodyWithOpts 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 ParseBodyWithOpts ¶
func ParseBodyWithOpts(input string, popts ParserOptions) (Body, error)
ParseBodyWithOpts returns exactly one body. It does _not_ set SkipRules: true on its own, but respects whatever ParserOptions it's been given.
func (*Body) Append ¶
Append adds the expr to the body and updates the expr's index accordingly.
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) Copy ¶
Copy returns a deep copy of body.
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) MarshalJSON ¶
MarshalJSON returns JSON encoded bytes representing body.
func (Body) Set ¶
Set sets the expr in the body at the specified position and updates the expr's index accordingly.
func (Body) SetLoc ¶
SetLoc sets the location on body.
func (Body) String ¶
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 ¶
Compare compares bol to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Boolean) Equal ¶
Equal returns true if the other Value is a Boolean and is equal.
func (Boolean) Find ¶
Find returns the current value or a not found error.
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 string `json:"name"` // Unique name of built-in function, e.g., <name>(arg1,arg2,...,argN) Description string `json:"description,omitempty"` // Description of what the built-in function does. // Categories of the built-in function. Omitted for namespaced // built-ins, i.e. "array.concat" is taken to be of the "array" category. // "minus" for example, is part of two categories: numbers and sets. (NOTE(sr): aspirational) Categories []string `json:"categories,omitempty"` Decl *types.Function `json:"decl"` // Built-in function type declaration. Infix string `json:"infix,omitempty"` // Unique name of infix operator. Default should be unset. Relation bool `json:"relation,omitempty"` // Indicates if the built-in acts as a relation. Nondeterministic bool `json:"nondeterministic,omitempty"` // Indicates if the built-in returns non-deterministic results. // contains filtered or unexported fields }
Builtin represents a built-in function supported by OPA. Every built-in function is uniquely identified by a name.
func (*Builtin) Call ¶
Call creates a new term for the built-in with the given operands.
func (*Builtin) Expr ¶
Expr creates a new expression for the built-in with the given operands.
func (*Builtin) IsDeprecated ¶
IsDeprecated returns true if the Builtin function is deprecated and will be removed in a future release.
func (*Builtin) IsNondeterministic ¶
IsDeterministic returns true if the Builtin function returns non-deterministic results.
func (*Builtin) IsTargetPos ¶
IsTargetPos returns true if a variable in the i-th position will be bound by evaluating the call expression.
func (*Builtin) Minimal ¶
Minimal returns a shallow copy of b with the descriptions and categories and named arguments stripped out.
func (*Builtin) Ref ¶
Ref returns a Ref that refers to the built-in function.
type Call ¶
type Call []*Term
Call represents as function call in the language.
func (Call) Compare ¶
Compare compares c to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Call) Copy ¶
Copy returns a deep copy of c.
func (Call) Find ¶
Find returns the current value or a not found error.
func (Call) Hash ¶
Hash returns the hash code for the Value.
func (Call) IsGround ¶
IsGround returns true if the Value is ground.
func (Call) MakeExpr ¶
MakeExpr returns an ew Expr from this call.
func (Call) String ¶
type Capabilities ¶
type Capabilities struct { Builtins []*Builtin `json:"builtins,omitempty"` FutureKeywords []string `json:"future_keywords,omitempty"` WasmABIVersions []WasmABIVersion `json:"wasm_abi_versions,omitempty"` // Features is a bit of a mixed bag for checking that an older version of OPA // is able to do what needs to be done. // TODO(sr): find better words ^^ Features []string `json:"features,omitempty"` // allow_net is an array of hostnames or IP addresses, that an OPA instance is // allowed to connect to. // If omitted, ANY host can be connected to. If empty, NO host can be connected to. // As of now, this only controls fetching remote refs for using JSON Schemas in // the type checker. // TODO(sr): support ports to further restrict connection peers // TODO(sr): support restricting `http.send` using the same mechanism (see https://github.com/open-policy-agent/opa/issues/3665) AllowNet []string `json:"allow_net,omitempty"` }
Capabilities defines a structure containing data that describes the capabilities or features supported by a particular version of OPA.
func CapabilitiesForThisVersion ¶
func CapabilitiesForThisVersion(opts ...CapabilitiesOption) *Capabilities
CapabilitiesForThisVersion returns the capabilities of this version of OPA.
func LoadCapabilitiesFile ¶
func LoadCapabilitiesFile(file string) (*Capabilities, error)
LoadCapabilitiesFile loads a JSON serialized capabilities structure from a file.
func LoadCapabilitiesJSON ¶
func LoadCapabilitiesJSON(r io.Reader) (*Capabilities, error)
LoadCapabilitiesJSON loads a JSON serialized capabilities structure from the reader r.
func LoadCapabilitiesVersion ¶
func LoadCapabilitiesVersion(version string) (*Capabilities, error)
LoadCapabilitiesVersion loads a JSON serialized capabilities structure from the specific version.
func (*Capabilities) ContainsFeature ¶
func (c *Capabilities) ContainsFeature(feature string) bool
func (*Capabilities) MinimumCompatibleVersion ¶
func (c *Capabilities) MinimumCompatibleVersion() (string, bool)
MinimumCompatibleVersion returns the minimum compatible OPA version based on the built-ins, features, and keywords in c.
type CapabilitiesOption ¶
type CapabilitiesOption func(*CapabilitiesOptions)
func CapabilitiesRegoVersion ¶
func CapabilitiesRegoVersion(regoVersion RegoVersion) CapabilitiesOption
type CapabilitiesOptions ¶
type CapabilitiesOptions struct {
// contains filtered or unexported fields
}
type Comment ¶
type Comment struct { // TODO: these fields have inconsistent JSON keys with other structs in this package. Text []byte Location *Location }
Comment contains the raw text from the comment in the definition.
func NewComment ¶
NewComment returns a new Comment object.
func (*Comment) Copy ¶
Copy returns a deep copy of c.
func (*Comment) Equal ¶
Equal returns true if this comment equals the other comment. Unlike other equality checks on AST nodes, comment equality depends on location.
func (*Comment) Loc ¶
Loc returns the location of the comment in the definition.
func (*Comment) SetLoc ¶
SetLoc sets the location on c.
func (*Comment) String ¶
type CompileOpts ¶
type CompileOpts struct { EnablePrintStatements bool ParserOptions ParserOptions }
CompileOpts defines a set of options for the compiler.
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 // a.b.c = 3 // // root // | // +--- data (no rules) // | // +--- ex (no rules) // | // +--- p (2 rules) // | // +--- q (1 rule) // | // +--- a // | // +--- b // | // +--- c (1 rule) // // Another example with general refs containing vars at arbitrary locations: // // package ex // a.b[x].d { x := "c" } # R1 // a.b.c[x] { x := "d" } # R2 // a.b[x][y] { x := "c"; y := "d" } # R3 // p := true # R4 // // root // | // +--- data (no rules) // | // +--- ex (no rules) // | // +--- a // | | // | +--- b (R1, R3) // | | // | +--- c (R2) // | // +--- p (R4) RuleTree *TreeNode // Graph contains dependencies between rules. An edge (u,v) is added to the // graph if rule 'u' refers to the virtual document defined by 'v'. Graph *Graph // TypeEnv holds type information for values inferred by the compiler. TypeEnv *TypeEnv // RewrittenVars is a mapping of variables that have been rewritten // with the key being the generated name and value being the original. RewrittenVars map[Var]Var // Capabilities required by the modules that were compiled. Required *Capabilities // contains filtered or unexported fields }
Compiler contains the state of a compilation process.
func CompileModules ¶
CompileModules takes a set of Rego modules represented as strings and compiles them for evaluation. The keys of the map are used as filenames.
func CompileModulesWithOpt ¶
func CompileModulesWithOpt(modules map[string]string, opts CompileOpts) (*Compiler, error)
CompileModulesWithOpt takes a set of Rego modules represented as strings and compiles them for evaluation. The keys of the map are used as filenames.
func MustCompileModules ¶
MustCompileModules compiles a set of Rego modules represented as strings. If the compilation process fails, this function panics.
func MustCompileModulesWithOpts ¶
func MustCompileModulesWithOpts(modules map[string]string, opts CompileOpts) *Compiler
MustCompileModulesWithOpts compiles a set of Rego modules represented as strings. If the compilation process fails, this function panics.
func NewCompiler ¶
func NewCompiler() *Compiler
NewCompiler returns a new empty compiler.
func (*Compiler) Capabilities ¶
func (c *Compiler) Capabilities() *Capabilities
Capabilities returns the capabilities enabled during compilation.
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/v1/ast"
)
func main() {
// Define an input module that will be compiled.
exampleModule := `package opa.example
import rego.v1
import data.foo
import input.bar
p[x] if { foo[x]; not bar[x]; x >= min_x }
min_x = 100 if { 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])
fmt.Println("Expr 4:", c.Modules["my_module"].Rules[0].Body[3])
}
Expr 1: data.foo[x]
Expr 2: not input.bar[x]
Expr 3: __local0__ = data.opa.example.min_x
Expr 4: gte(x, __local0__)
func (*Compiler) ComprehensionIndex ¶
func (c *Compiler) ComprehensionIndex(term *Term) *ComprehensionIndex
ComprehensionIndex returns a data structure specifying how to index comprehension results so that callers do not have to recompute the comprehension more than once. If no index is found, returns nil.
func (*Compiler) DefaultRegoVersion ¶
func (c *Compiler) DefaultRegoVersion() RegoVersion
func (*Compiler) Failed ¶
Failed returns true if a compilation error has been encountered.
func (*Compiler) GetAnnotationSet ¶
func (c *Compiler) GetAnnotationSet() *AnnotationSet
func (*Compiler) GetArity ¶
GetArity returns the number of args a function referred to by ref takes. If ref refers to built-in function, the built-in declaration is consulted, otherwise, the ref is used to perform a ruleset lookup.
func (*Compiler) GetRules ¶
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) GetRulesDynamic ¶
GetRulesDynamic returns a slice of rules that could be referred to by a ref.
Deprecated: use GetRulesDynamicWithOpts
func (*Compiler) GetRulesDynamicWithOpts ¶
func (c *Compiler) GetRulesDynamicWithOpts(ref Ref, opts RulesOptions) []*Rule
GetRulesDynamicWithOpts returns a slice of rules that could be referred to by a ref. When parts of the ref are statically known, we use that information to narrow down which rules the ref could refer to, but in the most general case this will be an over-approximation.
E.g., given the following modules:
package a.b.c r1 = 1 # rule1
and:
package a.d.c r2 = 2 # rule2
The following calls yield the rules on the right.
GetRulesDynamicWithOpts("data.a[x].c[y]", opts) => [rule1, rule2] GetRulesDynamicWithOpts("data.a[x].c.r2", opts) => [rule2] GetRulesDynamicWithOpts("data.a.b[x][y]", opts) => [rule1]
Using the RulesOptions parameter, the inclusion of hidden modules can be controlled:
With
package system.main r3 = 3 # rule3
We'd get this result:
GetRulesDynamicWithOpts("data[x]", RulesOptions{IncludeHiddenModules: true}) => [rule1, rule2, rule3]
Without the options, it would be excluded.
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]
func (*Compiler) ParsedModules ¶
ParsedModules returns the parsed, unprocessed modules from the compiler. It is `nil` if keeping modules wasn't enabled via `WithKeepModules(true)`. The map includes all modules loaded via the ModuleLoader, if one was used.
func (*Compiler) PassesTypeCheck ¶
PassesTypeCheck determines whether the given body passes type checking
func (*Compiler) PassesTypeCheckRules ¶
PassesTypeCheckRules determines whether the given rules passes type checking
func (*Compiler) QueryCompiler ¶
func (c *Compiler) QueryCompiler() QueryCompiler
func (*Compiler) RuleIndex ¶
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 ¶
SetErrorLimit sets the number of errors the compiler can encounter before it quits. Zero or a negative number indicates no limit.
func (*Compiler) WithAllowUndefinedFunctionCalls ¶
func (*Compiler) WithBuiltins ¶
WithBuiltins is deprecated. Deprecated: Use WithCapabilities instead.
func (*Compiler) WithCapabilities ¶
func (c *Compiler) WithCapabilities(capabilities *Capabilities) *Compiler
WithCapabilities sets capabilities to enable during compilation. Capabilities allow the caller to specify the set of built-in functions available to the policy. In the future, capabilities may be able to restrict access to other language features. Capabilities allow callers to check if policies are compatible with a particular version of OPA. If policies are a compiled for a specific version of OPA, there is no guarantee that _this_ version of OPA can evaluate them successfully.
func (*Compiler) WithDebug ¶
WithDebug sets where debug messages are written to. Passing `nil` has no effect.
func (*Compiler) WithDefaultRegoVersion ¶
func (c *Compiler) WithDefaultRegoVersion(regoVersion RegoVersion) *Compiler
WithDefaultRegoVersion sets the default Rego version to use when a module doesn't specify one; such as when it's hand-crafted instead of parsed.
func (*Compiler) WithEnablePrintStatements ¶
WithEnablePrintStatements enables print statements inside of modules compiled by the compiler. If print statements are not enabled, calls to print() are erased at compile-time.
func (*Compiler) WithEvalMode ¶
func (c *Compiler) WithEvalMode(e CompilerEvalMode) *Compiler
WithEvalMode allows setting the CompilerEvalMode of the compiler
func (*Compiler) WithKeepModules ¶
WithKeepModules enables retaining unprocessed modules in the compiler. Note that the modules aren't copied on the way in or out -- so when accessing them via ParsedModules(), mutations will occur in the module map that was passed into Compile().`
func (*Compiler) WithMetrics ¶
WithMetrics will set a metrics.Metrics and be used for profiling the Compiler instance.
func (*Compiler) WithModuleLoader ¶
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.
func (*Compiler) WithPathConflictsCheck ¶
WithPathConflictsCheck enables base-virtual document conflict detection. The compiler will check that rules don't overlap with paths that exist as determined by the provided callable.
func (*Compiler) WithPathConflictsCheckRoots ¶
WithPathConflictsCheckRoots enables checking path conflicts from the specified root instead of the top root node. Limiting conflict checks to a known set of roots, such as bundle roots, improves performance. Each root has the format of a "/"-delimited string, excluding the "data" root document.
func (*Compiler) WithRewriteTestRules ¶
WithRewriteTestRules enables rewriting test rules to capture dynamic values in local variables, so they can be accessed by tracing.
func (*Compiler) WithSchemas ¶
WithSchemas sets a schemaSet to the compiler
func (*Compiler) WithStageAfter ¶
func (c *Compiler) WithStageAfter(after string, stage CompilerStageDefinition) *Compiler
WithStageAfter registers a stage to run during compilation after the named stage.
func (*Compiler) WithStrict ¶
WithStrict toggles strict mode in the compiler.
func (*Compiler) WithUnsafeBuiltins ¶
WithUnsafeBuiltins is deprecated. Deprecated: Use WithCapabilities instead.
func (*Compiler) WithUseTypeCheckAnnotations ¶
WithUseTypeCheckAnnotations use schema annotations during type checking
type CompilerEvalMode ¶
type CompilerEvalMode int
CompilerEvalMode allows toggling certain stages that are only needed for certain modes, Concretely, only "topdown" mode will have the compiler build comprehension and rule indices.
const ( // EvalModeTopdown (default) instructs the compiler to build rule // and comprehension indices used by topdown evaluation. EvalModeTopdown CompilerEvalMode = iota // EvalModeIR makes the compiler skip the stages for comprehension // and rule indices. EvalModeIR )
type CompilerStage ¶
CompilerStage defines the interface for stages in the compiler.
type CompilerStageDefinition ¶
type CompilerStageDefinition struct { Name string MetricName string Stage CompilerStage }
CompilerStageDefinition defines a compiler stage
type ComprehensionIndex ¶
ComprehensionIndex specifies how the comprehension term can be indexed. The keys tell the evaluator what variables to use for indexing. In the future, the index could be expanded with more information that would allow the evaluator to index a larger fragment of comprehensions (e.g., by closing over variables in the outer query.)
func (*ComprehensionIndex) String ¶
func (ci *ComprehensionIndex) String() string
type DocKind ¶
type DocKind byte
DocKind represents the collection of document types that can be produced by rules.
type Error ¶
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.
func NewError ¶
NewError returns a new Error object.
func (*Error) Error ¶
type ErrorDetails ¶
type ErrorDetails interface { Lines() []string }
ErrorDetails defines the interface for detailed error messages.
type Errors ¶
type Errors []*Error
Errors represents a series of errors encountered during parsing, compiling, etc.
func CheckPathConflicts ¶
CheckPathConflicts returns a set of errors indicating paths that are in conflict with the result of the provided callable.
func CheckRegoV1 ¶
CheckRegoV1 checks the given module or rule for errors that are specific to Rego v1. Passing something other than an *ast.Rule or *ast.Module is considered a programming error, and will cause a panic.
func CheckRegoV1WithOptions ¶
func CheckRegoV1WithOptions(x any, opts RegoCheckOptions) Errors
func (Errors) Error ¶
func (Errors) Sort ¶
func (e Errors) Sort()
Sort sorts the error slice by location. If the locations are equal then the error message is compared.
type Every ¶
type Every struct { Key *Term `json:"key"` Value *Term `json:"value"` Domain *Term `json:"domain"` Body Body `json:"body"` Location *Location `json:"location,omitempty"` }
func (*Every) Compare ¶
func (*Every) Copy ¶
Copy returns a deep copy of d.
func (*Every) KeyValueVars ¶
KeyValueVars returns the key and val arguments of an `every` expression, if they are non-nil and not wildcards.
func (*Every) Loc ¶
func (*Every) MarshalJSON ¶
func (*Every) SetLoc ¶
func (*Every) String ¶
type Expr ¶
type Expr struct { With []*With `json:"with,omitempty"` Terms any `json:"terms"` Index int `json:"index"` Generated bool `json:"generated,omitempty"` Negated bool `json:"negated,omitempty"` Location *Location `json:"location,omitempty"` // contains filtered or unexported fields }
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 NewExpr ¶
NewExpr returns a new Expr object.
func ParseExpr ¶
ParseExpr returns exactly one expression. If multiple expressions are parsed, an error is returned.
func (*Expr) BaseCogeneratedExpr ¶
func (*Expr) CogeneratedExprs ¶
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. Declarations are always less than other expressions. 2. Preceding expression (by Index) is always less than the other expression. 3. Non-negated expressions are always less than negated expressions. 4. 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) ComplementNoWith ¶
ComplementNoWith returns a copy of this expression with the negation flag flipped and the with modifier removed. This is the same as calling .Complement().NoWith() but without making an intermediate copy.
func (*Expr) Copy ¶
Copy returns a deep copy of expr.
func (*Expr) CopyWithoutTerms ¶
CopyWithoutTerms returns a deep copy of expr without its Terms
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) IncludeWith ¶
IncludeWith returns a copy of expr with the with modifier appended.
func (*Expr) IsAssignment ¶
IsAssignment returns true if this an assignment expression.
func (*Expr) IsCall ¶
IsCall returns true if this expression calls a function.
func (*Expr) IsEquality ¶
IsEquality returns true if this is an equality expression.
func (*Expr) IsEvery ¶
IsEvery returns true if this expression is an 'every' expression.
func (*Expr) IsGround ¶
IsGround returns true if all of the expression terms are ground.
func (*Expr) IsSome ¶
IsSome returns true if this expression is a 'some' expression.
func (*Expr) Loc ¶
Loc returns the Location of expr.
func (*Expr) MarshalJSON ¶
func (*Expr) NoWith ¶
NoWith returns a copy of expr where the with modifier has been removed.
func (*Expr) Operand ¶
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) Operands ¶
Operands returns the built-in function operands.
func (*Expr) Operator ¶
Operator returns the name of the function or built-in this expression refers to. If this expression is not a function call, returns nil.
func (*Expr) OperatorTerm ¶
OperatorTerm returns the name of the function or built-in this expression refers to. If this expression is not a function call, returns nil.
func (*Expr) SetLoc ¶
SetLoc sets the location on expr.
func (*Expr) SetLocation ¶
SetLocation sets the expr's location and returns the expr itself.
func (*Expr) SetOperator ¶
SetOperator sets the expr's operator and returns the expr itself. If expr is not a call expr, this function will panic.
func (*Expr) String ¶
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 FlatAnnotationsRefSet ¶
type FlatAnnotationsRefSet AnnotationsRefSet
func (FlatAnnotationsRefSet) Insert ¶
func (ars FlatAnnotationsRefSet) Insert(ar *AnnotationsRef) FlatAnnotationsRefSet
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 NewGenericTransformer ¶
func NewGenericTransformer(f func(x any) (any, error)) *GenericTransformer
NewGenericTransformer returns a new GenericTransformer that will transform AST nodes using the function f.
func (*GenericTransformer) Transform ¶
func (t *GenericTransformer) Transform(x any) (any, error)
Transform calls the function f on the GenericTransformer.
type GenericVisitor ¶
type GenericVisitor struct {
// contains filtered or unexported fields
}
GenericVisitor provides 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 ¶
func NewGenericVisitor(f func(x any) bool) *GenericVisitor
NewGenericVisitor returns a new GenericVisitor that will invoke the function f on AST nodes.
func (*GenericVisitor) Walk ¶
func (vis *GenericVisitor) Walk(x any)
Walk iterates the AST by calling the function f on the GenericVisitor before recursing. Contrary to the generic Walk, this does not require allocating the visitor from heap.
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph represents the graph of dependencies between rules.
func NewGraph ¶
NewGraph returns a new Graph based on modules. The list function must return the rules referred to directly by the ref.
func (*Graph) Dependencies ¶
Dependencies returns the set of rules that x depends on.
func (*Graph) Dependents ¶
Dependents returns the set of rules that depend on x.
func (*Graph) Sort ¶
Sort returns a slice of rules sorted by dependencies. If a cycle is found, ok is set to false.
type GraphTraversal ¶
type GraphTraversal struct {
// contains filtered or unexported fields
}
GraphTraversal is a Traversal that understands the dependency graph
func NewGraphTraversal ¶
func NewGraphTraversal(graph *Graph) *GraphTraversal
NewGraphTraversal returns a Traversal for the dependency graph
func (*GraphTraversal) Edges ¶
func (g *GraphTraversal) Edges(x util.T) []util.T
Edges lists all dependency connections for a given node
func (*GraphTraversal) Visited ¶
func (g *GraphTraversal) Visited(u util.T) bool
Visited returns whether a node has been visited, setting a node to visited if not
type Head ¶
type Head struct { Name Var `json:"name,omitempty"` Reference Ref `json:"ref,omitempty"` Args Args `json:"args,omitempty"` Key *Term `json:"key,omitempty"` Value *Term `json:"value,omitempty"` Assign bool `json:"assign,omitempty"` Location *Location `json:"location,omitempty"` // contains filtered or unexported fields }
Head represents the head of a rule.
func NewHead ¶
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 RefHead ¶
RefHead returns a new Head object with the passed Ref. If args are provided, the first will be used for the value.
func VarHead ¶
VarHead creates a head object, initializes its Name and Location and returns the new head. NOTE: The JSON options argument is no longer used, and kept only for backwards compatibility.
func (*Head) Compare ¶
Compare returns an integer indicating whether head is less than, equal to, or greater than other.
func (*Head) Copy ¶
Copy returns a deep copy of head.
func (*Head) DocKind ¶
DocKind returns the type of document produced by this rule.
func (*Head) Equal ¶
Equal returns true if this head equals other.
func (*Head) HasDynamicRef ¶
func (*Head) Loc ¶
Loc returns the Location of head.
func (*Head) MarshalJSON ¶
func (*Head) Ref ¶
Ref returns the Ref of the rule. If it doesn't have one, it's filled in via the Head's Name.
func (*Head) RuleKind ¶
RuleKind returns the type of rule this is
func (*Head) SetLoc ¶
SetLoc sets the location on head.
func (*Head) SetRef ¶
SetRef can be used to set a rule head's Reference
func (*Head) String ¶
func (*Head) Vars ¶
Vars returns a set of vars found in the head.
type Import ¶
type Import struct { Path *Term `json:"path"` Alias Var `json:"alias,omitempty"` Location *Location `json:"location,omitempty"` }
Import represents a dependency on a document outside of the policy namespace. Imports are optional.
func MustParseImports ¶
MustParseImports returns a slice of imports. If an error occurs during parsing, panic.
func ParseImports ¶
ParseImports returns a slice of Import objects.
func (*Import) Compare ¶
Compare returns an integer indicating whether imp is less than, equal to, or greater than other.
func (*Import) Copy ¶
Copy returns a deep copy of imp.
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) MarshalJSON ¶
func (*Import) Name ¶
Name returns the variable that is used to refer to the imported virtual document. This is the alias if defined otherwise the last element in the path.
func (*Import) SetLoc ¶
SetLoc sets the location on imp.
func (*Import) String ¶
type IndexResult ¶
type IndexResult struct { Rules []*Rule Else map[*Rule][]*Rule Default *Rule Kind RuleKind EarlyExit bool OnlyGroundRefs bool }
IndexResult contains the result of an index lookup.
func NewIndexResult ¶
func NewIndexResult(kind RuleKind) *IndexResult
NewIndexResult returns a new IndexResult object.
func (*IndexResult) Empty ¶
func (ir *IndexResult) Empty() bool
Empty returns true if there are no rules to evaluate.
type JSONOpt ¶
type JSONOpt struct { SortSets bool // sort sets before serializing (this makes conversion more expensive) CopyMaps bool // enforces copying of map[string]any read from the store }
JSONOpt defines parameters for AST to JSON conversion.
type Location ¶
Location records a position in source code.
func NewLocation ¶
NewLocation returns a new Location object.
type Module ¶
type Module struct { Package *Package `json:"package"` Imports []*Import `json:"imports,omitempty"` Annotations []*Annotations `json:"annotations,omitempty"` Rules []*Rule `json:"rules,omitempty"` Comments []*Comment `json:"comments,omitempty"` // contains filtered or unexported fields }
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 MustParseModuleWithOpts ¶
func MustParseModuleWithOpts(input string, opts ParserOptions) *Module
MustParseModuleWithOpts 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 ParseModuleWithOpts ¶
func ParseModuleWithOpts(filename, input string, popts ParserOptions) (*Module, error)
ParseModuleWithOpts returns a parsed Module object, and has an additional input ParserOptions 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) Copy ¶
Copy returns a deep copy of mod.
func (*Module) Equal ¶
Equal returns true if mod equals other.
func (*Module) RegoVersion ¶
func (mod *Module) RegoVersion() RegoVersion
func (*Module) RuleSet ¶
RuleSet returns a RuleSet containing named rules in the mod.
func (*Module) SetRegoVersion ¶
func (mod *Module) SetRegoVersion(v RegoVersion)
SetRegoVersion sets the RegoVersion for the module. Note: Setting a rego-version that does not match the module's rego-version might have unintended consequences.
func (*Module) String ¶
func (*Module) UnmarshalJSON ¶
UnmarshalJSON parses bs and stores the result in mod. The rules in the module will have their module pointer set to mod.
type ModuleLoader ¶
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 ¶
func (n *ModuleTreeNode) DepthFirst(f func(*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.
func (*ModuleTreeNode) String ¶
func (n *ModuleTreeNode) String() string
type Node ¶
Node represents a node in an AST. Nodes may be statements in a policy module or elements of an ad-hoc query, expression, etc.
type Null ¶
type Null struct{}
Null represents the null value defined by JSON.
func (Null) Compare ¶
Compare compares null to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Null) Equal ¶
Equal returns true if the other term Value is also Null.
func (Null) Find ¶
Find returns the current value or a not found error.
func (Null) Hash ¶
Hash returns the hash code for the Value.
func (Null) IsGround ¶
IsGround always returns true.
func (Null) String ¶
type Number ¶
Number represents a numeric value as defined by JSON.
func (Number) Compare ¶
Compare compares num to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Number) Equal ¶
Equal returns true if the other Value is a Number and is equal.
func (Number) Find ¶
Find returns the current value or a not found error.
func (Number) Float64 ¶
Float64 returns the float64 representation of num if possible.
func (Number) Hash ¶
Hash returns the hash code for the Value.
func (Number) Int ¶
Int returns the int representation of num if possible.
func (Number) Int64 ¶
Int64 returns the int64 representation of num if possible.
func (Number) IsGround ¶
IsGround always returns true.
func (Number) MarshalJSON ¶
MarshalJSON returns JSON encoded bytes representing num.
func (Number) String ¶
type Object ¶
type Object interface { Value Len() int Get(*Term) *Term Copy() Object Insert(*Term, *Term) Iter(func(*Term, *Term) error) error Until(func(*Term, *Term) bool) bool Foreach(func(*Term, *Term)) Map(func(*Term, *Term) (*Term, *Term, error)) (Object, error) Diff(other Object) Object Intersect(other Object) [][3]*Term Merge(other Object) (Object, bool) MergeWith(other Object, conflictResolver func(v1, v2 *Term) (*Term, bool)) (Object, bool) Filter(filter Object) (Object, error) Keys() []*Term KeysIterator() ObjectKeysIterator // contains filtered or unexported methods }
Object represents an object as defined by the language.
func LazyObject ¶
func NewObject ¶
NewObject creates a new Object with t.
type ObjectComprehension ¶
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 ¶
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 ¶
func (oc *ObjectComprehension) Copy() *ObjectComprehension
Copy returns a deep copy of oc.
func (*ObjectComprehension) Equal ¶
func (oc *ObjectComprehension) Equal(other Value) bool
Equal returns true if oc is equal to other.
func (*ObjectComprehension) Find ¶
func (oc *ObjectComprehension) Find(path Ref) (Value, error)
Find returns the current value or a not found error.
func (*ObjectComprehension) Hash ¶
func (oc *ObjectComprehension) Hash() int
Hash returns the hash code of the Value.
func (*ObjectComprehension) IsGround ¶
func (oc *ObjectComprehension) IsGround() bool
IsGround returns true if the Key, Value and Body are ground.
func (*ObjectComprehension) String ¶
func (oc *ObjectComprehension) String() string
type ObjectKeysIterator ¶
NOTE(philipc): The only way to get an ObjectKeyIterator should be from an Object. This ensures that the iterator can have implementation- specific details internally, with no contracts except to the very limited interface.
type Package ¶
Package represents the namespace of the documents produced by rules inside the module.
func MustParsePackage ¶
MustParsePackage returns a Package. If an error occurs during parsing, panic.
func ParsePackage ¶
ParsePackage returns exactly one Package. If multiple statements are parsed, an error is returned.
func (*Package) Compare ¶
Compare returns an integer indicating whether pkg is less than, equal to, or greater than other.
func (*Package) Copy ¶
Copy returns a deep copy of pkg.
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) MarshalJSON ¶
func (*Package) SetLoc ¶
SetLoc sets the location on pkg.
func (*Package) String ¶
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser is used to parse Rego statements.
func NewParser ¶
func NewParser() *Parser
NewParser creates and initializes a Parser.
func (*Parser) Parse ¶
Parse will read the Rego source and parse statements and comments as they are found. Any errors encountered while parsing will be accumulated and returned as a list of Errors.
func (*Parser) WithAllFutureKeywords ¶
WithAllFutureKeywords enables all "future" keywords, i.e., the ParserOption equivalent of
import future.keywords
func (*Parser) WithCapabilities ¶
func (p *Parser) WithCapabilities(c *Capabilities) *Parser
WithCapabilities sets the capabilities structure on the parser.
func (*Parser) WithFilename ¶
WithFilename provides the filename for Location details on parsed statements.
func (*Parser) WithFutureKeywords ¶
WithFutureKeywords enables "future" keywords, i.e., keywords that can be imported via
import future.keywords.kw import future.keywords.other
but in a more direct way. The equivalent of this import would be
WithFutureKeywords("kw", "other")
func (*Parser) WithJSONOptions ¶
WithJSONOptions sets the JSON options on the parser (now a no-op).
Deprecated: Use SetOptions in the json package instead, where a longer description of why this is deprecated also can be found.
func (*Parser) WithMaxRecursionDepth ¶
WithMaxRecursionDepth sets the maximum recursion depth for the parser.
func (*Parser) WithProcessAnnotation ¶
WithProcessAnnotation enables or disables the processing of annotations by the Parser
func (*Parser) WithReader ¶
WithReader provides the io.Reader that the parser will use as its source.
func (*Parser) WithRegoVersion ¶
func (p *Parser) WithRegoVersion(version RegoVersion) *Parser
func (*Parser) WithSkipRules ¶
WithSkipRules instructs the parser not to attempt to parse Rule statements.
type ParserErrorDetail ¶
ParserErrorDetail holds additional details for parser errors.
func (ParserErrorDetail) Lines ¶
func (d ParserErrorDetail) Lines() []string
Lines returns the pretty formatted line output for the error details.
type ParserOptions ¶
type ParserOptions struct { Capabilities *Capabilities ProcessAnnotation bool AllFutureKeywords bool FutureKeywords []string SkipRules bool // RegoVersion is the version of Rego to parse for. RegoVersion RegoVersion // contains filtered or unexported fields }
ParserOptions defines the options for parsing Rego statements.
func (*ParserOptions) EffectiveRegoVersion ¶
func (po *ParserOptions) EffectiveRegoVersion() RegoVersion
EffectiveRegoVersion returns the effective RegoVersion to use for parsing.
type QueryCompiler ¶
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 // WithEnablePrintStatements enables print statements in queries compiled // with the QueryCompiler. WithEnablePrintStatements(yes bool) QueryCompiler // WithUnsafeBuiltins sets the built-in functions to treat as unsafe and not // allow inside of queries. By default the query compiler inherits the // compiler's unsafe built-in functions. This function allows callers to // override that set. If an empty (non-nil) map is provided, all built-ins // are allowed. WithUnsafeBuiltins(unsafe map[string]struct{}) QueryCompiler // WithStageAfter registers a stage to run during query compilation after // the named stage. WithStageAfter(after string, stage QueryCompilerStageDefinition) QueryCompiler // RewrittenVars maps generated vars in the compiled query to vars from the // parsed query. For example, given the query "input := 1" the rewritten // query would be "__local0__ = 1". The mapping would then be {__local0__: input}. RewrittenVars() map[Var]Var // ComprehensionIndex returns an index data structure for the given comprehension // term. If no index is found, returns nil. ComprehensionIndex(term *Term) *ComprehensionIndex // WithStrict enables strict mode for the query compiler. WithStrict(strict bool) QueryCompiler }
QueryCompiler defines the interface for compiling ad-hoc queries.
type QueryCompilerStage ¶
type QueryCompilerStage func(QueryCompiler, Body) (Body, error)
QueryCompilerStage defines the interface for stages in the query compiler.
type QueryCompilerStageDefinition ¶
type QueryCompilerStageDefinition struct { Name string MetricName string Stage QueryCompilerStage }
QueryCompilerStageDefinition defines a QueryCompiler stage
type QueryContext ¶
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 ¶
func NewQueryContext() *QueryContext
NewQueryContext returns a new QueryContext object.
func (*QueryContext) Copy ¶
func (qc *QueryContext) Copy() *QueryContext
Copy returns a deep copy of qc.
func (*QueryContext) WithImports ¶
func (qc *QueryContext) WithImports(imports []*Import) *QueryContext
WithImports sets the imports on qc.
func (*QueryContext) WithPackage ¶
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 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 PtrRef ¶
PtrRef returns a new reference against the head for the pointer s. Path components in the pointer are unescaped.
func (Ref) Append ¶
Append returns a copy of ref with the term appended to the end.
func (Ref) Compare ¶
Compare compares ref to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (Ref) Concat ¶
Concat returns a ref with the terms appended.
func (Ref) ConstantPrefix ¶
ConstantPrefix returns the constant portion of the ref starting from the head.
func (Ref) Copy ¶
Copy returns a deep copy of ref.
func (Ref) CopyNonGround ¶
CopyNonGround returns a new ref with deep copies of the non-ground parts and shallow copies of the ground parts. This is a *much* cheaper operation than Copy for operations that only intend to modify (e.g. plug) the non-ground parts. The head element of the ref is always shallow copied.
func (Ref) Dynamic ¶
Dynamic returns the offset of the first non-constant operand of ref.
func (Ref) DynamicSuffix ¶
func (Ref) Equal ¶
Equal returns true if ref is equal to other.
func (Ref) Extend ¶
Extend returns a copy of ref with the terms from other appended. The head of other will be converted to a string.
func (Ref) Find ¶
Find returns the current value or a "not found" error.
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) Insert ¶
Insert returns a copy of the ref with x inserted at pos. If pos < len(ref), existing elements are shifted to the right. If pos > len(ref)+1 this function panics.
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) Ptr ¶
Ptr returns a slash-separated path string for this ref. If the ref contains non-string terms this function returns an error. Path components are escaped.
func (Ref) String ¶
func (Ref) StringPrefix ¶
type RefErrInvalidDetail ¶
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 ¶
func (r *RefErrInvalidDetail) Lines() []string
Lines returns the string representation of the detail.
type RefErrUnsupportedDetail ¶
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 ¶
func (r *RefErrUnsupportedDetail) Lines() []string
Lines returns the string representation of the detail.
type RegoCheckOptions ¶
type RegoCheckOptions struct { NoDuplicateImports bool NoRootDocumentOverrides bool NoDeprecatedBuiltins bool NoKeywordsAsRuleNames bool RequireIfKeyword bool RequireContainsKeyword bool RequireRuleBodyOrValue bool }
func NewRegoCheckOptions ¶
func NewRegoCheckOptions() RegoCheckOptions
type RegoVersion ¶
type RegoVersion int
RegoVersion defines the Rego syntax requirements for a module.
const ( RegoUndefined RegoVersion = iota // RegoV0 is the default, original Rego syntax. RegoV0 // RegoV0CompatV1 requires modules to comply with both the RegoV0 and RegoV1 syntax (as when 'rego.v1' is imported in a module). // Shortly, RegoV1 compatibility is required, but 'rego.v1' or 'future.keywords' must also be imported. RegoV0CompatV1 // RegoV1 is the Rego syntax enforced by OPA 1.0; e.g.: // future.keywords part of default keyword set, and don't require imports; // 'if' and 'contains' required in rule heads; // (some) strict checks on by default. RegoV1 )
func RegoVersionFromInt ¶
func RegoVersionFromInt(i int) RegoVersion
func (RegoVersion) Int ¶
func (v RegoVersion) Int() int
func (RegoVersion) String ¶
func (v RegoVersion) String() string
type RelatedResourceAnnotation ¶
type RelatedResourceAnnotation struct { Ref url.URL `json:"ref"` Description string `json:"description,omitempty"` }
func (*RelatedResourceAnnotation) Compare ¶
func (rr *RelatedResourceAnnotation) Compare(other *RelatedResourceAnnotation) int
Compare returns an integer indicating if s is less than, equal to, or greater than other.
func (*RelatedResourceAnnotation) Copy ¶
func (rr *RelatedResourceAnnotation) Copy() *RelatedResourceAnnotation
Copy returns a deep copy of rr.
func (*RelatedResourceAnnotation) MarshalJSON ¶
func (rr *RelatedResourceAnnotation) MarshalJSON() ([]byte, error)
func (*RelatedResourceAnnotation) String ¶
func (rr *RelatedResourceAnnotation) String() string
type Resolver ¶
Resolver defines the interface for resolving references to native Go values.
type Rule ¶
type Rule struct { Default bool `json:"default,omitempty"` Head *Head `json:"head"` Body Body `json:"body"` Else *Rule `json:"else,omitempty"` Location *Location `json:"location,omitempty"` Annotations []*Annotations `json:"annotations,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:"-"` // contains filtered or unexported fields }
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 MustParseRuleWithOpts ¶
func MustParseRuleWithOpts(input string, opts ParserOptions) *Rule
MustParseRuleWithOpts returns a parsed rule. If an error occurs during parsing, panic.
func ParseCompleteDocRuleFromAssignmentExpr ¶
ParseCompleteDocRuleFromAssignmentExpr returns a rule if the expression can be interpreted as a complete document definition declared with the assignment operator.
func ParseCompleteDocRuleFromEqExpr ¶
ParseCompleteDocRuleFromEqExpr returns a rule if the expression can be interpreted as a complete document definition.
func ParseCompleteDocRuleWithDotsFromTerm ¶
func ParsePartialObjectDocRuleFromEqExpr ¶
ParsePartialObjectDocRuleFromEqExpr returns a rule if the expression can be interpreted as a partial object document definition.
func ParsePartialSetDocRuleFromTerm ¶
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 ¶
ParseRuleFromBody returns a rule if the body can be interpreted as a rule definition. Otherwise, an error is returned.
func ParseRuleFromCallEqExpr ¶
ParseRuleFromCallEqExpr returns a rule if the term can be interpreted as a function definition (e.g., f(x) = y => f(x) = y { true }).
func ParseRuleFromCallExpr ¶
ParseRuleFromCallExpr returns a rule if the terms can be interpreted as a function returning true or some value (e.g., f(x) => f(x) = true { true }).
func ParseRuleFromExpr ¶
ParseRuleFromExpr returns a rule if the expression can be interpreted as a rule definition.
func ParseRuleWithOpts ¶
func ParseRuleWithOpts(input string, opts ParserOptions) (*Rule, error)
ParseRuleWithOpts 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) Copy ¶
Copy returns a deep copy of rule.
func (*Rule) Equal ¶
Equal returns true if rule is equal to other.
func (*Rule) Loc ¶
Loc returns the location of the Rule in the definition.
func (*Rule) MarshalJSON ¶
func (*Rule) Path ¶
Path returns a ref referring to the document produced by this rule. If rule is not contained in a module, this function panics. Deprecated: Poor handling of ref rules. Use `(*Rule).Ref()` instead.
func (*Rule) Ref ¶
Ref returns a ref referring to the document produced by this rule. If rule is not contained in a module, this function panics. The returned ref may contain variables in the last position.
func (*Rule) SetLoc ¶
SetLoc sets the location on rule.
func (*Rule) String ¶
type RuleIndex ¶
type RuleIndex interface { // Build tries to construct an index for the given rules. If the index was // constructed, it returns true, otherwise false. Build(rules []*Rule) 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) (*IndexResult, error) // AllRules traverses the index and returns all rules that will match // the provided resolver without any optimizations (effectively with // indexing disabled). If the resolver returns an error, it is returned // via err. AllRules(resolver ValueResolver) (*IndexResult, error) }
RuleIndex defines the interface for rule indices.
type RuleKind ¶
type RuleKind byte
type RuleSet ¶
type RuleSet []*Rule
RuleSet represents a collection of rules that produce a virtual document.
func NewRuleSet ¶
NewRuleSet returns a new RuleSet containing the given rules.
func (*RuleSet) Add ¶
Add inserts the rule into rs.
func (RuleSet) Contains ¶
Contains returns true if rs contains rule.
func (RuleSet) Diff ¶
Diff returns a new RuleSet containing rules in rs that are not in other.
func (RuleSet) Equal ¶
Equal returns true if rs equals other.
func (RuleSet) Merge ¶
Merge returns a ruleset containing the union of rules from rs an other.
func (RuleSet) String ¶
type RulesOptions ¶
type RulesOptions struct { // IncludeHiddenModules determines if the result contains hidden modules, // currently only the "system" namespace, i.e. "data.system.*". IncludeHiddenModules bool }
RulesOptions defines the options for retrieving rules by Ref from the compiler.
type SchemaAnnotation ¶
type SchemaAnnotation struct { Path Ref `json:"path"` Schema Ref `json:"schema,omitempty"` Definition *any `json:"definition,omitempty"` }
SchemaAnnotation contains a schema declaration for the document identified by the path.
func (*SchemaAnnotation) Compare ¶
func (s *SchemaAnnotation) Compare(other *SchemaAnnotation) int
Compare returns an integer indicating if s is less than, equal to, or greater than other.
func (*SchemaAnnotation) Copy ¶
func (s *SchemaAnnotation) Copy() *SchemaAnnotation
Copy returns a deep copy of s.
func (*SchemaAnnotation) String ¶
func (s *SchemaAnnotation) String() string
type SchemaSet ¶
type SchemaSet struct {
// contains filtered or unexported fields
}
SchemaSet holds a map from a path to a schema.
func NewSchemaSet ¶
func NewSchemaSet() *SchemaSet
NewSchemaSet returns an empty SchemaSet.
func (*SchemaSet) Get ¶
Get returns the raw schema identified by the path.
func (*SchemaSet) Put ¶
Put inserts a raw schema into the set.
type Set ¶
type Set interface { Value Len() int Copy() Set Diff(Set) Set Intersect(Set) Set Union(Set) Set Add(*Term) Iter(func(*Term) error) error Until(func(*Term) bool) bool Foreach(func(*Term)) Contains(*Term) bool Map(func(*Term) (*Term, error)) (Set, error) Reduce(*Term, func(*Term, *Term) (*Term, error)) (*Term, error) Sorted() *Array Slice() []*Term }
Set represents a set as defined by the language.
func NewSet ¶
NewSet returns a new Set containing t.
type SetComprehension ¶
SetComprehension represents a set comprehension as defined in the language.
func (*SetComprehension) Compare ¶
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 ¶
func (sc *SetComprehension) Copy() *SetComprehension
Copy returns a deep copy of sc.
func (*SetComprehension) Equal ¶
func (sc *SetComprehension) Equal(other Value) bool
Equal returns true if sc is equal to other.
func (*SetComprehension) Find ¶
func (sc *SetComprehension) Find(path Ref) (Value, error)
Find returns the current value or a not found error.
func (*SetComprehension) Hash ¶
func (sc *SetComprehension) Hash() int
Hash returns the hash code of the Value.
func (*SetComprehension) IsGround ¶
func (sc *SetComprehension) IsGround() bool
IsGround returns true if the Term and Body are ground.
func (*SetComprehension) String ¶
func (sc *SetComprehension) String() string
type SomeDecl ¶
type SomeDecl struct { Symbols []*Term `json:"symbols"` Location *Location `json:"location,omitempty"` }
SomeDecl represents a variable declaration statement. The symbols are variables.
func (*SomeDecl) Compare ¶
Compare returns an integer indicating whether d is less than, equal to, or greater than other.
func (*SomeDecl) Copy ¶
Copy returns a deep copy of d.
func (*SomeDecl) Hash ¶
Hash returns a hash code of d.
func (*SomeDecl) Loc ¶
Loc returns the Location of d.
func (*SomeDecl) MarshalJSON ¶
func (*SomeDecl) SetLoc ¶
SetLoc sets the Location on d.
func (*SomeDecl) String ¶
type Statement ¶
type Statement interface { Node }
Statement represents a single statement in a policy module.
func MustParseStatement ¶
MustParseStatement returns exactly one statement. If an error occurs during parsing, panic.
func MustParseStatementWithOpts ¶
func MustParseStatementWithOpts(input string, popts ParserOptions) Statement
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.
func ParseStatementWithOpts ¶
func ParseStatementWithOpts(input string, popts ParserOptions) (Statement, error)
type String ¶
type String string
String represents a string value as defined by JSON.
func (String) Compare ¶
Compare compares str to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.
func (String) Equal ¶
Equal returns true if the other Value is a String and is equal.
func (String) Find ¶
Find returns the current value or a not found error.
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 `json:"value"` // the value of the Term as represented in Go Location *Location `json:"location,omitempty"` // 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 CallTerm ¶
CallTerm returns a new Term with a Call value defined by terms. The first term is the operator and the rest are operands.
func FloatNumberTerm ¶
FloatNumberTerm creates a new Term with a floating point Number value.
func IntNumberTerm ¶
IntNumberTerm creates a new Term with an integer Number value.
func InternedBooleanTerm ¶
InternedBooleanTerm returns an interned term with the given boolean value.
func InternedIntNumberTerm ¶
InternedIntNumberTerm returns a term with the given integer value. The term is cached between -1 to 512, and for values outside of that range, this function is equivalent to ast.IntNumberTerm.
func InternedIntNumberTermFromString ¶
InternedIntFromString returns a term with the given integer value if the string maps to an interned term. If the string does not map to an interned term, nil is returned.
func InternedIntegerString ¶
Returns an interned string term representing the integer value i, if interned. If not, creates a new StringTerm for the integer value.
func InternedStringTerm ¶
InternedStringTerm returns an interned term with the given string value. If the provided string is not interned, a new term is created for that value. It does *not* modify the global interned terms map.
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 NewTerm ¶
NewTerm returns a new Term object.
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 ObjectComprehensionTerm ¶
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 RefTerm ¶
RefTerm creates a new Term with a Ref value.
func SetComprehensionTerm ¶
SetComprehensionTerm creates a new Term with an SetComprehension 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 UIntNumberTerm ¶
UIntNumberTerm creates a new Term with an unsigned integer Number value.
func VarTerm ¶
VarTerm creates a new Term with a Variable value.
func (*Term) Copy ¶
Copy returns a deep copy of term.
func (*Term) Equal ¶
Equal returns true if this term equals the other term. Equality is defined for each kind of term, and does not compare the Location.
func (*Term) Get ¶
Get returns a value referred to by name from the term.
func (*Term) Hash ¶
Hash returns the hash code of the Term's Value. Its Location is ignored.
func (*Term) IsGround ¶
IsGround returns true if this term's Value is ground.
func (*Term) Loc ¶
Loc returns the Location 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) SetLoc ¶
SetLoc sets the location on term.
func (*Term) SetLocation ¶
SetLocation updates the term's Location and returns the term itself.
func (*Term) String ¶
func (*Term) UnmarshalJSON ¶
UnmarshalJSON parses the byte array and stores the result in term. Specialized unmarshalling is required to handle Value and Location.
func (*Term) Vars ¶
Vars returns a VarSet with variables contained in this term.
type Transformer ¶
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 ¶
type TreeNode struct { Key Value Values []any Children map[Value]*TreeNode Sorted []Value Hide bool }
TreeNode represents a node in the rule tree. The rule tree is keyed by rule path.
func NewRuleTree ¶
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) Child ¶
Child returns n's child with key k.
func (*TreeNode) DepthFirst ¶
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.
func (*TreeNode) Find ¶
Find dereferences ref along the tree
func (*TreeNode) Size ¶
Size returns the number of rules in the tree.
func (*TreeNode) String ¶
type TypeEnv ¶
type TypeEnv struct {
// contains filtered or unexported fields
}
TypeEnv contains type info for static analysis such as type checking.
func (*TypeEnv) Get ¶
Get returns the type of x. Deprecated: Use GetByValue or GetByRef instead, as they are more efficient.
func (*TypeEnv) GetByRef ¶
GetByRef returns the type of the value referred to by ref.
func (*TypeEnv) GetByValue ¶
GetByValue returns the type of v.
type UnificationErrDetail ¶
UnificationErrDetail describes a type mismatch error when two values are unified (e.g., x = [1,2,y]).
func (*UnificationErrDetail) Lines ¶
func (a *UnificationErrDetail) Lines() []string
Lines returns the string representation of the detail.
type UnknownValueErr ¶
type UnknownValueErr struct{}
UnknownValueErr indicates a ValueResolver was unable to resolve a reference because the reference refers to an unknown value.
func (UnknownValueErr) Error ¶
func (UnknownValueErr) Error() string
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, Set, and Object Comprehensions - Calls
func InterfaceToValue ¶
InterfaceToValue converts a native Go value x to a Value.
func MustInterfaceToValue ¶
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.
func ValueFromReader ¶
ValueFromReader returns an AST value from a JSON serialized value in the reader.
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) 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) MarshalJSON ¶
MarshalJSON provides a custom marshaller for the ValueMap which will include the key, value, and value type.
func (*ValueMap) Put ¶
Put inserts a key k into the map with value v.
func (*ValueMap) String ¶
type ValueResolver ¶
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 ¶
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) Find ¶
Find returns the current value or a not found error.
func (Var) Hash ¶
Hash returns the hash code for the Value.
func (Var) IsGenerated ¶
IsGenerated returns true if this variable was generated during compilation.
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 NewVarSetOfSize ¶
NewVarSet returns a new VarSet containing the specified variables.
func OutputVarsFromBody ¶
OutputVarsFromBody returns all variables which are the "output" for the given body. For safety checks this means that they would be made safe by the body.
func OutputVarsFromExpr ¶
OutputVarsFromExpr returns all variables which are the "output" for the given expression. For safety checks this means that they would be made safe by the expr.
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) Equal ¶
Equal returns true if s contains exactly the same elements as vs.
func (VarSet) Intersect ¶
Intersect returns a VarSet containing variables in s that are in vs.
func (VarSet) Sorted ¶
Sorted returns a new sorted slice of vars from s.
func (VarSet) String ¶
func (VarSet) Update ¶
Update merges the other VarSet into this VarSet.
type VarVisitor ¶
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 ¶
func NewVarVisitor() *VarVisitor
NewVarVisitor returns a new VarVisitor object.
func (*VarVisitor) Vars ¶
func (vis *VarVisitor) Vars() VarSet
Vars returns a VarSet that contains collected vars.
func (*VarVisitor) Walk ¶
func (vis *VarVisitor) Walk(x any)
Walk iterates the AST by calling the function f on the GenericVisitor before recursing. Contrary to the generic Walk, this does not require allocating the visitor from heap.
func (*VarVisitor) WithParams ¶
func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor
WithParams sets the parameters in params on vis.
type VarVisitorParams ¶
type VarVisitorParams struct { SkipRefHead bool SkipRefCallHead bool SkipObjectKeys bool SkipClosures bool SkipWithTarget bool SkipSets bool }
VarVisitorParams contains settings for a VarVisitor.
type VersionIndex ¶
type VersionIndex struct { Builtins map[string]semver.Version `json:"builtins"` Features map[string]semver.Version `json:"features"` Keywords map[string]semver.Version `json:"keywords"` }
VersonIndex contains an index from built-in function name, language feature, and future rego keyword to version number. During the build, this is used to create an index of the minimum version required for the built-in/feature/kw.
type 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. Deprecated: use GenericVisitor or another visitor implementation
type WasmABIVersion ¶
WasmABIVersion captures the Wasm ABI version. Its `Minor` version is indicating backwards-compatible changes.
type With ¶
type With struct { Target *Term `json:"target"` Value *Term `json:"value"` Location *Location `json:"location,omitempty"` }
With represents a modifier on an expression.
func (*With) Compare ¶
Compare returns an integer indicating whether w is less than, equal to, or greater than other.
func (*With) Copy ¶
Copy returns a deep copy of w.
func (*With) Equal ¶
Equal returns true if this With is equals the other With.
func (With) Hash ¶
Hash returns the hash code of the With.
func (*With) Loc ¶
Loc returns the Location of w.
func (*With) MarshalJSON ¶
func (*With) SetLoc ¶
SetLoc sets the location on w.
func (*With) SetLocation ¶
SetLocation sets the location on w.
func (*With) String ¶
Source Files ¶
annotations.go builtins.go capabilities.go check.go compare.go compile.go compilehelper.go compilemetrics.go conflicts.go doc.go env.go errors.go index.go interning.go map.go parser.go parser_ext.go policy.go pretty.go rego_v1.go schema.go strings.go syncpools.go term.go transform.go unify.go varset.go visit.go
Directories ¶
Path | Synopsis |
---|---|
v1/ast/internal | |
v1/ast/json | This package provides options for JSON marshalling of AST nodes, and location data in particular. |
v1/ast/location | Package location defines locations in Rego source code. |
v1/ast/oracle |
- Version
- v1.5.1 (latest)
- Published
- Jun 4, 2025
- Platform
- js/wasm
- Imports
- 35 packages
- Last checked
- 6 hours ago –
Tools for package owners.