package ast

import "github.com/open-policy-agent/opa/ast"

Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the github.com/open-policy-agent/opa/v1 package instead. See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information.

Index

Constants

const (
	// EvalModeTopdown (default) instructs the compiler to build rule
	// and comprehension indices used by topdown evaluation.
	EvalModeTopdown = v1.EvalModeTopdown

	// EvalModeIR makes the compiler skip the stages for comprehension
	// and rule indices.
	EvalModeIR = v1.EvalModeIR
)
const (
	// ParseErr indicates an unclassified parse error occurred.
	ParseErr = v1.ParseErr

	// CompileErr indicates an unclassified compile error occurred.
	CompileErr = v1.CompileErr

	// TypeErr indicates a type error was caught.
	TypeErr = v1.TypeErr

	// UnsafeVarErr indicates an unsafe variable was found during compilation.
	UnsafeVarErr = v1.UnsafeVarErr

	// RecursionErr indicates recursion was found during compilation.
	RecursionErr = v1.RecursionErr
)
const (
	RegoUndefined = v1.RegoUndefined
	// RegoV0 is the default, original Rego syntax.
	RegoV0 = v1.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 = v1.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 = v1.RegoV1
)
const (
	// CompleteDoc represents a document that is completely defined by the rule.
	CompleteDoc = v1.CompleteDoc

	// PartialSetDoc represents a set document that is partially defined by the rule.
	PartialSetDoc = v1.PartialSetDoc

	// PartialObjectDoc represents an object document that is partially defined by the rule.
	PartialObjectDoc = v1.PartialObjectDoc
)
const (
	SingleValue = v1.SingleValue
	MultiValue  = v1.MultiValue
)
const CompileErrorLimitDefault = 10

CompileErrorLimitDefault is the default number errors a compiler will allow before exiting.

const DefaultRegoVersion = RegoV0
const FeatureRefHeadStringPrefixes = v1.FeatureRefHeadStringPrefixes

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 = v1.FeatureRefHeads
const FeatureRegoV1 = v1.FeatureRegoV1
const FeatureRegoV1Import = v1.FeatureRegoV1Import
const SystemDocumentKey = v1.SystemDocumentKey

SystemDocumentKey is the name of the top-level key that identifies the system document.

const WildcardPrefix = v1.WildcardPrefix

WildcardPrefix is the special character that all wildcard variables are prefixed with when the statement they are contained in is parsed.

Variables

var Abs = v1.Abs
var AddDate = v1.AddDate
var All = v1.All

All takes a list and returns true if all of the items are true. A collection of length 0 returns true.

var And = v1.And
var Any = v1.Any

Any takes a collection and returns true if any of the items is true. A collection of length 0 returns false.

var AnyPrefixMatch = v1.AnyPrefixMatch
var AnySuffixMatch = v1.AnySuffixMatch
var ArrayConcat = v1.ArrayConcat
var ArrayReverse = v1.ArrayReverse
var ArraySlice = v1.ArraySlice
var Assign = v1.Assign

Assign represents the assignment (":=") operator.

var Base64Decode = v1.Base64Decode
var Base64Encode = v1.Base64Encode
var Base64IsValid = v1.Base64IsValid
var Base64UrlDecode = v1.Base64UrlDecode
var Base64UrlEncode = v1.Base64UrlEncode
var Base64UrlEncodeNoPad = v1.Base64UrlEncodeNoPad
var BitsAnd = v1.BitsAnd
var BitsNegate = v1.BitsNegate
var BitsOr = v1.BitsOr
var BitsShiftLeft = v1.BitsShiftLeft
var BitsShiftRight = v1.BitsShiftRight
var BitsXOr = v1.BitsXOr
var BuiltinMap = v1.BuiltinMap

BuiltinMap provides a convenient mapping of built-in names to built-in definitions.

var Builtins = v1.Builtins

Builtins is the registry of built-in functions supported by OPA. Call RegisterBuiltin to add a new built-in.

var CastArray = v1.CastArray

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 = v1.CastBoolean

CastBoolean returns input if it is a boolean; if not returns error.

var CastNull = v1.CastNull

CastNull returns null if input is null; if not returns error.

var CastObject = v1.CastObject

CastObject returns the given object if it is null; throws an error otherwise

var CastSet = v1.CastSet

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 = v1.CastString

CastString returns input if it is a string; if not returns error. For formatting variables, see sprintf

var Ceil = v1.Ceil
var Clock = v1.Clock
var Concat = v1.Concat
var Contains = v1.Contains
var Count = v1.Count
var CryptoHmacEqual = v1.CryptoHmacEqual
var CryptoHmacMd5 = v1.CryptoHmacMd5
var CryptoHmacSha1 = v1.CryptoHmacSha1
var CryptoHmacSha256 = v1.CryptoHmacSha256
var CryptoHmacSha512 = v1.CryptoHmacSha512
var CryptoMd5 = v1.CryptoMd5
var CryptoParsePrivateKeys = v1.CryptoParsePrivateKeys
var CryptoSha1 = v1.CryptoSha1
var CryptoSha256 = v1.CryptoSha256
var CryptoX509ParseAndVerifyCertificates = v1.CryptoX509ParseAndVerifyCertificates
var CryptoX509ParseAndVerifyCertificatesWithOptions = v1.CryptoX509ParseAndVerifyCertificatesWithOptions
var CryptoX509ParseCertificateRequest = v1.CryptoX509ParseCertificateRequest
var CryptoX509ParseCertificates = v1.CryptoX509ParseCertificates
var CryptoX509ParseKeyPair = v1.CryptoX509ParseKeyPair
var CryptoX509ParseRSAPrivateKey = v1.CryptoX509ParseRSAPrivateKey
var Date = v1.Date
var DefaultBuiltins = v1.DefaultBuiltins

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 = v1.DefaultRootDocument

DefaultRootDocument is the default root document.

All package directives inside source files are implicitly prefixed with the DefaultRootDocument value.

var DefaultRootRef = v1.DefaultRootRef

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 = v1.Diff
var Divide = v1.Divide
var EndsWith = v1.EndsWith
var Equal = v1.Equal

Equal represents the "==" comparison operator.

var Equality = v1.Equality

Equality represents the "=" operator.

var Floor = v1.Floor
var Format = v1.Format
var FormatInt = v1.FormatInt
var FunctionArgRootDocument = v1.FunctionArgRootDocument

FunctionArgRootDocument names the document containing function arguments. It's only for internal usage, for referencing function arguments between the index and topdown.

var FutureRootDocument = v1.FutureRootDocument

FutureRootDocument names the document containing new, to-become-default, features.

var GlobMatch = v1.GlobMatch
var GlobQuoteMeta = v1.GlobQuoteMeta
var GlobsMatch = v1.GlobsMatch

GlobsMatch takes two strings regexp-style strings and evaluates to true if their intersection matches a non-empty set of non-empty strings. Examples:

var GraphQLIsValid = v1.GraphQLIsValid

GraphQLIsValid returns true if a GraphQL query is valid with a given schema, and returns false for all other inputs.

var GraphQLParse = v1.GraphQLParse

GraphQLParse returns a pair of AST objects from parsing/validation.

var GraphQLParseAndVerify = v1.GraphQLParseAndVerify

GraphQLParseAndVerify returns a boolean and a pair of AST object from parsing/validation.

var GraphQLParseQuery = v1.GraphQLParseQuery

GraphQLParseQuery parses the input GraphQL query and returns a JSON representation of its AST.

var GraphQLParseSchema = v1.GraphQLParseSchema

GraphQLParseSchema parses the input GraphQL schema and returns a JSON representation of its AST.

var GraphQLSchemaIsValid = v1.GraphQLSchemaIsValid

GraphQLSchemaIsValid returns true if the input is valid GraphQL schema, and returns false for all other inputs.

var GreaterThan = v1.GreaterThan
var GreaterThanEq = v1.GreaterThanEq
var HTTPSend = v1.HTTPSend

Marked non-deterministic because HTTP request results can be non-deterministic.

var HexDecode = v1.HexDecode
var HexEncode = v1.HexEncode
var IgnoreDuringPartialEval = v1.IgnoreDuringPartialEval

Deprecated: Builtins can now be directly annotated with the Nondeterministic property, and when set to true, will be ignored for partial evaluation.

var IndexOf = v1.IndexOf
var IndexOfN = v1.IndexOfN
var InputRootDocument = v1.InputRootDocument

InputRootDocument names the document containing query arguments.

var InputRootRef = v1.InputRootRef

InputRootRef is a reference to the root of the input document.

All refs to query arguments are prefixed with this ref.

var InternalPrint = v1.InternalPrint

InternalPrint represents the internal implementation of the print() function. The compiler rewrites print() calls to refer to the internal implementation.

var Intersection = v1.Intersection
var IsArray = v1.IsArray
var IsBoolean = v1.IsBoolean
var IsNull = v1.IsNull
var IsNumber = v1.IsNumber
var IsObject = v1.IsObject
var IsSet = v1.IsSet
var IsString = v1.IsString
var JSONFilter = v1.JSONFilter
var JSONIsValid = v1.JSONIsValid
var JSONMarshal = v1.JSONMarshal
var JSONMarshalWithOptions = v1.JSONMarshalWithOptions
var JSONMatchSchema = v1.JSONMatchSchema

JSONMatchSchema returns empty array if the document matches the JSON schema, and returns non-empty array with error objects otherwise.

var JSONPatch = v1.JSONPatch
var JSONRemove = v1.JSONRemove
var JSONSchemaVerify = v1.JSONSchemaVerify

JSONSchemaVerify returns empty string if the input is valid JSON schema and returns error string for all other inputs.

var JSONUnmarshal = v1.JSONUnmarshal
var JWTDecode = v1.JWTDecode
var JWTDecodeVerify = v1.JWTDecodeVerify

Marked non-deterministic because it relies on time internally.

var JWTEncodeSign = v1.JWTEncodeSign

Marked non-deterministic because it relies on RNG internally.

var JWTEncodeSignRaw = v1.JWTEncodeSignRaw

Marked non-deterministic because it relies on RNG internally.

var JWTVerifyES256 = v1.JWTVerifyES256
var JWTVerifyES384 = v1.JWTVerifyES384
var JWTVerifyES512 = v1.JWTVerifyES512
var JWTVerifyHS256 = v1.JWTVerifyHS256
var JWTVerifyHS384 = v1.JWTVerifyHS384
var JWTVerifyHS512 = v1.JWTVerifyHS512
var JWTVerifyPS256 = v1.JWTVerifyPS256
var JWTVerifyPS384 = v1.JWTVerifyPS384
var JWTVerifyPS512 = v1.JWTVerifyPS512
var JWTVerifyRS256 = v1.JWTVerifyRS256
var JWTVerifyRS384 = v1.JWTVerifyRS384
var JWTVerifyRS512 = v1.JWTVerifyRS512
var Keywords = v1.Keywords

Keywords contains strings that map to language keywords.

var KeywordsV0 = v1.KeywordsV0
var KeywordsV1 = v1.KeywordsV1
var LessThan = v1.LessThan

LessThan represents the "<" comparison operator.

var LessThanEq = v1.LessThanEq
var Lower = v1.Lower
var Max = v1.Max
var Member = v1.Member

Member represents the `in` (infix) operator.

var MemberWithKey = v1.MemberWithKey

MemberWithKey represents the `in` (infix) operator when used with two terms on the lhs, i.e., `k, v in obj`.

var Min = v1.Min
var Minus = v1.Minus
var Multiply = v1.Multiply
var NetCIDRContains = v1.NetCIDRContains
var NetCIDRContainsMatches = v1.NetCIDRContainsMatches
var NetCIDRExpand = v1.NetCIDRExpand
var NetCIDRIntersects = v1.NetCIDRIntersects
var NetCIDRIsValid = v1.NetCIDRIsValid
var NetCIDRMerge = v1.NetCIDRMerge
var NetCIDROverlap = v1.NetCIDROverlap

NetCIDROverlap has been replaced by the `net.cidr_contains` built-in.

var NetLookupIPAddr = v1.NetLookupIPAddr

Marked non-deterministic because DNS resolution results can be non-deterministic.

var NotEqual = v1.NotEqual
var NowNanos = v1.NowNanos

Marked non-deterministic because it relies on time directly.

var NumbersRange = v1.NumbersRange
var NumbersRangeStep = v1.NumbersRangeStep
var OPARuntime = v1.OPARuntime

Marked non-deterministic because of unpredictable config/environment-dependent results.

var ObjectFilter = v1.ObjectFilter
var ObjectGet = v1.ObjectGet
var ObjectKeys = v1.ObjectKeys
var ObjectRemove = v1.ObjectRemove
var ObjectSubset = v1.ObjectSubset
var ObjectUnion = v1.ObjectUnion
var ObjectUnionN = v1.ObjectUnionN
var Or = v1.Or

Or performs a union operation on sets.

var ParseDurationNanos = v1.ParseDurationNanos
var ParseNanos = v1.ParseNanos
var ParseRFC3339Nanos = v1.ParseRFC3339Nanos
var Plus = v1.Plus
var Print = v1.Print

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 = v1.Product
var ProvidersAWSSignReqObj = v1.ProvidersAWSSignReqObj
var RandIntn = v1.RandIntn

RandIntn returns a random number 0 - n Marked non-deterministic because it relies on RNG internally.

var ReachableBuiltin = v1.ReachableBuiltin
var ReachablePathsBuiltin = v1.ReachablePathsBuiltin
var RegexFind = v1.RegexFind

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 = v1.RegexFindAllStringSubmatch
var RegexIsValid = v1.RegexIsValid
var RegexMatch = v1.RegexMatch
var RegexMatchDeprecated = v1.RegexMatchDeprecated

RegexMatchDeprecated declares `re_match` which has been deprecated. Use `regex.match` instead.

var RegexReplace = v1.RegexReplace
var RegexSplit = v1.RegexSplit
var RegexTemplateMatch = v1.RegexTemplateMatch
var RegoMetadataChain = v1.RegoMetadataChain
var RegoMetadataRule = v1.RegoMetadataRule

RegoMetadataRule returns the metadata for the active rule

var RegoParseModule = v1.RegoParseModule
var RegoRootDocument = v1.RegoRootDocument

RegoRootDocument names the document containing new, to-become-default, features in a future versioned release.

var RegoV1CompatibleRef = v1.RegoV1CompatibleRef
var Rem = v1.Rem
var RenderTemplate = v1.RenderTemplate
var Replace = v1.Replace
var ReplaceN = v1.ReplaceN
var ReservedVars = v1.ReservedVars

ReservedVars is the set of names that refer to implicitly ground vars.

var RootDocumentNames = v1.RootDocumentNames

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 = v1.RootDocumentRefs

RootDocumentRefs contains the prefixes of top-level documents that all non-local references start with.

var Round = v1.Round
var SafetyCheckVisitorParams = v1.SafetyCheckVisitorParams

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 = v1.SchemaRootDocument

SchemaRootDocument names the document containing external data schemas.

var SchemaRootRef = v1.SchemaRootRef

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 = v1.SemVerCompare
var SemVerIsValid = v1.SemVerIsValid
var SetDiff = v1.SetDiff

SetDiff has been replaced by the minus built-in.

var Sort = v1.Sort
var Split = v1.Split
var Sprintf = v1.Sprintf
var StartsWith = v1.StartsWith
var StringCount = v1.StringCount
var StringReverse = v1.StringReverse
var Substring = v1.Substring
var Sum = v1.Sum
var ToNumber = v1.ToNumber
var Trace = v1.Trace
var Trim = v1.Trim
var TrimLeft = v1.TrimLeft
var TrimPrefix = v1.TrimPrefix
var TrimRight = v1.TrimRight
var TrimSpace = v1.TrimSpace
var TrimSuffix = v1.TrimSuffix
var TypeNameBuiltin = v1.TypeNameBuiltin

TypeNameBuiltin returns the type of the input.

var URLQueryDecode = v1.URLQueryDecode
var URLQueryDecodeObject = v1.URLQueryDecodeObject
var URLQueryEncode = v1.URLQueryEncode
var URLQueryEncodeObject = v1.URLQueryEncodeObject
var UUIDParse = v1.UUIDParse
var UUIDRFC4122 = v1.UUIDRFC4122

UUIDRFC4122 returns a version 4 UUID string. Marked non-deterministic because it relies on RNG internally.

var Union = v1.Union
var UnitsParse = v1.UnitsParse
var UnitsParseBytes = v1.UnitsParseBytes
var Upper = v1.Upper
var WalkBuiltin = v1.WalkBuiltin
var Weekday = v1.Weekday
var Wildcard = v1.Wildcard

Wildcard represents the wildcard variable as defined in the language.

var YAMLIsValid = v1.YAMLIsValid

YAMLIsValid verifies the input string is a valid YAML document.

var YAMLMarshal = v1.YAMLMarshal
var YAMLUnmarshal = v1.YAMLUnmarshal

Functions

func As

func As(v Value, x interface{}) error

As converts v into a Go native type referred to by x.

func BuildAnnotationSet

func BuildAnnotationSet(modules []*Module) (*AnnotationSet, Errors)

func Compare

func Compare(a, b interface{}) int

Compare returns an integer indicating whether two AST values are less than, equal to, or greater than each other.

If a is less than b, the return value is negative. If a is greater than b, the return value is positive. If a is equal to b, the return value is zero.

Different types are never equal to each other. For comparison purposes, types are sorted as follows:

nil < Null < Boolean < Number < String < Var < Ref < Array < Object < Set < ArrayComprehension < 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

func ContainsClosures(v interface{}) bool

ContainsClosures returns true if the Value v contains closures.

func ContainsComprehensions

func ContainsComprehensions(v interface{}) bool

ContainsComprehensions returns true if the Value v contains comprehensions.

func ContainsRefs

func ContainsRefs(v interface{}) bool

ContainsRefs returns true if the Value v contains refs.

func Copy

func Copy(x interface{}) interface{}

Copy returns a deep copy of the AST node x. If x is not an AST node, x is returned unmodified.

func HasInternedIntNumberTerm

func HasInternedIntNumberTerm(i int) bool

func IsComprehension

func IsComprehension(x Value) bool

IsComprehension returns true if the supplied value is a comprehension.

func IsConstant

func IsConstant(v Value) bool

IsConstant returns true if the AST value is constant.

func IsError

func IsError(code string, err error) bool

IsError returns true if err is an AST error with code.

func IsFutureKeyword

func IsFutureKeyword(s string) bool

func IsInKeywords

func IsInKeywords(s string, keywords []string) bool

func IsKeyword

func IsKeyword(s string) bool

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

func IsScalar(v Value) bool

IsScalar returns true if the AST value is a scalar.

func IsUnknownValueErr

func IsUnknownValueErr(err error) bool

IsUnknownValueErr returns true if the err is an UnknownValueErr.

func IsValidImportPath

func IsValidImportPath(v Value) (err error)

IsValidImportPath returns an error indicating if the import path is invalid. If the import path is valid, err is nil.

func IsVarCompatibleString

func IsVarCompatibleString(s string) bool

func JSON

func JSON(v Value) (interface{}, error)

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

func JSONWithOpt(v Value, opt JSONOpt) (interface{}, error)

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

func LoadCapabilitiesVersions() ([]string, error)

LoadCapabilitiesVersions loads all capabilities versions

func MustJSON

func MustJSON(v Value) interface{}

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

func ParseStatements(filename, input string) ([]Statement, []*Comment, error)

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

func Pretty(w io.Writer, x interface{})

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 RegisterBuiltin

func RegisterBuiltin(b *Builtin)

RegisterBuiltin adds a new built-in function to the registry.

func Transform

func Transform(t Transformer, x interface{}) (interface{}, error)

Transform iterates the AST and calls the Transform function on the Transformer t for x before recursing.

func TransformComprehensions

func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error)

TransformComprehensions calls the functio nf on all comprehensions under x.

func TransformRefs

func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error)

TransformRefs calls the function f on all references under x.

func TransformVars

func TransformVars(x interface{}, f func(Var) (Value, error)) (interface{}, error)

TransformVars calls the function f on all vars under x.

func TypeName

func TypeName(x interface{}) string

TypeName returns a human readable name for the AST element type.

func ValueToInterface

func ValueToInterface(v Value, resolver Resolver) (interface{}, error)

ValueToInterface returns the Go representation of an AST value. The AST value should not contain any values that require evaluation (e.g., vars, comprehensions, etc.)

func Walk

func Walk(v Visitor, x interface{})

Walk iterates the AST by calling the Visit function on the Visitor v for x before recursing. Deprecated: use GenericVisitor.Walk

func WalkBeforeAndAfter

func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{})

WalkBeforeAndAfter iterates the AST by calling the Visit function on the Visitor v for x before recursing. Deprecated: use GenericVisitor.Walk

func WalkBodies

func WalkBodies(x interface{}, f func(Body) bool)

WalkBodies calls the function f on all bodies under x. If the function f returns true, AST nodes under the last node will not be visited.

func WalkClosures

func WalkClosures(x interface{}, f func(interface{}) bool)

WalkClosures calls the function f on all closures under x. If the function f returns true, AST nodes under the last node will not be visited.

func WalkExprs

func WalkExprs(x interface{}, f func(*Expr) bool)

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

func WalkNodes(x interface{}, f func(Node) bool)

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

func WalkRefs(x interface{}, f func(Ref) bool)

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

func WalkRules(x interface{}, f func(*Rule) bool)

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

func WalkTerms(x interface{}, f func(*Term) bool)

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

func WalkVars(x interface{}, f func(Var) bool)

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

func WalkWiths(x interface{}, f func(*With) bool)

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 = v1.AnnotationSet

type Annotations

type Annotations = v1.Annotations

Annotations represents metadata attached to other AST nodes such as rules.

type AnnotationsRef

type AnnotationsRef = v1.AnnotationsRef

func NewAnnotationsRef

func NewAnnotationsRef(a *Annotations) *AnnotationsRef

type AnnotationsRefSet

type AnnotationsRefSet = v1.AnnotationsRefSet

type Args

type Args = v1.Args

Args represents zero or more arguments to a rule.

type Array

type Array = v1.Array

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

func NewArray(a ...*Term) *Array

NewArray creates an Array with the terms provided. The array will use the provided term slice.

type ArrayComprehension

type ArrayComprehension = v1.ArrayComprehension

ArrayComprehension represents an array comprehension as defined in the language.

type AuthorAnnotation

type AuthorAnnotation = v1.AuthorAnnotation

type BeforeAfterVisitor

type BeforeAfterVisitor = v1.BeforeAfterVisitor

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 interface{}) bool, after func(x interface{})) *BeforeAfterVisitor

NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that will invoke the functions before and after AST nodes.

type BeforeAndAfterVisitor

type BeforeAndAfterVisitor = v1.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 = v1.Body

Body represents one or more expressions contained inside a rule or user function.

func MustParseBody

func MustParseBody(input string) Body

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

func NewBody(exprs ...*Expr) Body

NewBody returns a new Body containing the given expressions. The indices of the immediate expressions will be reset.

func ParseBody

func ParseBody(input string) (Body, error)

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.

type Boolean

type Boolean = v1.Boolean

Boolean represents a boolean value defined by JSON.

type Builtin

type Builtin = v1.Builtin

Builtin represents a built-in function supported by OPA. Every built-in function is uniquely identified by a name.

type Call

type Call = v1.Call

Call represents as function call in the language.

type Capabilities

type Capabilities = v1.Capabilities

Capabilities defines a structure containing data that describes the capabilities or features supported by a particular version of OPA.

func CapabilitiesForThisVersion

func CapabilitiesForThisVersion() *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.

type Comment

type Comment = v1.Comment

Comment contains the raw text from the comment in the definition.

func NewComment

func NewComment(text []byte) *Comment

NewComment returns a new Comment object.

type CompileOpts

type CompileOpts = v1.CompileOpts

CompileOpts defines a set of options for the compiler.

type Compiler

type Compiler = v1.Compiler

Compiler contains the state of a compilation process.

func CompileModules

func CompileModules(modules map[string]string) (*Compiler, error)

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

func MustCompileModules(modules map[string]string) *Compiler

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.

type CompilerEvalMode

type CompilerEvalMode = v1.CompilerEvalMode

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.

type CompilerStage

type CompilerStage = v1.CompilerStage

CompilerStage defines the interface for stages in the compiler.

type CompilerStageDefinition

type CompilerStageDefinition = v1.CompilerStageDefinition

CompilerStageDefinition defines a compiler stage

type ComprehensionIndex

type ComprehensionIndex = v1.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.)

type DocKind

type DocKind = v1.DocKind

DocKind represents the collection of document types that can be produced by rules.

type Error

type Error = v1.Error

Error represents a single error caught during parsing, compiling, etc.

func NewError

func NewError(code string, loc *Location, f string, a ...interface{}) *Error

NewError returns a new Error object.

type ErrorDetails

type ErrorDetails = v1.ErrorDetails

ErrorDetails defines the interface for detailed error messages.

type Errors

type Errors = v1.Errors

Errors represents a series of errors encountered during parsing, compiling, etc.

func CheckPathConflicts

func CheckPathConflicts(c *Compiler, exists func([]string) (bool, error)) Errors

CheckPathConflicts returns a set of errors indicating paths that are in conflict with the result of the provided callable.

type Every

type Every = v1.Every

type Expr

type Expr = v1.Expr

Expr represents a single expression contained inside the body of a rule.

func MustParseExpr

func MustParseExpr(input string) *Expr

MustParseExpr returns a parsed expression. If an error occurs during parsing, panic.

func NewBuiltinExpr

func NewBuiltinExpr(terms ...*Term) *Expr

NewBuiltinExpr creates a new Expr object with the supplied terms. The builtin operator must be the first term.

func NewExpr

func NewExpr(terms interface{}) *Expr

NewExpr returns a new Expr object.

func ParseExpr

func ParseExpr(input string) (*Expr, error)

ParseExpr returns exactly one expression. If multiple expressions are parsed, an error is returned.

type FlatAnnotationsRefSet

type FlatAnnotationsRefSet = v1.FlatAnnotationsRefSet

type GenericTransformer

type GenericTransformer = v1.GenericTransformer

GenericTransformer implements the Transformer interface to provide a utility to transform AST nodes using a closure.

func NewGenericTransformer

func NewGenericTransformer(f func(x interface{}) (interface{}, error)) *GenericTransformer

NewGenericTransformer returns a new GenericTransformer that will transform AST nodes using the function f.

type GenericVisitor

type GenericVisitor = v1.GenericVisitor

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 interface{}) bool) *GenericVisitor

NewGenericVisitor returns a new GenericVisitor that will invoke the function f on AST nodes.

type Graph

type Graph = v1.Graph

Graph represents the graph of dependencies between rules.

func NewGraph

func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph

NewGraph returns a new Graph based on modules. The list function must return the rules referred to directly by the ref.

type GraphTraversal

type GraphTraversal = v1.GraphTraversal

GraphTraversal is a Traversal that understands the dependency graph

func NewGraphTraversal

func NewGraphTraversal(graph *Graph) *GraphTraversal

NewGraphTraversal returns a Traversal for the dependency graph

type Head = v1.Head

Head represents the head of a rule.

func NewHead

func NewHead(name Var, args ...*Term) *Head

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

func RefHead(ref Ref, args ...*Term) *Head

RefHead returns a new Head object with the passed Ref. If args are provided, the first will be used for the value.

func VarHead

func VarHead(name Var, location *Location, jsonOpts *astJSON.Options) *Head

VarHead creates a head object, initializes its Name, Location, and Options, and returns the new head.

type Import

type Import = v1.Import

Import represents a dependency on a document outside of the policy namespace. Imports are optional.

func MustParseImports

func MustParseImports(input string) []*Import

MustParseImports returns a slice of imports. If an error occurs during parsing, panic.

func ParseImports

func ParseImports(input string) ([]*Import, error)

ParseImports returns a slice of Import objects.

type IndexResult

type IndexResult = v1.IndexResult

IndexResult contains the result of an index lookup.

func NewIndexResult

func NewIndexResult(kind RuleKind) *IndexResult

NewIndexResult returns a new IndexResult object.

type JSONOpt

type JSONOpt = v1.JSONOpt

JSONOpt defines parameters for AST to JSON conversion.

type Location

type Location = v1.Location

Location records a position in source code.

func NewLocation

func NewLocation(text []byte, file string, row int, col int) *Location

NewLocation returns a new Location object.

type Module

type Module = v1.Module

Module represents a collection of policies (defined by rules) within a namespace (defined by the package) and optional dependencies on external documents (defined by imports).

func MustParseModule

func MustParseModule(input string) *Module

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

func ParseModule(filename, input string) (*Module, error)

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.

type ModuleLoader

type ModuleLoader = v1.ModuleLoader

ModuleLoader defines the interface that callers can implement to enable lazy loading of modules during compilation.

type ModuleTreeNode

type ModuleTreeNode = v1.ModuleTreeNode

ModuleTreeNode represents a node in the module tree. The module tree is keyed by the package path.

type Node

type Node = v1.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 = v1.Null

Null represents the null value defined by JSON.

type Number

type Number = v1.Number

Number represents a numeric value as defined by JSON.

type Object

type Object = v1.Object

Object represents an object as defined by the language.

func LazyObject

func LazyObject(blob map[string]interface{}) Object

func NewObject

func NewObject(t ...[2]*Term) Object

NewObject creates a new Object with t.

type ObjectComprehension

type ObjectComprehension = v1.ObjectComprehension

ObjectComprehension represents an object comprehension as defined in the language.

type ObjectKeysIterator

type ObjectKeysIterator = v1.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

type Package = v1.Package

Package represents the namespace of the documents produced by rules inside the module.

func MustParsePackage

func MustParsePackage(input string) *Package

MustParsePackage returns a Package. If an error occurs during parsing, panic.

func ParsePackage

func ParsePackage(input string) (*Package, error)

ParsePackage returns exactly one Package. If multiple statements are parsed, an error is returned.

type Parser

type Parser = v1.Parser

Parser is used to parse Rego statements.

func NewParser

func NewParser() *Parser

NewParser creates and initializes a Parser.

type ParserErrorDetail

type ParserErrorDetail = v1.ParserErrorDetail

ParserErrorDetail holds additional details for parser errors.

type ParserOptions

type ParserOptions = v1.ParserOptions

ParserOptions defines the options for parsing Rego statements.

type QueryCompiler

type QueryCompiler = v1.QueryCompiler

QueryCompiler defines the interface for compiling ad-hoc queries.

type QueryCompilerStage

type QueryCompilerStage = v1.QueryCompilerStage

QueryCompilerStage defines the interface for stages in the query compiler.

type QueryCompilerStageDefinition

type QueryCompilerStageDefinition = v1.QueryCompilerStageDefinition

QueryCompilerStageDefinition defines a QueryCompiler stage

type QueryContext

type QueryContext = v1.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.

type QueryIterator

type QueryIterator = v1.QueryIterator

QueryIterator defines the interface for querying AST documents with references.

type Ref

type Ref = v1.Ref

Ref represents a reference as defined by the language.

func EmptyRef

func EmptyRef() Ref

EmptyRef returns a new, empty reference.

func MustParseRef

func MustParseRef(input string) Ref

MustParseRef returns a parsed reference. If an error occurs during parsing, panic.

func ParseRef

func ParseRef(input string) (Ref, error)

ParseRef returns exactly one reference.

func PtrRef

func PtrRef(head *Term, s string) (Ref, error)

PtrRef returns a new reference against the head for the pointer s. Path components in the pointer are unescaped.

type RefErrInvalidDetail

type RefErrInvalidDetail = v1.RefErrInvalidDetail

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.)

type RefErrUnsupportedDetail

type RefErrUnsupportedDetail = v1.RefErrUnsupportedDetail

RefErrUnsupportedDetail describes an undefined reference error where the referenced value does not support dereferencing (e.g., scalars).

type RegoVersion

type RegoVersion = v1.RegoVersion

RegoVersion defines the Rego syntax requirements for a module.

func RegoVersionFromInt

func RegoVersionFromInt(i int) RegoVersion

type RelatedResourceAnnotation

type RelatedResourceAnnotation = v1.RelatedResourceAnnotation

type Resolver

type Resolver = v1.Resolver

Resolver defines the interface for resolving references to native Go values.

type Rule

type Rule = v1.Rule

Rule represents a rule as defined in the language. Rules define the content of documents that represent policy decisions.

func MustParseRule

func MustParseRule(input string) *Rule

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

func ParseCompleteDocRuleFromAssignmentExpr(module *Module, lhs, rhs *Term) (*Rule, error)

ParseCompleteDocRuleFromAssignmentExpr returns a rule if the expression can be interpreted as a complete document definition declared with the assignment operator.

func ParseCompleteDocRuleFromEqExpr

func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)

ParseCompleteDocRuleFromEqExpr returns a rule if the expression can be interpreted as a complete document definition.

func ParseCompleteDocRuleWithDotsFromTerm

func ParseCompleteDocRuleWithDotsFromTerm(module *Module, term *Term) (*Rule, error)

func ParsePartialObjectDocRuleFromEqExpr

func ParsePartialObjectDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)

ParsePartialObjectDocRuleFromEqExpr returns a rule if the expression can be interpreted as a partial object document definition.

func ParsePartialSetDocRuleFromTerm

func ParsePartialSetDocRuleFromTerm(module *Module, term *Term) (*Rule, error)

ParsePartialSetDocRuleFromTerm returns a rule if the term can be interpreted as a partial set document definition.

func ParseRule

func ParseRule(input string) (*Rule, error)

ParseRule returns exactly one rule. If multiple rules are parsed, an error is returned.

func ParseRuleFromBody

func ParseRuleFromBody(module *Module, body Body) (*Rule, error)

ParseRuleFromBody returns a rule if the body can be interpreted as a rule definition. Otherwise, an error is returned.

func ParseRuleFromCallEqExpr

func ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error)

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

func ParseRuleFromCallExpr(module *Module, terms []*Term) (*Rule, error)

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

func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error)

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.

type RuleIndex

type RuleIndex v1.RuleIndex

RuleIndex defines the interface for rule indices.

type RuleKind

type RuleKind = v1.RuleKind

type RuleSet

type RuleSet = v1.RuleSet

RuleSet represents a collection of rules that produce a virtual document.

func NewRuleSet

func NewRuleSet(rules ...*Rule) RuleSet

NewRuleSet returns a new RuleSet containing the given rules.

type RulesOptions

type RulesOptions = v1.RulesOptions

RulesOptions defines the options for retrieving rules by Ref from the compiler.

type SchemaAnnotation

type SchemaAnnotation = v1.SchemaAnnotation

SchemaAnnotation contains a schema declaration for the document identified by the path.

type SchemaSet

type SchemaSet = v1.SchemaSet

SchemaSet holds a map from a path to a schema.

func NewSchemaSet

func NewSchemaSet() *SchemaSet

NewSchemaSet returns an empty SchemaSet.

type Set

type Set = v1.Set

Set represents a set as defined by the language.

func NewSet

func NewSet(t ...*Term) Set

NewSet returns a new Set containing t.

type SetComprehension

type SetComprehension = v1.SetComprehension

SetComprehension represents a set comprehension as defined in the language.

type SomeDecl

type SomeDecl = v1.SomeDecl

SomeDecl represents a variable declaration statement. The symbols are variables.

type Statement

type Statement = v1.Statement

Statement represents a single statement in a policy module.

func MustParseStatement

func MustParseStatement(input string) Statement

MustParseStatement returns exactly one statement. If an error occurs during parsing, panic.

func MustParseStatementWithOpts

func MustParseStatementWithOpts(input string, popts ParserOptions) Statement

func MustParseStatements

func MustParseStatements(input string) []Statement

MustParseStatements returns a slice of parsed statements. If an error occurs during parsing, panic.

func ParseStatement

func ParseStatement(input string) (Statement, error)

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 = v1.String

String represents a string value as defined by JSON.

type Term

type Term = v1.Term

Term is an argument to a function.

func ArrayComprehensionTerm

func ArrayComprehensionTerm(term *Term, body Body) *Term

ArrayComprehensionTerm creates a new Term with an ArrayComprehension value.

func ArrayTerm

func ArrayTerm(a ...*Term) *Term

ArrayTerm creates a new Term with an Array value.

func BooleanTerm

func BooleanTerm(b bool) *Term

BooleanTerm creates a new Term with a Boolean value.

func CallTerm

func CallTerm(terms ...*Term) *Term

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

func FloatNumberTerm(f float64) *Term

FloatNumberTerm creates a new Term with a floating point Number value.

func IntNumberTerm

func IntNumberTerm(i int) *Term

IntNumberTerm creates a new Term with an integer Number value.

func InternedBooleanTerm

func InternedBooleanTerm(b bool) *Term

func InternedIntNumberTerm

func InternedIntNumberTerm(i int) *Term

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 Item

func Item(key, value *Term) [2]*Term

Item is a helper for constructing an tuple containing two Terms representing a key/value pair in an Object.

func MustParseTerm

func MustParseTerm(input string) *Term

MustParseTerm returns a parsed term. If an error occurs during parsing, panic.

func NewTerm

func NewTerm(v Value) *Term

NewTerm returns a new Term object.

func NullTerm

func NullTerm() *Term

NullTerm creates a new Term with a Null value.

func NumberTerm

func NumberTerm(n json.Number) *Term

NumberTerm creates a new Term with a Number value.

func ObjectComprehensionTerm

func ObjectComprehensionTerm(key, value *Term, body Body) *Term

ObjectComprehensionTerm creates a new Term with an ObjectComprehension value.

func ObjectTerm

func ObjectTerm(o ...[2]*Term) *Term

ObjectTerm creates a new Term with an Object value.

func ParseTerm

func ParseTerm(input string) (*Term, error)

ParseTerm returns exactly one term. If multiple terms are parsed, an error is returned.

func RefTerm

func RefTerm(r ...*Term) *Term

RefTerm creates a new Term with a Ref value.

func SetComprehensionTerm

func SetComprehensionTerm(term *Term, body Body) *Term

SetComprehensionTerm creates a new Term with an SetComprehension value.

func SetTerm

func SetTerm(t ...*Term) *Term

func StringTerm

func StringTerm(s string) *Term

StringTerm creates a new Term with a String value.

func UIntNumberTerm

func UIntNumberTerm(u uint64) *Term

UIntNumberTerm creates a new Term with an unsigned integer Number value.

func VarTerm

func VarTerm(v string) *Term

VarTerm creates a new Term with a Variable value.

type Transformer

type Transformer = v1.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 = v1.TreeNode

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.

type TypeEnv

type TypeEnv = v1.TypeEnv

TypeEnv contains type info for static analysis such as type checking.

type UnificationErrDetail

type UnificationErrDetail = v1.UnificationErrDetail

UnificationErrDetail describes a type mismatch error when two values are unified (e.g., x = [1,2,y]).

type UnknownValueErr

type UnknownValueErr = v1.UnknownValueErr

UnknownValueErr indicates a ValueResolver was unable to resolve a reference because the reference refers to an unknown value.

type Value

type Value = v1.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

func InterfaceToValue(x interface{}) (Value, error)

InterfaceToValue converts a native Go value x to a Value.

func MustInterfaceToValue

func MustInterfaceToValue(x interface{}) Value

MustInterfaceToValue converts a native Go value x to a Value. If the conversion fails, this function will panic. This function is mostly for test purposes.

func ValueFromReader

func ValueFromReader(r io.Reader) (Value, error)

ValueFromReader returns an AST value from a JSON serialized value in the reader.

type ValueMap

type ValueMap = v1.ValueMap

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.

type ValueResolver

type ValueResolver = v1.ValueResolver

ValueResolver defines the interface for resolving references to AST values.

type Var

type Var = v1.Var

Var represents a variable as defined by the language.

type VarSet

type VarSet = v1.VarSet

VarSet represents a set of variables.

func NewVarSet

func NewVarSet(vs ...Var) VarSet

NewVarSet returns a new VarSet containing the specified variables.

func OutputVarsFromBody

func OutputVarsFromBody(c *Compiler, body Body, safe VarSet) VarSet

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

func OutputVarsFromExpr(c *Compiler, expr *Expr, safe VarSet) VarSet

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

func Unify(safe VarSet, a *Term, b *Term) VarSet

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.

type VarVisitor

type VarVisitor = v1.VarVisitor

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.

type VarVisitorParams

type VarVisitorParams = v1.VarVisitorParams

VarVisitorParams contains settings for a VarVisitor.

type VersionIndex

type VersionIndex = v1.VersionIndex

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

type Visitor = v1.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

type WasmABIVersion = v1.WasmABIVersion

WasmABIVersion captures the Wasm ABI version. Its `Minor` version is indicating backwards-compatible changes.

type With

type With = v1.With

With represents a modifier on an expression.

Source Files

annotations.go builtins.go capabilities.go check.go compare.go compile.go compilehelper.go conflicts.go doc.go env.go errors.go index.go interning.go map.go parser.go parser_ext.go policy.go pretty.go schema.go strings.go term.go transform.go unify.go varset.go visit.go

Directories

PathSynopsis
ast/jsonDeprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended.
ast/locationDeprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended.
Version
v1.4.2 (latest)
Published
May 2, 2025
Platform
linux/amd64
Imports
6 packages
Last checked
2 hours ago

Tools for package owners.