ast

package
v0.32.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2021 License: Apache-2.0 Imports: 26 Imported by: 588

Documentation

Overview

Package ast declares Rego syntax tree types and also includes a parser and compiler for preparing policies for execution in the policy engine.

Rego policies are defined using a relatively small set of types: modules, package and import declarations, rules, expressions, and terms. At their core, policies consist of rules that are defined by one or more expressions over documents available to the policy engine. The expressions are defined by intrinsic values (terms) such as strings, objects, variables, etc.

Rego policies are typically defined in text files and then parsed and compiled by the policy engine at runtime. The parsing stage takes the text or string representation of the policy and converts it into an abstract syntax tree (AST) that consists of the types mentioned above. The AST is organized as follows:

Module
 |
 +--- Package (Reference)
 |
 +--- Imports
 |     |
 |     +--- Import (Term)
 |
 +--- Rules
       |
       +--- Rule
             |
             +--- Head
             |     |
             |     +--- Name (Variable)
             |     |
             |     +--- Key (Term)
             |     |
             |     +--- Value (Term)
             |
             +--- Body
                   |
                   +--- Expression (Term | Terms | 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

Examples

Constants

View Source
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"
)
View Source
const (
	// CompleteDoc represents a document that is completely defined by the rule.
	CompleteDoc = iota

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

	// PartialObjectDoc represents an object document that is partially defined by the rule.
	PartialObjectDoc = iota
)
View Source
const CompileErrorLimitDefault = 10

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

Variables

View Source
var Abs = &Builtin{
	Name: "abs",
	Decl: types.NewFunction(
		types.Args(types.N),
		types.N,
	),
}

Abs returns the number without its sign.

View Source
var AddDate = &Builtin{
	Name: "time.add_date",
	Decl: types.NewFunction(
		types.Args(
			types.N,
			types.N,
			types.N,
			types.N,
		),
		types.N,
	),
}

AddDate returns the nanoseconds since epoch after adding years, months and days to nanoseconds.

View Source
var All = &Builtin{
	Name: "all",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewSet(types.A),
				types.NewArray(nil, types.A),
			),
		),
		types.B,
	),
}

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

View Source
var And = &Builtin{
	Name:  "and",
	Infix: "&",
	Decl: types.NewFunction(
		types.Args(
			types.NewSet(types.A),
			types.NewSet(types.A),
		),
		types.NewSet(types.A),
	),
}

And performs an intersection operation on sets.

View Source
var Any = &Builtin{
	Name: "any",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewSet(types.A),
				types.NewArray(nil, types.A),
			),
		),
		types.B,
	),
}

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

View Source
var ArrayConcat = &Builtin{
	Name: "array.concat",
	Decl: types.NewFunction(
		types.Args(
			types.NewArray(nil, types.A),
			types.NewArray(nil, types.A),
		),
		types.NewArray(nil, types.A),
	),
}

ArrayConcat returns the result of concatenating two arrays together.

View Source
var ArraySlice = &Builtin{
	Name: "array.slice",
	Decl: types.NewFunction(
		types.Args(
			types.NewArray(nil, types.A),
			types.NewNumber(),
			types.NewNumber(),
		),
		types.NewArray(nil, types.A),
	),
}

ArraySlice returns a slice of a given array

View Source
var Assign = &Builtin{
	Name:  "assign",
	Infix: ":=",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

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

View Source
var Base64Decode = &Builtin{
	Name: "base64.decode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Base64Decode deserializes the base64 encoded input string.

View Source
var Base64Encode = &Builtin{
	Name: "base64.encode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Base64Encode serializes the input string into base64 encoding.

View Source
var Base64IsValid = &Builtin{
	Name: "base64.is_valid",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.B,
	),
}

Base64IsValid verifies the input string is base64 encoded.

View Source
var Base64UrlDecode = &Builtin{
	Name: "base64url.decode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Base64UrlDecode deserializes the base64url encoded input string.

View Source
var Base64UrlEncode = &Builtin{
	Name: "base64url.encode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Base64UrlEncode serializes the input string into base64url encoding.

View Source
var Base64UrlEncodeNoPad = &Builtin{
	Name: "base64url.encode_no_pad",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Base64UrlEncodeNoPad serializes the input string into base64url encoding without padding.

View Source
var BitsAnd = &Builtin{
	Name: "bits.and",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

BitsAnd returns the bitwise "and" of two integers.

View Source
var BitsNegate = &Builtin{
	Name: "bits.negate",
	Decl: types.NewFunction(
		types.Args(types.N),
		types.N,
	),
}

BitsNegate returns the bitwise "negation" of an integer (i.e. flips each bit).

View Source
var BitsOr = &Builtin{
	Name: "bits.or",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

BitsOr returns the bitwise "or" of two integers.

View Source
var BitsShiftLeft = &Builtin{
	Name: "bits.lsh",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

BitsShiftLeft returns a new integer with its bits shifted some value to the left.

View Source
var BitsShiftRight = &Builtin{
	Name: "bits.rsh",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

BitsShiftRight returns a new integer with its bits shifted some value to the right.

View Source
var BitsXOr = &Builtin{
	Name: "bits.xor",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

BitsXOr returns the bitwise "exclusive-or" of two integers.

View Source
var BuiltinMap map[string]*Builtin

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

View Source
var Builtins []*Builtin

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

View Source
var CastArray = &Builtin{
	Name: "cast_array",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.NewArray(nil, types.A),
	),
}

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.

View Source
var CastBoolean = &Builtin{
	Name: "cast_boolean",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.B,
	),
}

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

View Source
var CastNull = &Builtin{
	Name: "cast_null",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.NewNull(),
	),
}

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

View Source
var CastObject = &Builtin{
	Name: "cast_object",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)),
	),
}

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

View Source
var CastSet = &Builtin{
	Name: "cast_set",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.NewSet(types.A),
	),
}

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

View Source
var CastString = &Builtin{
	Name: "cast_string",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.S,
	),
}

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

View Source
var Ceil = &Builtin{
	Name: "ceil",
	Decl: types.NewFunction(
		types.Args(types.N),
		types.N,
	),
}

Ceil rounds the number up to the nearest integer.

View Source
var Clock = &Builtin{
	Name: "time.clock",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.N,
				types.NewArray([]types.Type{types.N, types.S}, nil),
			),
		),
		types.NewArray([]types.Type{types.N, types.N, types.N}, nil),
	),
}

Clock returns the [hour, minute, second] of the day for the nanoseconds since epoch.

View Source
var Concat = &Builtin{
	Name: "concat",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.NewAny(
				types.NewSet(types.S),
				types.NewArray(nil, types.S),
			),
		),
		types.S,
	),
}

Concat joins an array of strings with an input string.

View Source
var Contains = &Builtin{
	Name: "contains",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

Contains returns true if the search string is included in the base string

Count takes a collection or string and counts the number of elements in it.

View Source
var CryptoMd5 = &Builtin{
	Name: "crypto.md5",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

CryptoMd5 returns a string representing the input string hashed with the md5 function

View Source
var CryptoSha1 = &Builtin{
	Name: "crypto.sha1",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

CryptoSha1 returns a string representing the input string hashed with the sha1 function

View Source
var CryptoSha256 = &Builtin{
	Name: "crypto.sha256",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

CryptoSha256 returns a string representing the input string hashed with the sha256 function

View Source
var CryptoX509ParseAndVerifyCertificates = &Builtin{
	Name: "crypto.x509.parse_and_verify_certificates",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.NewArray([]types.Type{
			types.B,
			types.NewArray(nil, types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))),
		}, nil),
	),
}

CryptoX509ParseAndVerifyCertificates returns one or more certificates from the given string containing PEM or base64 encoded DER certificates after verifying the supplied certificates form a complete certificate chain back to a trusted root.

The first certificate is treated as the root and the last is treated as the leaf, with all others being treated as intermediates

View Source
var CryptoX509ParseCertificateRequest = &Builtin{
	Name: "crypto.x509.parse_certificate_request",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.NewObject(nil, types.NewDynamicProperty(types.S, types.A)),
	),
}

CryptoX509ParseCertificateRequest returns a PKCS #10 certificate signing request from the given PEM-encoded PKCS#10 certificate signing request.

View Source
var CryptoX509ParseCertificates = &Builtin{
	Name: "crypto.x509.parse_certificates",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.NewArray(nil, types.NewObject(nil, types.NewDynamicProperty(types.S, types.A))),
	),
}

CryptoX509ParseCertificates returns one or more certificates from the given base64 encoded string containing DER encoded certificates that have been concatenated.

View Source
var Date = &Builtin{
	Name: "time.date",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.N,
				types.NewArray([]types.Type{types.N, types.S}, nil),
			),
		),
		types.NewArray([]types.Type{types.N, types.N, types.N}, nil),
	),
}

Date returns the [year, month, day] for the nanoseconds since epoch.

View Source
var DefaultBuiltins = [...]*Builtin{}/* 156 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.

View Source
var DefaultRootDocument = VarTerm("data")

DefaultRootDocument is the default root document.

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

View Source
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.

Diff returns the difference [years, months, days, hours, minutes, seconds] between two unix timestamps in nanoseconds

View Source
var Divide = &Builtin{
	Name:  "div",
	Infix: "/",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

Divide divides the first number by the second number.

View Source
var EndsWith = &Builtin{
	Name: "endswith",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

EndsWith returns true if the search string begins with the base string

View Source
var Equal = &Builtin{
	Name:  "equal",
	Infix: "==",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

Equal represents the "==" comparison operator.

View Source
var Equality = &Builtin{
	Name:  "eq",
	Infix: "=",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

Equality represents the "=" operator.

View Source
var Floor = &Builtin{
	Name: "floor",
	Decl: types.NewFunction(
		types.Args(types.N),
		types.N,
	),
}

Floor rounds the number down to the nearest integer.

View Source
var FormatInt = &Builtin{
	Name: "format_int",
	Decl: types.NewFunction(
		types.Args(
			types.N,
			types.N,
		),
		types.S,
	),
}

FormatInt returns the string representation of the number in the given base after converting it to an integer value.

View Source
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.

View Source
var GlobMatch = &Builtin{
	Name: "glob.match",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.NewArray(nil, types.S),
			types.S,
		),
		types.B,
	),
}

GlobMatch - not to be confused with regex.globs_match - parses and matches strings against the glob notation.

View Source
var GlobQuoteMeta = &Builtin{
	Name: "glob.quote_meta",
	Decl: types.NewFunction(
		types.Args(
			types.S,
		),
		types.S,
	),
}

GlobQuoteMeta returns a string which represents a version of the pattern where all asterisks have been escaped.

View Source
var GlobsMatch = &Builtin{
	Name: "regex.globs_match",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

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.
View Source
var GreaterThan = &Builtin{
	Name:  "gt",
	Infix: ">",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

GreaterThan represents the ">" comparison operator.

View Source
var GreaterThanEq = &Builtin{
	Name:  "gte",
	Infix: ">=",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

GreaterThanEq represents the ">=" comparison operator.

HTTPSend returns a HTTP response to the given HTTP request.

View Source
var HexDecode = &Builtin{
	Name: "hex.decode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

HexDecode deserializes the hex encoded input string.

View Source
var HexEncode = &Builtin{
	Name: "hex.encode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

HexEncode serializes the input string into hex encoding.

View Source
var IgnoreDuringPartialEval = []*Builtin{
	NowNanos,
	HTTPSend,
	UUIDRFC4122,
	RandIntn,
}

IgnoreDuringPartialEval is a set of built-in functions that should not be evaluated during partial evaluation. These functions are not partially evaluated because they are not pure.

View Source
var IndexOf = &Builtin{
	Name: "indexof",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.N,
	),
}

IndexOf returns the index of a substring contained inside a string

View Source
var InputRootDocument = VarTerm("input")

InputRootDocument names the document containing query arguments.

View Source
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.

View Source
var Intersection = &Builtin{
	Name: "intersection",
	Decl: types.NewFunction(
		types.Args(
			types.NewSet(types.NewSet(types.A)),
		),
		types.NewSet(types.A),
	),
}

Intersection returns the intersection of the given input sets

View Source
var IsArray = &Builtin{
	Name: "is_array",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsArray returns true if the input value is an array.

View Source
var IsBoolean = &Builtin{
	Name: "is_boolean",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsBoolean returns true if the input value is a boolean.

View Source
var IsNull = &Builtin{
	Name: "is_null",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsNull returns true if the input value is null.

View Source
var IsNumber = &Builtin{
	Name: "is_number",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsNumber returns true if the input value is a number

View Source
var IsObject = &Builtin{
	Name: "is_object",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsObject returns true if the input value is an object.

View Source
var IsSet = &Builtin{
	Name: "is_set",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsSet returns true if the input value is a set.

View Source
var IsString = &Builtin{
	Name: "is_string",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

IsString returns true if the input value is a string.

JSONFilter filters the JSON object

View Source
var JSONIsValid = &Builtin{
	Name: "json.is_valid",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.B,
	),
}

JSONIsValid verifies the input string is a valid JSON document.

View Source
var JSONMarshal = &Builtin{
	Name: "json.marshal",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.S,
	),
}

JSONMarshal serializes the input term.

View Source
var JSONPatch = &Builtin{
	Name: "json.patch",
	Decl: types.NewFunction(
		types.Args(
			types.A,
			types.NewArray(
				nil,
				types.NewObject(
					[]*types.StaticProperty{
						{Key: "op", Value: types.S},
						{Key: "path", Value: types.A},
					},
					types.NewDynamicProperty(types.A, types.A),
				),
			),
		),
		types.A,
	),
}

JSONPatch patches a JSON object according to RFC6902

JSONRemove removes paths in the JSON object

View Source
var JSONUnmarshal = &Builtin{
	Name: "json.unmarshal",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.A,
	),
}

JSONUnmarshal deserializes the input string.

JWTDecode decodes a JSON Web Token and outputs it as an Object.

JWTDecodeVerify verifies a JWT signature under parameterized constraints and decodes the claims if it is valid.

JWTEncodeSign encodes and optionally sign a JSON Web Token. Inputs are protected headers, payload, secret

View Source
var JWTEncodeSignRaw = &Builtin{
	Name: "io.jwt.encode_sign_raw",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
			types.S,
		),
		types.S,
	),
}

JWTEncodeSignRaw encodes and optionally sign a JSON Web Token. Inputs are protected headers, payload, secret

View Source
var JWTVerifyES256 = &Builtin{
	Name: "io.jwt.verify_es256",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyES256 verifies if a ES256 JWT signature is valid or not.

View Source
var JWTVerifyES384 = &Builtin{
	Name: "io.jwt.verify_es384",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyES384 verifies if a ES384 JWT signature is valid or not.

View Source
var JWTVerifyES512 = &Builtin{
	Name: "io.jwt.verify_es512",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyES512 verifies if a ES512 JWT signature is valid or not.

View Source
var JWTVerifyHS256 = &Builtin{
	Name: "io.jwt.verify_hs256",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyHS256 verifies if a HS256 (secret) JWT signature is valid or not.

View Source
var JWTVerifyHS384 = &Builtin{
	Name: "io.jwt.verify_hs384",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyHS384 verifies if a HS384 (secret) JWT signature is valid or not.

View Source
var JWTVerifyHS512 = &Builtin{
	Name: "io.jwt.verify_hs512",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyHS512 verifies if a HS512 (secret) JWT signature is valid or not.

View Source
var JWTVerifyPS256 = &Builtin{
	Name: "io.jwt.verify_ps256",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyPS256 verifies if a PS256 JWT signature is valid or not.

View Source
var JWTVerifyPS384 = &Builtin{
	Name: "io.jwt.verify_ps384",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyPS384 verifies if a PS384 JWT signature is valid or not.

View Source
var JWTVerifyPS512 = &Builtin{
	Name: "io.jwt.verify_ps512",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyPS512 verifies if a PS512 JWT signature is valid or not.

View Source
var JWTVerifyRS256 = &Builtin{
	Name: "io.jwt.verify_rs256",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyRS256 verifies if a RS256 JWT signature is valid or not.

View Source
var JWTVerifyRS384 = &Builtin{
	Name: "io.jwt.verify_rs384",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyRS384 verifies if a RS384 JWT signature is valid or not.

View Source
var JWTVerifyRS512 = &Builtin{
	Name: "io.jwt.verify_rs512",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

JWTVerifyRS512 verifies if a RS512 JWT signature is valid or not.

View Source
var Keywords = [...]string{
	"not",
	"package",
	"import",
	"as",
	"default",
	"else",
	"with",
	"null",
	"true",
	"false",
	"some",
}

Keywords contains strings that map to language keywords.

View Source
var LessThan = &Builtin{
	Name:  "lt",
	Infix: "<",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

LessThan represents the "<" comparison operator.

View Source
var LessThanEq = &Builtin{
	Name:  "lte",
	Infix: "<=",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

LessThanEq represents the "<=" comparison operator.

View Source
var Lower = &Builtin{
	Name: "lower",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Lower returns the input string but with all characters in lower-case

View Source
var Max = &Builtin{
	Name: "max",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewSet(types.A),
				types.NewArray(nil, types.A),
			),
		),
		types.A,
	),
}

Max returns the maximum value in a collection.

View Source
var Min = &Builtin{
	Name: "min",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewSet(types.A),
				types.NewArray(nil, types.A),
			),
		),
		types.A,
	),
}

Min returns the minimum value in a collection.

View Source
var Minus = &Builtin{
	Name:  "minus",
	Infix: "-",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(types.N, types.NewSet(types.A)),
			types.NewAny(types.N, types.NewSet(types.A)),
		),
		types.NewAny(types.N, types.NewSet(types.A)),
	),
}

Minus subtracts the second number from the first number or computes the diff between two sets.

View Source
var Multiply = &Builtin{
	Name:  "mul",
	Infix: "*",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

Multiply multiplies two numbers together.

View Source
var NetCIDRContains = &Builtin{
	Name: "net.cidr_contains",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

NetCIDRContains checks if a cidr or ip is contained within another cidr and returns true or false

View Source
var NetCIDRContainsMatches = &Builtin{
	Name: "net.cidr_contains_matches",
	Decl: types.NewFunction(
		types.Args(netCidrContainsMatchesOperandType, netCidrContainsMatchesOperandType),
		types.NewSet(types.NewArray([]types.Type{types.A, types.A}, nil)),
	),
}

NetCIDRContainsMatches checks if collections of cidrs or ips are contained within another collection of cidrs and returns matches.

View Source
var NetCIDRExpand = &Builtin{
	Name: "net.cidr_expand",
	Decl: types.NewFunction(
		types.Args(
			types.S,
		),
		types.NewSet(types.S),
	),
}

NetCIDRExpand returns a set of hosts inside the specified cidr.

View Source
var NetCIDRIntersects = &Builtin{
	Name: "net.cidr_intersects",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

NetCIDRIntersects checks if a cidr intersects with another cidr and returns true or false

View Source
var NetCIDRMerge = &Builtin{
	Name: "net.cidr_merge",
	Decl: types.NewFunction(
		types.Args(netCidrMergeOperandType),
		types.NewSet(types.S),
	),
}

NetCIDRMerge merges IP addresses and subnets into the smallest possible list of CIDRs.

View Source
var NetCIDROverlap = &Builtin{
	Name: "net.cidr_overlap",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

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

View Source
var NotEqual = &Builtin{
	Name:  "neq",
	Infix: "!=",
	Decl: types.NewFunction(
		types.Args(types.A, types.A),
		types.B,
	),
}

NotEqual represents the "!=" comparison operator.

View Source
var NowNanos = &Builtin{
	Name: "time.now_ns",
	Decl: types.NewFunction(
		nil,
		types.N,
	),
}

NowNanos returns the current time since epoch in nanoseconds.

View Source
var NumbersRange = &Builtin{
	Name: "numbers.range",
	Decl: types.NewFunction(
		types.Args(
			types.N,
			types.N,
		),
		types.NewArray(nil, types.N),
	),
}

NumbersRange returns an array of numbers in the given inclusive range.

View Source
var OPARuntime = &Builtin{
	Name: "opa.runtime",
	Decl: types.NewFunction(
		nil,
		types.NewObject(nil, types.NewDynamicProperty(types.S, types.A)),
	),
}

OPARuntime returns an object containing OPA runtime information such as the configuration that OPA was booted with.

ObjectFilter filters the object by keeping only specified keys

View Source
var ObjectGet = &Builtin{
	Name: "object.get",
	Decl: types.NewFunction(
		types.Args(
			types.NewObject(nil, types.NewDynamicProperty(types.A, types.A)),
			types.A,
			types.A,
		),
		types.A,
	),
}

ObjectGet returns takes an object and returns a value under its key if present, otherwise it returns the default.

ObjectRemove Removes specified keys from an object

View Source
var ObjectUnion = &Builtin{
	Name: "object.union",
	Decl: types.NewFunction(
		types.Args(
			types.NewObject(
				nil,
				types.NewDynamicProperty(types.A, types.A),
			),
			types.NewObject(
				nil,
				types.NewDynamicProperty(types.A, types.A),
			),
		),
		types.A,
	),
}

ObjectUnion creates a new object that is the asymmetric union of two objects

View Source
var Or = &Builtin{
	Name:  "or",
	Infix: "|",
	Decl: types.NewFunction(
		types.Args(
			types.NewSet(types.A),
			types.NewSet(types.A),
		),
		types.NewSet(types.A),
	),
}

Or performs a union operation on sets.

View Source
var ParseDurationNanos = &Builtin{
	Name: "time.parse_duration_ns",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.N,
	),
}

ParseDurationNanos returns the duration in nanoseconds represented by a duration string. Duration string is similar to the Go time.ParseDuration string

View Source
var ParseNanos = &Builtin{
	Name: "time.parse_ns",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.N,
	),
}

ParseNanos returns the time in nanoseconds parsed from the string in the given format.

View Source
var ParseRFC3339Nanos = &Builtin{
	Name: "time.parse_rfc3339_ns",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.N,
	),
}

ParseRFC3339Nanos returns the time in nanoseconds parsed from the string in RFC3339 format.

View Source
var Plus = &Builtin{
	Name:  "plus",
	Infix: "+",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

Plus adds two numbers together.

View Source
var Product = &Builtin{
	Name: "product",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewSet(types.N),
				types.NewArray(nil, types.N),
			),
		),
		types.N,
	),
}

Product takes an array or set of numbers and multiplies them.

View Source
var RandIntn = &Builtin{
	Name: "rand.intn",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.N,
		),
		types.N,
	),
}

RandIntn returns a random number 0 - n

ReachableBuiltin computes the set of reachable nodes in the graph from a set of starting nodes.

View Source
var RegexFind = &Builtin{
	Name: "regex.find_n",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
			types.N,
		),
		types.NewArray(nil, types.S),
	),
}

RegexFind takes two strings and a number, the pattern, the value and number of match values to return, -1 means all match values.

View Source
var RegexFindAllStringSubmatch = &Builtin{
	Name: "regex.find_all_string_submatch_n",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
			types.N,
		),
		types.NewArray(nil, types.NewArray(nil, types.S)),
	),
}

RegexFindAllStringSubmatch returns an array of all successive matches of the expression. It takes two strings and a number, the pattern, the value and number of matches to return, -1 means all matches.

View Source
var RegexIsValid = &Builtin{
	Name: "regex.is_valid",
	Decl: types.NewFunction(
		types.Args(
			types.S,
		),
		types.B,
	),
}

RegexIsValid returns true if the regex pattern string is valid, otherwise false.

View Source
var RegexMatch = &Builtin{
	Name: "regex.match",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

RegexMatch takes two strings and evaluates to true if the string in the second position matches the pattern in the first position.

View Source
var RegexMatchDeprecated = &Builtin{
	Name: "re_match",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

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

View Source
var RegexSplit = &Builtin{
	Name: "regex.split",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.NewArray(nil, types.S),
	),
}

RegexSplit splits the input string by the occurrences of the given pattern.

View Source
var RegexTemplateMatch = &Builtin{
	Name: "regex.template_match",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
			types.S,
			types.S,
		),
		types.B,
	),
}

RegexTemplateMatch takes two strings and evaluates to true if the string in the second position matches the pattern in the first position.

View Source
var RegoParseModule = &Builtin{
	Name: "rego.parse_module",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.NewObject(nil, types.NewDynamicProperty(types.S, types.A)),
	),
}

RegoParseModule parses the input Rego file and returns a JSON representation of the AST.

View Source
var Rem = &Builtin{
	Name:  "rem",
	Infix: "%",
	Decl: types.NewFunction(
		types.Args(types.N, types.N),
		types.N,
	),
}

Rem returns the remainder for x%y for y != 0.

View Source
var Replace = &Builtin{
	Name: "replace",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
			types.S,
		),
		types.S,
	),
}

Replace returns the given string with all instances of the second argument replaced by the third.

View Source
var ReplaceN = &Builtin{
	Name: "strings.replace_n",
	Decl: types.NewFunction(
		types.Args(
			types.NewObject(
				nil,
				types.NewDynamicProperty(
					types.S,
					types.S)),
			types.S,
		),
		types.S,
	),
}

ReplaceN replaces a string from a list of old, new string pairs. Replacements are performed in the order they appear in the target string, without overlapping matches. The old string comparisons are done in argument order.

View Source
var ReservedVars = NewVarSet(
	DefaultRootDocument.Value.(Var),
	InputRootDocument.Value.(Var),
)

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

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

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

View Source
var Round = &Builtin{
	Name: "round",
	Decl: types.NewFunction(
		types.Args(types.N),
		types.N,
	),
}

Round rounds the number to the nearest integer.

View Source
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.

View Source
var SchemaRootDocument = VarTerm("schema")

SchemaRootDocument names the document containing external data schemas.

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

View Source
var SemVerCompare = &Builtin{
	Name: "semver.compare",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.N,
	),
}

SemVerCompare compares valid SemVer formatted version strings. Given two version strings, if A < B returns -1, if A > B returns 1. If A == B, returns 0

View Source
var SemVerIsValid = &Builtin{
	Name: "semver.is_valid",
	Decl: types.NewFunction(
		types.Args(
			types.A,
		),
		types.B,
	),
}

SemVerIsValid validiates a the term is a valid SemVer as a string, returns false for all other input

View Source
var SetDiff = &Builtin{
	Name: "set_diff",
	Decl: types.NewFunction(
		types.Args(
			types.NewSet(types.A),
			types.NewSet(types.A),
		),
		types.NewSet(types.A),
	),
}

SetDiff has been replaced by the minus built-in.

View Source
var Sort = &Builtin{
	Name: "sort",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewArray(nil, types.A),
				types.NewSet(types.A),
			),
		),
		types.NewArray(nil, types.A),
	),
}

Sort returns a sorted array.

View Source
var Split = &Builtin{
	Name: "split",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.NewArray(nil, types.S),
	),
}

Split returns an array containing elements of the input string split on a delimiter.

View Source
var Sprintf = &Builtin{
	Name: "sprintf",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.NewArray(nil, types.A),
		),
		types.S,
	),
}

Sprintf returns the given string, formatted.

View Source
var StartsWith = &Builtin{
	Name: "startswith",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.B,
	),
}

StartsWith returns true if the search string begins with the base string

View Source
var Substring = &Builtin{
	Name: "substring",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.N,
			types.N,
		),
		types.S,
	),
}

Substring returns the portion of a string for a given start index and a length.

If the length is less than zero, then substring returns the remainder of the string.
View Source
var Sum = &Builtin{
	Name: "sum",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.NewSet(types.N),
				types.NewArray(nil, types.N),
			),
		),
		types.N,
	),
}

Sum takes an array or set of numbers and sums them.

View Source
var SystemDocumentKey = String("system")

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

View Source
var ToNumber = &Builtin{
	Name: "to_number",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.N,
				types.S,
				types.B,
				types.NewNull(),
			),
		),
		types.N,
	),
}

ToNumber takes a string, bool, or number value and converts it to a number. Strings are converted to numbers using strconv.Atoi. Boolean false is converted to 0 and boolean true is converted to 1.

View Source
var Trace = &Builtin{
	Name: "trace",
	Decl: types.NewFunction(
		types.Args(
			types.S,
		),
		types.B,
	),
}

Trace prints a note that is included in the query explanation.

View Source
var Trim = &Builtin{
	Name: "trim",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.S,
	),
}

Trim returns the given string with all leading or trailing instances of the second argument removed.

View Source
var TrimLeft = &Builtin{
	Name: "trim_left",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.S,
	),
}

TrimLeft returns the given string with all leading instances of second argument removed.

View Source
var TrimPrefix = &Builtin{
	Name: "trim_prefix",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.S,
	),
}

TrimPrefix returns the given string without the second argument prefix string. If the given string doesn't start with prefix, it is returned unchanged.

View Source
var TrimRight = &Builtin{
	Name: "trim_right",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.S,
	),
}

TrimRight returns the given string with all trailing instances of second argument removed.

View Source
var TrimSpace = &Builtin{
	Name: "trim_space",
	Decl: types.NewFunction(
		types.Args(
			types.S,
		),
		types.S,
	),
}

TrimSpace return the given string with all leading and trailing white space removed.

View Source
var TrimSuffix = &Builtin{
	Name: "trim_suffix",
	Decl: types.NewFunction(
		types.Args(
			types.S,
			types.S,
		),
		types.S,
	),
}

TrimSuffix returns the given string without the second argument suffix string. If the given string doesn't end with suffix, it is returned unchanged.

View Source
var TypeNameBuiltin = &Builtin{
	Name: "type_name",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.A,
			),
		),
		types.S,
	),
}

TypeNameBuiltin returns the type of the input.

View Source
var URLQueryDecode = &Builtin{
	Name: "urlquery.decode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

URLQueryDecode decodes a URL encoded input string.

View Source
var URLQueryDecodeObject = &Builtin{
	Name: "urlquery.decode_object",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.NewObject(nil, types.NewDynamicProperty(
			types.S,
			types.NewArray(nil, types.S))),
	),
}

URLQueryDecodeObject decodes the given URL query string into an object.

View Source
var URLQueryEncode = &Builtin{
	Name: "urlquery.encode",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

URLQueryEncode encodes the input string into a URL encoded string.

View Source
var URLQueryEncodeObject = &Builtin{
	Name: "urlquery.encode_object",
	Decl: types.NewFunction(
		types.Args(
			types.NewObject(
				nil,
				types.NewDynamicProperty(
					types.S,
					types.NewAny(
						types.S,
						types.NewArray(nil, types.S),
						types.NewSet(types.S))))),
		types.S,
	),
}

URLQueryEncodeObject encodes the given JSON into a URL encoded query string.

View Source
var UUIDRFC4122 = &Builtin{
	Name: "uuid.rfc4122",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

UUIDRFC4122 returns a version 4 UUID string.

View Source
var Union = &Builtin{
	Name: "union",
	Decl: types.NewFunction(
		types.Args(
			types.NewSet(types.NewSet(types.A)),
		),
		types.NewSet(types.A),
	),
}

Union returns the union of the given input sets

View Source
var UnitsParseBytes = &Builtin{
	Name: "units.parse_bytes",
	Decl: types.NewFunction(
		types.Args(
			types.S,
		),
		types.N,
	),
}

UnitsParseBytes converts strings like 10GB, 5K, 4mb, and the like into an integer number of bytes.

View Source
var Upper = &Builtin{
	Name: "upper",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.S,
	),
}

Upper returns the input string but with all characters in upper-case

View Source
var WalkBuiltin = &Builtin{
	Name:     "walk",
	Relation: true,
	Decl: types.NewFunction(
		types.Args(types.A),
		types.NewArray(
			[]types.Type{
				types.NewArray(nil, types.A),
				types.A,
			},
			nil,
		),
	),
}

WalkBuiltin generates [path, value] tuples for all nested documents (recursively).

View Source
var Weekday = &Builtin{
	Name: "time.weekday",
	Decl: types.NewFunction(
		types.Args(
			types.NewAny(
				types.N,
				types.NewArray([]types.Type{types.N, types.S}, nil),
			),
		),
		types.S,
	),
}

Weekday returns the day of the week (Monday, Tuesday, ...) for the nanoseconds since epoch.

View Source
var Wildcard = &Term{Value: Var("_")}

Wildcard represents the wildcard variable as defined in the language.

View Source
var WildcardPrefix = "$"

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

View Source
var YAMLIsValid = &Builtin{
	Name: "yaml.is_valid",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.B,
	),
}

YAMLIsValid verifies the input string is a valid YAML document.

View Source
var YAMLMarshal = &Builtin{
	Name: "yaml.marshal",
	Decl: types.NewFunction(
		types.Args(types.A),
		types.S,
	),
}

YAMLMarshal serializes the input term.

View Source
var YAMLUnmarshal = &Builtin{
	Name: "yaml.unmarshal",
	Decl: types.NewFunction(
		types.Args(types.S),
		types.A,
	),
}

YAMLUnmarshal deserializes the input string.

Functions

func As added in v0.14.0

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

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

func Compare added in v0.2.0

func Compare(a, b interface{}) int

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

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

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

nil < Null < Boolean < Number < String < Var < Ref < Array < Object < Set < ArrayComprehension < ObjectComprehension < SetComprehension < Expr < SomeDecl < With < Body < Rule < Import < Package < Module.

Arrays and Refs are equal iff both a and b have the same length and all corresponding elements are equal. If one element is not equal, the return value is the same as for the first differing element. If all elements are equal but a and b have different lengths, the shorter is considered less than the other.

Objects are considered equal iff both a and b have the same sorted (key, value) pairs and are of the same length. Other comparisons are consistent but not defined.

Sets are considered equal iff the symmetric difference of a and b is empty. Other comparisons are consistent but not defined.

func ContainsComprehensions added in v0.5.8

func ContainsComprehensions(v interface{}) bool

ContainsComprehensions returns true if the Value v contains comprehensions.

func ContainsRefs added in v0.5.8

func ContainsRefs(v interface{}) bool

ContainsRefs returns true if the Value v contains refs.

func Copy added in v0.20.5

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 IsComprehension added in v0.5.11

func IsComprehension(x Value) bool

IsComprehension returns true if the supplied value is a comprehension.

func IsConstant added in v0.4.9

func IsConstant(v Value) bool

IsConstant returns true if the AST value is constant.

func IsError added in v0.4.0

func IsError(code string, err error) bool

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

func IsKeyword added in v0.2.2

func IsKeyword(s string) bool

IsKeyword returns true if s is a language keyword.

func IsScalar added in v0.2.0

func IsScalar(v Value) bool

IsScalar returns true if the AST value is a scalar.

func IsUnknownValueErr added in v0.9.0

func IsUnknownValueErr(err error) bool

IsUnknownValueErr returns true if the err is an UnknownValueErr.

func IsValidImportPath added in v0.3.0

func IsValidImportPath(v Value) (err error)

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

func JSON added in v0.4.9

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 added in v0.27.1

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 MustJSON added in v0.25.0

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 added in v0.28.0

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 added in v0.7.0

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 added in v0.2.0

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

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

func TransformComprehensions added in v0.5.8

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

TransformComprehensions calls the functio nf on all comprehensions under x.

func TransformRefs added in v0.2.0

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

TransformRefs calls the function f on all references under x.

func TransformVars added in v0.7.0

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

TransformVars calls the function f on all vars under x.

func TypeName added in v0.3.0

func TypeName(x interface{}) string

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

func ValueToInterface added in v0.4.9

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. This is deprecated.

func WalkBeforeAndAfter added in v0.7.0

func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{})

WalkBeforeAndAfter iterates the AST by calling the Visit function on the Visitor v for x before recursing. This is deprecated.

func WalkBodies added in v0.2.0

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 added in v0.4.9

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 added in v0.9.2

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 added in v0.4.10

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 added in v0.7.0

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 added in v0.2.1

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 added in v0.4.1

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 Annotations added in v0.28.0

type Annotations struct {
	Location *Location           `json:"-"`
	Scope    string              `json:"scope"`
	Schemas  []*SchemaAnnotation `json:"schemas,omitempty"`
	// contains filtered or unexported fields
}

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

func (*Annotations) Compare added in v0.28.0

func (s *Annotations) Compare(other *Annotations) int

Compare returns an integer indicating if s is less than, equal to, or greater than other.

func (*Annotations) Copy added in v0.28.0

func (s *Annotations) Copy(node Node) *Annotations

Copy returns a deep copy of s.

func (*Annotations) Loc added in v0.28.0

func (s *Annotations) Loc() *Location

Loc returns the location of this annotation.

func (*Annotations) SetLoc added in v0.28.0

func (s *Annotations) SetLoc(l *Location)

SetLoc updates the location of this annotation.

func (*Annotations) String added in v0.28.0

func (s *Annotations) String() string

type ArgErrDetail added in v0.4.9

type ArgErrDetail struct {
	Have []types.Type `json:"have"`
	Want []types.Type `json:"want"`
}

ArgErrDetail represents a generic argument error.

func (*ArgErrDetail) Lines added in v0.4.9

func (d *ArgErrDetail) Lines() []string

Lines returns the string representation of the detail.

type Args added in v0.5.0

type Args []*Term

Args represents zero or more arguments to a rule.

func (Args) Copy added in v0.5.0

func (a Args) Copy() Args

Copy returns a deep copy of a.

func (Args) Loc added in v0.9.2

func (a Args) Loc() *Location

Loc returns the Location of a.

func (Args) SetLoc added in v0.9.2

func (a Args) SetLoc(loc *Location)

SetLoc sets the location on a.

func (Args) String added in v0.5.0

func (a Args) String() string

func (Args) Vars added in v0.5.9

func (a Args) Vars() VarSet

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 added in v0.23.0

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

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

func (*Array) Append added in v0.23.0

func (arr *Array) Append(v *Term) *Array

Append appends a term to arr, returning the appended array.

func (*Array) Compare added in v0.5.0

func (arr *Array) Compare(other Value) int

Compare compares arr to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (*Array) Copy added in v0.2.2

func (arr *Array) Copy() *Array

Copy returns a deep copy of arr.

func (*Array) Elem added in v0.23.0

func (arr *Array) Elem(i int) *Term

Elem returns the element i of arr.

func (*Array) Equal

func (arr *Array) Equal(other Value) bool

Equal returns true if arr is equal to other.

func (*Array) Find added in v0.4.5

func (arr *Array) Find(path Ref) (Value, error)

Find returns the value at the index or an out-of-range error.

func (*Array) Foreach added in v0.23.0

func (arr *Array) Foreach(f func(*Term))

Foreach calls f on each element in arr.

func (*Array) Get added in v0.4.9

func (arr *Array) Get(pos *Term) *Term

Get returns the element at pos or nil if not possible.

func (*Array) Hash

func (arr *Array) Hash() int

Hash returns the hash code for the Value.

func (*Array) IsGround

func (arr *Array) IsGround() bool

IsGround returns true if all of the Array elements are ground.

func (*Array) Iter added in v0.23.0

func (arr *Array) Iter(f func(*Term) error) error

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 added in v0.23.0

func (arr *Array) Len() int

Len returns the number of elements in the array.

func (*Array) MarshalJSON added in v0.3.0

func (arr *Array) MarshalJSON() ([]byte, error)

MarshalJSON returns JSON encoded bytes representing arr.

func (*Array) Slice added in v0.23.0

func (arr *Array) Slice(i, j int) *Array

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 added in v0.6.0

func (arr *Array) Sorted() *Array

Sorted returns a new Array that contains the sorted elements of arr.

func (*Array) String

func (arr *Array) String() string

func (*Array) Until added in v0.23.0

func (arr *Array) Until(f func(*Term) bool) bool

Until calls f on each element in arr. If f returns true, iteration stops.

type ArrayComprehension

type ArrayComprehension struct {
	Term *Term `json:"term"`
	Body Body  `json:"body"`
}

ArrayComprehension represents an array comprehension as defined in the language.

func (*ArrayComprehension) Compare added in v0.5.0

func (ac *ArrayComprehension) Compare(other Value) int

Compare compares ac to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (*ArrayComprehension) Copy added in v0.2.2

Copy returns a deep copy of ac.

func (*ArrayComprehension) Equal

func (ac *ArrayComprehension) Equal(other Value) bool

Equal returns true if ac is equal to other.

func (*ArrayComprehension) Find added in v0.4.5

func (ac *ArrayComprehension) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (*ArrayComprehension) Hash

func (ac *ArrayComprehension) Hash() int

Hash returns the hash code of the Value.

func (*ArrayComprehension) IsGround

func (ac *ArrayComprehension) IsGround() bool

IsGround returns true if the Term and Body are ground.

func (*ArrayComprehension) String

func (ac *ArrayComprehension) String() string

type BeforeAfterVisitor added in v0.17.0

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 added in v0.17.0

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.

func (*BeforeAfterVisitor) Walk added in v0.17.0

func (vis *BeforeAfterVisitor) Walk(x interface{})

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 added in v0.7.0

type BeforeAndAfterVisitor interface {
	Visitor
	Before(x interface{})
	After(x interface{})
}

BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before and after the AST has been visited. This is deprecated.

type Body

type Body []*Expr

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 NewBody added in v0.2.0

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 (*Body) Append added in v0.4.1

func (body *Body) Append(expr *Expr)

Append adds the expr to the body and updates the expr's index accordingly.

func (Body) Compare added in v0.2.0

func (body Body) Compare(other Body) int

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

func (body Body) Contains(x *Expr) bool

Contains returns true if this body contains the given expression.

func (Body) Copy added in v0.2.2

func (body Body) Copy() Body

Copy returns a deep copy of body.

func (Body) Equal

func (body Body) Equal(other Body) bool

Equal returns true if this Body is equal to the other Body.

func (Body) Hash

func (body Body) Hash() int

Hash returns the hash code for the Body.

func (Body) IsGround

func (body Body) IsGround() bool

IsGround returns true if all of the expressions in the Body are ground.

func (Body) Loc

func (body Body) Loc() *Location

Loc returns the location of the Body in the definition.

func (Body) MarshalJSON added in v0.9.0

func (body Body) MarshalJSON() ([]byte, error)

MarshalJSON returns JSON encoded bytes representing body.

func (Body) Set added in v0.6.0

func (body Body) Set(expr *Expr, pos int)

Set sets the expr in the body at the specified position and updates the expr's index accordingly.

func (Body) SetLoc added in v0.9.2

func (body Body) SetLoc(loc *Location)

SetLoc sets the location on body.

func (Body) String

func (body Body) String() 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 added in v0.5.0

func (bol Boolean) Compare(other Value) int

Compare compares bol to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (Boolean) Equal

func (bol Boolean) Equal(other Value) bool

Equal returns true if the other Value is a Boolean and is equal.

func (Boolean) Find added in v0.4.5

func (bol Boolean) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (Boolean) Hash

func (bol Boolean) Hash() int

Hash returns the hash code for the Value.

func (Boolean) IsGround

func (Boolean) IsGround() bool

IsGround always returns true.

func (Boolean) String

func (bol Boolean) String() string

type Builtin

type Builtin struct {
	Name     string          `json:"name"`               // Unique name of built-in function, e.g., <name>(arg1,arg2,...,argN)
	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.
}

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

func (*Builtin) Call added in v0.7.0

func (b *Builtin) Call(operands ...*Term) *Term

Call creates a new term for the built-in with the given operands.

func (*Builtin) Expr

func (b *Builtin) Expr(operands ...*Term) *Expr

Expr creates a new expression for the built-in with the given operands.

func (*Builtin) IsTargetPos

func (b *Builtin) IsTargetPos(i int) bool

IsTargetPos returns true if a variable in the i-th position will be bound by evaluating the call expression.

func (*Builtin) Ref added in v0.5.9

func (b *Builtin) Ref() Ref

Ref returns a Ref that refers to the built-in function.

type Call added in v0.7.0

type Call []*Term

Call represents as function call in the language.

func (Call) Compare added in v0.7.0

func (c Call) Compare(other Value) int

Compare compares c to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (Call) Copy added in v0.7.0

func (c Call) Copy() Call

Copy returns a deep copy of c.

func (Call) Find added in v0.7.0

func (c Call) Find(Ref) (Value, error)

Find returns the current value or a not found error.

func (Call) Hash added in v0.7.0

func (c Call) Hash() int

Hash returns the hash code for the Value.

func (Call) IsGround added in v0.7.0

func (c Call) IsGround() bool

IsGround returns true if the Value is ground.

func (Call) MakeExpr added in v0.7.0

func (c Call) MakeExpr(output *Term) *Expr

MakeExpr returns an ew Expr from this call.

func (Call) String added in v0.7.0

func (c Call) String() string

type Capabilities added in v0.23.0

type Capabilities struct {
	// builtins is a set of built-in functions that are supported.
	Builtins        []*Builtin       `json:"builtins"`
	WasmABIVersions []WasmABIVersion `json:"wasm_abi_versions"`

	// 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 capablilities or features supported by a particular version of OPA.

func CapabilitiesForThisVersion added in v0.23.0

func CapabilitiesForThisVersion() *Capabilities

CapabilitiesForThisVersion returns the capabilities of this version of OPA.

func LoadCapabilitiesJSON added in v0.23.0

func LoadCapabilitiesJSON(r io.Reader) (*Capabilities, error)

LoadCapabilitiesJSON loads a JSON serialized capabilities structure from the reader r.

type Comment added in v0.4.0

type Comment struct {
	Text     []byte
	Location *Location
}

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

func NewComment added in v0.4.0

func NewComment(text []byte) *Comment

NewComment returns a new Comment object.

func (*Comment) Copy added in v0.20.5

func (c *Comment) Copy() *Comment

Copy returns a deep copy of c.

func (*Comment) Equal added in v0.10.3

func (c *Comment) Equal(other *Comment) bool

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 added in v0.4.0

func (c *Comment) Loc() *Location

Loc returns the location of the comment in the definition.

func (*Comment) SetLoc added in v0.9.2

func (c *Comment) SetLoc(loc *Location)

SetLoc sets the location on c.

func (*Comment) String added in v0.4.0

func (c *Comment) String() string

type Compiler

type Compiler struct {

	// Errors contains errors that occurred during the compilation process.
	// If there are one or more errors, the compilation process is considered
	// "failed".
	Errors Errors

	// Modules contains the compiled modules. The compiled modules are the
	// output of the compilation process. If the compilation process failed,
	// there is no guarantee about the state of the modules.
	Modules map[string]*Module

	// ModuleTree organizes the modules into a tree where each node is keyed by
	// an element in the module's package path. E.g., given modules containing
	// the following package directives: "a", "a.b", "a.c", and "a.b", the
	// resulting module tree would be:
	//
	//  root
	//    |
	//    +--- data (no modules)
	//           |
	//           +--- a (1 module)
	//                |
	//                +--- b (2 modules)
	//                |
	//                +--- c (1 module)
	//
	ModuleTree *ModuleTreeNode

	// RuleTree organizes rules into a tree where each node is keyed by an
	// element in the rule's path. The rule path is the concatenation of the
	// containing package and the stringified rule name. E.g., given the
	// following module:
	//
	//  package ex
	//  p[1] { true }
	//  p[2] { true }
	//  q = true
	//
	//  root
	//    |
	//    +--- data (no rules)
	//           |
	//           +--- ex (no rules)
	//                |
	//                +--- p (2 rules)
	//                |
	//                +--- q (1 rule)
	RuleTree *TreeNode

	// 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
	// contains filtered or unexported fields
}

Compiler contains the state of a compilation process.

func CompileModules added in v0.10.2

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 MustCompileModules added in v0.10.2

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 NewCompiler

func NewCompiler() *Compiler

NewCompiler returns a new empty compiler.

func (*Compiler) Compile

func (c *Compiler) Compile(modules map[string]*Module)

Compile runs the compilation process on the input modules. The compiled version of the modules and associated data structures are stored on the compiler. If the compilation process fails for any reason, the compiler will contain a slice of errors.

Example
package main

import (
	"fmt"

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

func main() {

	// Define an input module that will be compiled.
	exampleModule := `package opa.example

import data.foo
import input.bar

p[x] { foo[x]; not bar[x]; x >= min_x }
min_x = 100 { true }`

	// Parse the input module to obtain the AST representation.
	mod, err := ast.ParseModule("my_module", exampleModule)
	if err != nil {
		fmt.Println("Parse error:", err)
	}

	// Create a new compiler instance and compile the module.
	c := ast.NewCompiler()

	mods := map[string]*ast.Module{
		"my_module": mod,
	}

	if c.Compile(mods); c.Failed() {
		fmt.Println("Compile error:", c.Errors)
	}

	fmt.Println("Expr 1:", c.Modules["my_module"].Rules[0].Body[0])
	fmt.Println("Expr 2:", c.Modules["my_module"].Rules[0].Body[1])
	fmt.Println("Expr 3:", c.Modules["my_module"].Rules[0].Body[2])
	fmt.Println("Expr 4:", c.Modules["my_module"].Rules[0].Body[3])

}
Output:


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 added in v0.20.0

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

func (c *Compiler) Failed() bool

Failed returns true if a compilation error has been encountered.

func (*Compiler) GetArity added in v0.7.0

func (c *Compiler) GetArity(ref Ref) int

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 added in v0.4.0

func (c *Compiler) GetRules(ref Ref) (rules []*Rule)

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 added in v0.14.0

func (c *Compiler) GetRulesDynamic(ref Ref) (rules []*Rule)

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

GetRulesDynamic("data.a[x].c[y]") => [rule1, rule2]
GetRulesDynamic("data.a[x].c.r2") => [rule2]
GetRulesDynamic("data.a.b[x][y]") => [rule1]

func (*Compiler) GetRulesExact added in v0.2.0

func (c *Compiler) GetRulesExact(ref Ref) (rules []*Rule)

GetRulesExact returns a slice of rules referred to by the reference.

E.g., given the following module:

	package a.b.c

	p[k] = v { ... }    # rule1
 p[k1] = v1 { ... }  # rule2

The following calls yield the rules on the right.

GetRulesExact("data.a.b.c.p")   => [rule1, rule2]
GetRulesExact("data.a.b.c.p.x") => nil
GetRulesExact("data.a.b.c")     => nil

func (*Compiler) GetRulesForVirtualDocument added in v0.2.0

func (c *Compiler) GetRulesForVirtualDocument(ref Ref) (rules []*Rule)

GetRulesForVirtualDocument returns a slice of rules that produce the virtual document referred to by the reference.

E.g., given the following module:

	package a.b.c

	p[k] = v { ... }    # rule1
 p[k1] = v1 { ... }  # rule2

The following calls yield the rules on the right.

GetRulesForVirtualDocument("data.a.b.c.p")   => [rule1, rule2]
GetRulesForVirtualDocument("data.a.b.c.p.x") => [rule1, rule2]
GetRulesForVirtualDocument("data.a.b.c")     => nil

func (*Compiler) GetRulesWithPrefix added in v0.2.0

func (c *Compiler) GetRulesWithPrefix(ref Ref) (rules []*Rule)

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) PassesTypeCheck added in v0.26.0

func (c *Compiler) PassesTypeCheck(body Body) bool

PassesTypeCheck determines whether the given body passes type checking

func (*Compiler) QueryCompiler added in v0.2.2

func (c *Compiler) QueryCompiler() QueryCompiler

QueryCompiler returns a new QueryCompiler object.

func (*Compiler) RuleIndex added in v0.4.9

func (c *Compiler) RuleIndex(path Ref) 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 added in v0.5.3

func (c *Compiler) SetErrorLimit(limit int) *Compiler

SetErrorLimit sets the number of errors the compiler can encounter before it quits. Zero or a negative number indicates no limit.

func (*Compiler) WithBuiltins added in v0.14.0

func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler

WithBuiltins is deprecated. Use WithCapabilities instead.

func (*Compiler) WithCapabilities added in v0.23.0

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 added in v0.27.0

func (c *Compiler) WithDebug(sink io.Writer) *Compiler

WithDebug sets where debug messages are written to. Passing `nil` has no effect.

func (*Compiler) WithMetrics added in v0.11.0

func (c *Compiler) WithMetrics(metrics metrics.Metrics) *Compiler

WithMetrics will set a metrics.Metrics and be used for profiling the Compiler instance.

func (*Compiler) WithModuleLoader added in v0.3.0

func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler

WithModuleLoader sets f as the ModuleLoader on the compiler.

The compiler will invoke the ModuleLoader after resolving all references in the current set of input modules. The ModuleLoader can return a new collection of parsed modules that are to be included in the compilation process. This process will repeat until the ModuleLoader returns an empty collection or an error. If an error is returned, compilation will stop immediately.

func (*Compiler) WithPathConflictsCheck added in v0.10.4

func (c *Compiler) WithPathConflictsCheck(fn func([]string) (bool, error)) *Compiler

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) WithSchemas added in v0.27.0

func (c *Compiler) WithSchemas(schemas *SchemaSet) *Compiler

WithSchemas sets a schemaSet to the compiler

func (*Compiler) WithStageAfter added in v0.10.6

func (c *Compiler) WithStageAfter(after string, stage CompilerStageDefinition) *Compiler

WithStageAfter registers a stage to run during compilation after the named stage.

func (*Compiler) WithUnsafeBuiltins added in v0.13.0

func (c *Compiler) WithUnsafeBuiltins(unsafeBuiltins map[string]struct{}) *Compiler

WithUnsafeBuiltins is deprecated. Use WithCapabilities instead.

type CompilerStage added in v0.10.6

type CompilerStage func(*Compiler) *Error

CompilerStage defines the interface for stages in the compiler.

type CompilerStageDefinition added in v0.11.0

type CompilerStageDefinition struct {
	Name       string
	MetricName string
	Stage      CompilerStage
}

CompilerStageDefinition defines a compiler stage

type ComprehensionIndex added in v0.20.0

type ComprehensionIndex struct {
	Term *Term
	Keys []*Term
}

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 added in v0.20.0

func (ci *ComprehensionIndex) String() string

type DocKind

type DocKind int

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

type Error added in v0.2.0

type Error struct {
	Code     string       `json:"code"`
	Message  string       `json:"message"`
	Location *Location    `json:"location,omitempty"`
	Details  ErrorDetails `json:"details,omitempty"`
}

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

func NewError added in v0.2.0

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

NewError returns a new Error object.

func (*Error) Error added in v0.2.0

func (e *Error) Error() string

type ErrorDetails added in v0.4.9

type ErrorDetails interface {
	Lines() []string
}

ErrorDetails defines the interface for detailed error messages.

type Errors added in v0.2.0

type Errors []*Error

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

func CheckPathConflicts added in v0.10.4

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.

func (Errors) Error added in v0.2.0

func (e Errors) Error() string

func (Errors) Sort added in v0.14.0

func (e Errors) Sort()

Sort sorts the error slice by location. If the locations are equal then the error message is compared.

type Expr

type Expr struct {
	With      []*With     `json:"with,omitempty"`
	Terms     interface{} `json:"terms"`
	Location  *Location   `json:"-"`
	Index     int         `json:"index"`
	Generated bool        `json:"generated,omitempty"`
	Negated   bool        `json:"negated,omitempty"`
}

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

func MustParseExpr added in v0.2.0

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 added in v0.2.1

func NewExpr(terms interface{}) *Expr

NewExpr returns a new Expr object.

func ParseExpr added in v0.2.0

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

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

func (*Expr) Compare added in v0.2.0

func (expr *Expr) Compare(other *Expr) int

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

func (expr *Expr) Complement() *Expr

Complement returns a copy of this expression with the negation flag flipped.

func (*Expr) Copy added in v0.2.2

func (expr *Expr) Copy() *Expr

Copy returns a deep copy of expr.

func (*Expr) Equal

func (expr *Expr) Equal(other *Expr) bool

Equal returns true if this Expr equals the other Expr.

func (*Expr) Hash

func (expr *Expr) Hash() int

Hash returns the hash code of the Expr.

func (*Expr) IncludeWith added in v0.4.1

func (expr *Expr) IncludeWith(target *Term, value *Term) *Expr

IncludeWith returns a copy of expr with the with modifier appended.

func (*Expr) IsAssignment added in v0.7.0

func (expr *Expr) IsAssignment() bool

IsAssignment returns true if this an assignment expression.

func (*Expr) IsCall added in v0.5.9

func (expr *Expr) IsCall() bool

IsCall returns true if this expression calls a function.

func (*Expr) IsEquality

func (expr *Expr) IsEquality() bool

IsEquality returns true if this is an equality expression.

func (*Expr) IsGround

func (expr *Expr) IsGround() bool

IsGround returns true if all of the expression terms are ground.

func (*Expr) Loc added in v0.9.2

func (expr *Expr) Loc() *Location

Loc returns the Location of expr.

func (*Expr) NoWith added in v0.4.1

func (expr *Expr) NoWith() *Expr

NoWith returns a copy of expr where the with modifier has been removed.

func (*Expr) Operand added in v0.4.9

func (expr *Expr) Operand(pos int) *Term

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 added in v0.4.9

func (expr *Expr) Operands() []*Term

Operands returns the built-in function operands.

func (*Expr) Operator added in v0.5.9

func (expr *Expr) Operator() Ref

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) SetLoc added in v0.9.2

func (expr *Expr) SetLoc(loc *Location)

SetLoc sets the location on expr.

func (*Expr) SetLocation added in v0.5.6

func (expr *Expr) SetLocation(loc *Location) *Expr

SetLocation sets the expr's location and returns the expr itself.

func (*Expr) SetOperator added in v0.7.0

func (expr *Expr) SetOperator(term *Term) *Expr

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 *Expr) String() string

func (*Expr) UnmarshalJSON

func (expr *Expr) UnmarshalJSON(bs []byte) error

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 GenericTransformer added in v0.2.0

type GenericTransformer struct {
	// contains filtered or unexported fields
}

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

func NewGenericTransformer added in v0.5.11

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

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

func (*GenericTransformer) Transform added in v0.2.0

func (t *GenericTransformer) Transform(x interface{}) (interface{}, error)

Transform calls the function f on the GenericTransformer.

type GenericVisitor

type GenericVisitor struct {
	// contains filtered or unexported fields
}

GenericVisitor 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 added in v0.4.1

func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor

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

func (*GenericVisitor) Walk added in v0.17.0

func (vis *GenericVisitor) Walk(x interface{})

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 added in v0.5.0

type Graph struct {
	// contains filtered or unexported fields
}

Graph represents the graph of dependencies between rules.

func NewGraph added in v0.5.0

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.

func (*Graph) Dependencies added in v0.5.0

func (g *Graph) Dependencies(x util.T) map[util.T]struct{}

Dependencies returns the set of rules that x depends on.

func (*Graph) Dependents added in v0.20.0

func (g *Graph) Dependents(x util.T) map[util.T]struct{}

Dependents returns the set of rules that depend on x.

func (*Graph) Sort added in v0.5.0

func (g *Graph) Sort() (sorted []util.T, ok bool)

Sort returns a slice of rules sorted by dependencies. If a cycle is found, ok is set to false.

type GraphTraversal added in v0.12.0

type GraphTraversal struct {
	// contains filtered or unexported fields
}

GraphTraversal is a Traversal that understands the dependency graph

func NewGraphTraversal added in v0.12.0

func NewGraphTraversal(graph *Graph) *GraphTraversal

NewGraphTraversal returns a Traversal for the dependency graph

func (*GraphTraversal) Edges added in v0.12.0

func (g *GraphTraversal) Edges(x util.T) []util.T

Edges lists all dependency connections for a given node

func (*GraphTraversal) Visited added in v0.12.0

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 struct {
	Location *Location `json:"-"`
	Name     Var       `json:"name"`
	Args     Args      `json:"args,omitempty"`
	Key      *Term     `json:"key,omitempty"`
	Value    *Term     `json:"value,omitempty"`
	Assign   bool      `json:"assign,omitempty"`
}

Head represents the head of a rule.

func NewHead added in v0.4.1

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 (*Head) Compare added in v0.4.1

func (head *Head) Compare(other *Head) int

Compare returns an integer indicating whether head is less than, equal to, or greater than other.

func (*Head) Copy added in v0.4.1

func (head *Head) Copy() *Head

Copy returns a deep copy of head.

func (*Head) DocKind added in v0.4.1

func (head *Head) DocKind() DocKind

DocKind returns the type of document produced by this rule.

func (*Head) Equal added in v0.4.1

func (head *Head) Equal(other *Head) bool

Equal returns true if this head equals other.

func (*Head) Loc added in v0.9.2

func (head *Head) Loc() *Location

Loc returns the Location of head.

func (*Head) SetLoc added in v0.9.2

func (head *Head) SetLoc(loc *Location)

SetLoc sets the location on head.

func (*Head) String added in v0.2.0

func (head *Head) String() string

func (*Head) Vars added in v0.4.1

func (head *Head) Vars() VarSet

Vars returns a set of vars found in the head.

type Import

type Import struct {
	Location *Location `json:"-"`
	Path     *Term     `json:"path"`
	Alias    Var       `json:"alias,omitempty"`
}

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

func MustParseImports added in v0.2.2

func MustParseImports(input string) []*Import

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

func ParseImports added in v0.2.2

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

ParseImports returns a slice of Import objects.

func (*Import) Compare added in v0.2.0

func (imp *Import) Compare(other *Import) int

Compare returns an integer indicating whether imp is less than, equal to, or greater than other.

func (*Import) Copy added in v0.2.2

func (imp *Import) Copy() *Import

Copy returns a deep copy of imp.

func (*Import) Equal

func (imp *Import) Equal(other *Import) bool

Equal returns true if imp is equal to other.

func (*Import) Loc

func (imp *Import) Loc() *Location

Loc returns the location of the Import in the definition.

func (*Import) Name added in v0.2.2

func (imp *Import) Name() Var

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 added in v0.9.2

func (imp *Import) SetLoc(loc *Location)

SetLoc sets the location on imp.

func (*Import) String

func (imp *Import) String() string

type IndexResult added in v0.4.10

type IndexResult struct {
	Kind    DocKind
	Rules   []*Rule
	Else    map[*Rule][]*Rule
	Default *Rule
}

IndexResult contains the result of an index lookup.

func NewIndexResult added in v0.4.10

func NewIndexResult(kind DocKind) *IndexResult

NewIndexResult returns a new IndexResult object.

func (*IndexResult) Empty added in v0.4.10

func (ir *IndexResult) Empty() bool

Empty returns true if there are no rules to evaluate.

type JSONOpt added in v0.27.1

type JSONOpt struct {
	SortSets bool // sort sets before serializing (this makes conversion more expensive)
}

JSONOpt defines parameters for AST to JSON conversion.

type Location

type Location = location.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 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"`
}

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 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 added in v0.28.0

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 added in v0.2.0

func (mod *Module) Compare(other *Module) int

Compare returns an integer indicating whether mod is less than, equal to, or greater than other.

func (*Module) Copy added in v0.2.2

func (mod *Module) Copy() *Module

Copy returns a deep copy of mod.

func (*Module) Equal

func (mod *Module) Equal(other *Module) bool

Equal returns true if mod equals other.

func (*Module) RuleSet added in v0.4.9

func (mod *Module) RuleSet(name Var) RuleSet

RuleSet returns a RuleSet containing named rules in the mod.

func (*Module) String added in v0.2.0

func (mod *Module) String() string

func (*Module) UnmarshalJSON added in v0.15.1

func (mod *Module) UnmarshalJSON(bs []byte) error

UnmarshalJSON parses bs and stores the result in mod. The rules in the module will have their module pointer set to mod.

type ModuleLoader added in v0.3.0

type ModuleLoader func(resolved map[string]*Module) (parsed map[string]*Module, err error)

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

type ModuleTreeNode

type ModuleTreeNode struct {
	Key      Value
	Modules  []*Module
	Children map[Value]*ModuleTreeNode
	Hide     bool
}

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

func NewModuleTree

func NewModuleTree(mods map[string]*Module) *ModuleTreeNode

NewModuleTree returns a new ModuleTreeNode that represents the root of the module tree populated with the given modules.

func (*ModuleTreeNode) DepthFirst added in v0.2.2

func (n *ModuleTreeNode) DepthFirst(f func(node *ModuleTreeNode) bool)

DepthFirst performs a depth-first traversal of the module tree rooted at n. If f returns true, traversal will not continue to the children of n.

func (*ModuleTreeNode) Size

func (n *ModuleTreeNode) Size() int

Size returns the number of modules in the tree.

type Node added in v0.9.2

type Node interface {
	fmt.Stringer
	Loc() *Location
	SetLoc(*Location)
}

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 added in v0.5.0

func (null Null) Compare(other Value) int

Compare compares null to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (Null) Equal

func (null Null) Equal(other Value) bool

Equal returns true if the other term Value is also Null.

func (Null) Find added in v0.4.5

func (null Null) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (Null) Hash

func (null Null) Hash() int

Hash returns the hash code for the Value.

func (Null) IsGround

func (Null) IsGround() bool

IsGround always returns true.

func (Null) String

func (null Null) String() string

type Number

type Number json.Number

Number represents a numeric value as defined by JSON.

func (Number) Compare added in v0.5.0

func (num Number) Compare(other Value) int

Compare compares num to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (Number) Equal

func (num Number) Equal(other Value) bool

Equal returns true if the other Value is a Number and is equal.

func (Number) Find added in v0.4.5

func (num Number) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (Number) Float64 added in v0.8.2

func (num Number) Float64() (float64, bool)

Float64 returns the float64 representation of num if possible.

func (Number) Hash

func (num Number) Hash() int

Hash returns the hash code for the Value.

func (Number) Int added in v0.3.0

func (num Number) Int() (int, bool)

Int returns the int representation of num if possible.

func (Number) Int64 added in v0.15.0

func (num Number) Int64() (int64, bool)

Int64 returns the int64 representation of num if possible.

func (Number) IsGround

func (Number) IsGround() bool

IsGround always returns true.

func (Number) MarshalJSON added in v0.3.0

func (num Number) MarshalJSON() ([]byte, error)

MarshalJSON returns JSON encoded bytes representing num.

func (Number) String

func (num Number) String() 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
	Elem(i int) (*Term, *Term)
	// contains filtered or unexported methods
}

Object represents an object as defined by the language.

func NewObject added in v0.6.0

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

NewObject creates a new Object with t.

type ObjectComprehension added in v0.5.2

type ObjectComprehension struct {
	Key   *Term `json:"key"`
	Value *Term `json:"value"`
	Body  Body  `json:"body"`
}

ObjectComprehension represents an object comprehension as defined in the language.

func (*ObjectComprehension) Compare added in v0.5.2

func (oc *ObjectComprehension) Compare(other Value) int

Compare compares oc to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (*ObjectComprehension) Copy added in v0.5.2

Copy returns a deep copy of oc.

func (*ObjectComprehension) Equal added in v0.5.2

func (oc *ObjectComprehension) Equal(other Value) bool

Equal returns true if oc is equal to other.

func (*ObjectComprehension) Find added in v0.5.2

func (oc *ObjectComprehension) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (*ObjectComprehension) Hash added in v0.5.2

func (oc *ObjectComprehension) Hash() int

Hash returns the hash code of the Value.

func (*ObjectComprehension) IsGround added in v0.5.2

func (oc *ObjectComprehension) IsGround() bool

IsGround returns true if the Key, Value and Body are ground.

func (*ObjectComprehension) String added in v0.5.2

func (oc *ObjectComprehension) String() string

type Package

type Package struct {
	Location *Location `json:"-"`
	Path     Ref       `json:"path"`
}

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

func MustParsePackage added in v0.2.2

func MustParsePackage(input string) *Package

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

func ParsePackage added in v0.2.2

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

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

func (*Package) Compare added in v0.2.0

func (pkg *Package) Compare(other *Package) int

Compare returns an integer indicating whether pkg is less than, equal to, or greater than other.

func (*Package) Copy added in v0.2.2

func (pkg *Package) Copy() *Package

Copy returns a deep copy of pkg.

func (*Package) Equal

func (pkg *Package) Equal(other *Package) bool

Equal returns true if pkg is equal to other.

func (*Package) Loc

func (pkg *Package) Loc() *Location

Loc returns the location of the Package in the definition.

func (*Package) SetLoc added in v0.9.2

func (pkg *Package) SetLoc(loc *Location)

SetLoc sets the location on pkg.

func (*Package) String

func (pkg *Package) String() string

type Parser added in v0.19.0

type Parser struct {
	// contains filtered or unexported fields
}

Parser is used to parse Rego statements.

func NewParser added in v0.19.0

func NewParser() *Parser

NewParser creates and initializes a Parser.

func (*Parser) Parse added in v0.19.0

func (p *Parser) Parse() ([]Statement, []*Comment, Errors)

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) WithFilename added in v0.19.0

func (p *Parser) WithFilename(filename string) *Parser

WithFilename provides the filename for Location details on parsed statements.

func (*Parser) WithProcessAnnotation added in v0.28.0

func (p *Parser) WithProcessAnnotation(processAnnotation bool) *Parser

WithProcessAnnotation enables or disables the processing of annotations by the Parser

func (*Parser) WithReader added in v0.19.0

func (p *Parser) WithReader(r io.Reader) *Parser

WithReader provides the io.Reader that the parser will use as its source.

type ParserErrorDetail added in v0.15.0

type ParserErrorDetail struct {
	Line string `json:"line"`
	Idx  int    `json:"idx"`
}

ParserErrorDetail holds additional details for parser errors.

func (ParserErrorDetail) Lines added in v0.15.0

func (d ParserErrorDetail) Lines() []string

Lines returns the pretty formatted line output for the error details.

type ParserOptions added in v0.28.0

type ParserOptions struct {
	ProcessAnnotation bool
}

ParserOptions defines the options for parsing Rego statements.

type QueryCompiler added in v0.2.2

type QueryCompiler interface {

	// Compile should be called to compile ad-hoc queries. The return value is
	// the compiled version of the query.
	Compile(q Body) (Body, error)

	// TypeEnv returns the type environment built after running type checking
	// on the query.
	TypeEnv() *TypeEnv

	// WithContext sets the QueryContext on the QueryCompiler. Subsequent calls
	// to Compile will take the QueryContext into account.
	WithContext(qctx *QueryContext) QueryCompiler

	// 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
}

QueryCompiler defines the interface for compiling ad-hoc queries.

type QueryCompilerStage added in v0.7.0

type QueryCompilerStage func(QueryCompiler, Body) (Body, error)

QueryCompilerStage defines the interface for stages in the query compiler.

type QueryCompilerStageDefinition added in v0.11.0

type QueryCompilerStageDefinition struct {
	Name       string
	MetricName string
	Stage      QueryCompilerStage
}

QueryCompilerStageDefinition defines a QueryCompiler stage

type QueryContext added in v0.2.2

type QueryContext struct {
	Package *Package
	Imports []*Import
}

QueryContext contains contextual information for running an ad-hoc query.

Ad-hoc queries can be run in the context of a package and imports may be included to provide concise access to data.

func NewQueryContext added in v0.2.2

func NewQueryContext() *QueryContext

NewQueryContext returns a new QueryContext object.

func (*QueryContext) Copy added in v0.2.2

func (qc *QueryContext) Copy() *QueryContext

Copy returns a deep copy of qc.

func (*QueryContext) WithImports added in v0.4.0

func (qc *QueryContext) WithImports(imports []*Import) *QueryContext

WithImports sets the imports on qc.

func (*QueryContext) WithPackage added in v0.4.0

func (qc *QueryContext) WithPackage(pkg *Package) *QueryContext

WithPackage sets the pkg on qc.

type QueryIterator

type QueryIterator func(map[Var]Value, Value) error

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

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 added in v0.10.4

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.

func (Ref) Append added in v0.2.0

func (ref Ref) Append(term *Term) Ref

Append returns a copy of ref with the term appended to the end.

func (Ref) Compare added in v0.5.0

func (ref Ref) Compare(other Value) int

Compare compares ref to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (Ref) Concat added in v0.9.0

func (ref Ref) Concat(terms []*Term) Ref

Concat returns a ref with the terms appended.

func (Ref) ConstantPrefix added in v0.5.3

func (ref Ref) ConstantPrefix() Ref

ConstantPrefix returns the constant portion of the ref starting from the head.

func (Ref) Copy added in v0.2.2

func (ref Ref) Copy() Ref

Copy returns a deep copy of ref.

func (Ref) Dynamic added in v0.4.9

func (ref Ref) Dynamic() int

Dynamic returns the offset of the first non-constant operand of ref.

func (Ref) Equal

func (ref Ref) Equal(other Value) bool

Equal returns true if ref is equal to other.

func (Ref) Extend added in v0.3.0

func (ref Ref) Extend(other Ref) Ref

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 added in v0.4.5

func (ref Ref) Find(path Ref) (Value, error)

Find returns the current value or a "not found" error.

func (Ref) GroundPrefix added in v0.2.0

func (ref Ref) GroundPrefix() Ref

GroundPrefix returns the ground portion of the ref starting from the head. By definition, the head of the reference is always ground.

func (Ref) HasPrefix added in v0.2.0

func (ref Ref) HasPrefix(other Ref) bool

HasPrefix returns true if the other ref is a prefix of this ref.

func (Ref) Hash

func (ref Ref) Hash() int

Hash returns the hash code for the Value.

func (Ref) Insert added in v0.6.0

func (ref Ref) Insert(x *Term, pos int) Ref

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

func (ref Ref) IsGround() bool

IsGround returns true if all of the parts of the Ref are ground.

func (Ref) IsNested

func (ref Ref) IsNested() bool

IsNested returns true if this ref contains other Refs.

func (Ref) OutputVars

func (ref Ref) OutputVars() VarSet

OutputVars returns a VarSet containing variables that would be bound by evaluating

this expression in isolation.

func (Ref) Ptr added in v0.10.4

func (ref Ref) Ptr() (string, error)

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 Ref) String() string

type RefErrInvalidDetail added in v0.5.2

type RefErrInvalidDetail struct {
	Ref   Ref        `json:"ref"`            // invalid ref
	Pos   int        `json:"pos"`            // invalid element
	Have  types.Type `json:"have,omitempty"` // type of invalid element (for var/ref elements)
	Want  types.Type `json:"want"`           // allowed type (for non-object values)
	OneOf []Value    `json:"oneOf"`          // allowed values (e.g., for object keys)
}

RefErrInvalidDetail describes an undefined reference error where the referenced value does not support the reference operand (e.g., missing object key, invalid key type, etc.)

func (*RefErrInvalidDetail) Lines added in v0.5.2

func (r *RefErrInvalidDetail) Lines() []string

Lines returns the string representation of the detail.

type RefErrUnsupportedDetail added in v0.5.2

type RefErrUnsupportedDetail struct {
	Ref  Ref        `json:"ref"`  // invalid ref
	Pos  int        `json:"pos"`  // invalid element
	Have types.Type `json:"have"` // referenced type
}

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

func (*RefErrUnsupportedDetail) Lines added in v0.5.2

func (r *RefErrUnsupportedDetail) Lines() []string

Lines returns the string representation of the detail.

type Resolver added in v0.4.9

type Resolver interface {
	Resolve(ref Ref) (interface{}, error)
}

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

type Rule

type Rule struct {
	Location *Location `json:"-"`
	Default  bool      `json:"default,omitempty"`
	Head     *Head     `json:"head"`
	Body     Body      `json:"body"`
	Else     *Rule     `json:"else,omitempty"`

	// Module is a pointer to the module containing this rule. If the rule
	// was NOT created while parsing/constructing a module, this should be
	// left unset. The pointer is not included in any standard operations
	// on the rule (e.g., printing, comparison, visiting, etc.)
	Module *Module `json:"-"`
}

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

func MustParseRule

func MustParseRule(input string) *Rule

MustParseRule returns a parsed rule. If an error occurs during parsing, panic.

func ParseCompleteDocRuleFromAssignmentExpr added in v0.14.0

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 added in v0.5.6

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 ParsePartialObjectDocRuleFromEqExpr added in v0.5.6

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 added in v0.5.6

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 added in v0.3.0

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 added in v0.7.0

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 added in v0.5.9

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 added in v0.5.6

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

ParseRuleFromExpr returns a rule if the expression can be interpreted as a rule definition.

func (*Rule) Compare added in v0.2.0

func (rule *Rule) Compare(other *Rule) int

Compare returns an integer indicating whether rule is less than, equal to, or greater than other.

func (*Rule) Copy added in v0.2.2

func (rule *Rule) Copy() *Rule

Copy returns a deep copy of rule.

func (*Rule) Equal

func (rule *Rule) Equal(other *Rule) bool

Equal returns true if rule is equal to other.

func (*Rule) Loc

func (rule *Rule) Loc() *Location

Loc returns the location of the Rule in the definition.

func (*Rule) Path added in v0.2.0

func (rule *Rule) Path() Ref

Path returns a ref referring to the document produced by this rule. If rule is not contained in a module, this function panics.

func (*Rule) SetLoc added in v0.9.2

func (rule *Rule) SetLoc(loc *Location)

SetLoc sets the location on rule.

func (*Rule) String

func (rule *Rule) String() string

type RuleIndex added in v0.4.9

type RuleIndex interface {

	// Build tries to construct an index for the given rules. If the index was
	// constructed, 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 RuleSet added in v0.4.9

type RuleSet []*Rule

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

func NewRuleSet added in v0.4.9

func NewRuleSet(rules ...*Rule) RuleSet

NewRuleSet returns a new RuleSet containing the given rules.

func (*RuleSet) Add added in v0.4.9

func (rs *RuleSet) Add(rule *Rule)

Add inserts the rule into rs.

func (RuleSet) Contains added in v0.4.9

func (rs RuleSet) Contains(rule *Rule) bool

Contains returns true if rs contains rule.

func (RuleSet) Diff added in v0.4.9

func (rs RuleSet) Diff(other RuleSet) RuleSet

Diff returns a new RuleSet containing rules in rs that are not in other.

func (RuleSet) Equal added in v0.4.9

func (rs RuleSet) Equal(other RuleSet) bool

Equal returns true if rs equals other.

func (RuleSet) Merge added in v0.4.9

func (rs RuleSet) Merge(other RuleSet) RuleSet

Merge returns a ruleset containing the union of rules from rs an other.

func (RuleSet) String added in v0.4.9

func (rs RuleSet) String() string

type SchemaAnnotation added in v0.28.0

type SchemaAnnotation struct {
	Path       Ref          `json:"path"`
	Schema     Ref          `json:"schema,omitempty"`
	Definition *interface{} `json:"definition,omitempty"`
}

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

func (*SchemaAnnotation) Compare added in v0.28.0

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 added in v0.28.0

Copy returns a deep copy of s.

func (*SchemaAnnotation) String added in v0.28.0

func (s *SchemaAnnotation) String() string

type SchemaSet added in v0.27.0

type SchemaSet struct {
	// contains filtered or unexported fields
}

SchemaSet holds a map from a path to a schema.

func NewSchemaSet added in v0.28.0

func NewSchemaSet() *SchemaSet

NewSchemaSet returns an empty SchemaSet.

func (*SchemaSet) Get added in v0.28.0

func (ss *SchemaSet) Get(path Ref) interface{}

Get returns the raw schema identified by the path.

func (*SchemaSet) Put added in v0.28.0

func (ss *SchemaSet) Put(path Ref, raw interface{})

Put inserts a raw schema into the set.

type Set added in v0.2.0

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 added in v0.6.0

func NewSet(t ...*Term) Set

NewSet returns a new Set containing t.

type SetComprehension added in v0.5.2

type SetComprehension struct {
	Term *Term `json:"term"`
	Body Body  `json:"body"`
}

SetComprehension represents a set comprehension as defined in the language.

func (*SetComprehension) Compare added in v0.5.2

func (sc *SetComprehension) Compare(other Value) int

Compare compares sc to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (*SetComprehension) Copy added in v0.5.2

func (sc *SetComprehension) Copy() *SetComprehension

Copy returns a deep copy of sc.

func (*SetComprehension) Equal added in v0.5.2

func (sc *SetComprehension) Equal(other Value) bool

Equal returns true if sc is equal to other.

func (*SetComprehension) Find added in v0.5.2

func (sc *SetComprehension) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (*SetComprehension) Hash added in v0.5.2

func (sc *SetComprehension) Hash() int

Hash returns the hash code of the Value.

func (*SetComprehension) IsGround added in v0.5.2

func (sc *SetComprehension) IsGround() bool

IsGround returns true if the Term and Body are ground.

func (*SetComprehension) String added in v0.5.2

func (sc *SetComprehension) String() string

type SomeDecl added in v0.11.0

type SomeDecl struct {
	Location *Location `json:"-"`
	Symbols  []*Term   `json:"symbols"`
}

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

func (*SomeDecl) Compare added in v0.11.0

func (d *SomeDecl) Compare(other *SomeDecl) int

Compare returns an integer indicating whether d is less than, equal to, or greater than other.

func (*SomeDecl) Copy added in v0.11.0

func (d *SomeDecl) Copy() *SomeDecl

Copy returns a deep copy of d.

func (*SomeDecl) Hash added in v0.11.0

func (d *SomeDecl) Hash() int

Hash returns a hash code of d.

func (*SomeDecl) Loc added in v0.11.0

func (d *SomeDecl) Loc() *Location

Loc returns the Location of d.

func (*SomeDecl) SetLoc added in v0.11.0

func (d *SomeDecl) SetLoc(loc *Location)

SetLoc sets the Location on d.

func (*SomeDecl) String added in v0.11.0

func (d *SomeDecl) String() string

type Statement

type Statement interface {
	Node
}

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

type String

type String string

String represents a string value as defined by JSON.

func (String) Compare added in v0.5.0

func (str String) Compare(other Value) int

Compare compares str to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (String) Equal

func (str String) Equal(other Value) bool

Equal returns true if the other Value is a String and is equal.

func (String) Find added in v0.4.5

func (str String) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (String) Hash

func (str String) Hash() int

Hash returns the hash code for the Value.

func (String) IsGround

func (String) IsGround() bool

IsGround always returns true.

func (String) String

func (str String) String() string

type Term

type Term struct {
	Value    Value     `json:"value"` // the value of the Term as represented in Go
	Location *Location `json:"-"`     // the location of the Term in the source
}

Term is an argument to a function.

func ArrayComprehensionTerm

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 added in v0.7.0

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 added in v0.3.0

func FloatNumberTerm(f float64) *Term

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

func IntNumberTerm added in v0.3.0

func IntNumberTerm(i int) *Term

IntNumberTerm creates a new Term with an integer Number value.

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 added in v0.2.1

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 added in v0.5.2

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 added in v0.5.2

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

SetComprehensionTerm creates a new Term with an SetComprehension value.

func SetTerm added in v0.2.0

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

SetTerm returns a new Term representing a set containing terms t.

func StringTerm

func StringTerm(s string) *Term

StringTerm creates a new Term with a String value.

func UIntNumberTerm added in v0.22.0

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.

func (*Term) Copy added in v0.2.2

func (term *Term) Copy() *Term

Copy returns a deep copy of term.

func (*Term) Equal

func (term *Term) Equal(other *Term) bool

Equal returns true if this term equals the other term. Equality is defined for each kind of term.

func (*Term) Get added in v0.7.0

func (term *Term) Get(name *Term) *Term

Get returns a value referred to by name from the term.

func (*Term) Hash

func (term *Term) Hash() int

Hash returns the hash code of the Term's value.

func (*Term) IsGround

func (term *Term) IsGround() bool

IsGround returns true if this term's Value is ground.

func (*Term) Loc added in v0.9.2

func (term *Term) Loc() *Location

Loc returns the Location of term.

func (*Term) MarshalJSON

func (term *Term) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of the term.

Specialized marshalling logic is required to include a type hint for Value.

func (*Term) SetLoc added in v0.9.2

func (term *Term) SetLoc(loc *Location)

SetLoc sets the location on term.

func (*Term) SetLocation added in v0.5.0

func (term *Term) SetLocation(loc *Location) *Term

SetLocation updates the term's Location and returns the term itself.

func (*Term) String

func (term *Term) String() string

func (*Term) UnmarshalJSON

func (term *Term) UnmarshalJSON(bs []byte) error

UnmarshalJSON parses the byte array and stores the result in term. Specialized unmarshalling is required to handle Value.

func (*Term) Vars

func (term *Term) Vars() VarSet

Vars returns a VarSet with variables contained in this term.

type Transformer added in v0.2.0

type Transformer interface {
	Transform(v interface{}) (interface{}, error)
}

Transformer defines the interface for transforming AST elements. If the transformer returns nil and does not indicate an error, the AST element will be set to nil and no transformations will be applied to children of the element.

type TreeNode added in v0.5.0

type TreeNode struct {
	Key      Value
	Values   []util.T
	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 added in v0.2.0

func NewRuleTree(mtree *ModuleTreeNode) *TreeNode

NewRuleTree returns a new TreeNode that represents the root of the rule tree populated with the given rules.

func (*TreeNode) Child added in v0.5.0

func (n *TreeNode) Child(k Value) *TreeNode

Child returns n's child with key k.

func (*TreeNode) DepthFirst added in v0.5.0

func (n *TreeNode) DepthFirst(f func(node *TreeNode) bool)

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) Size added in v0.5.0

func (n *TreeNode) Size() int

Size returns the number of rules in the tree.

type TypeEnv added in v0.4.9

type TypeEnv struct {
	// contains filtered or unexported fields
}

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

func (*TypeEnv) Get added in v0.4.9

func (env *TypeEnv) Get(x interface{}) types.Type

Get returns the type of x.

type UnificationErrDetail added in v0.4.9

type UnificationErrDetail struct {
	Left  types.Type `json:"a"`
	Right types.Type `json:"b"`
}

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

func (*UnificationErrDetail) Lines added in v0.4.9

func (a *UnificationErrDetail) Lines() []string

Lines returns the string representation of the detail.

type UnknownValueErr added in v0.9.0

type UnknownValueErr struct{}

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

func (UnknownValueErr) Error added in v0.9.0

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

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

InterfaceToValue converts a native Go value x to a Value.

func MustInterfaceToValue added in v0.4.5

func MustInterfaceToValue(x interface{}) Value

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

func ValueFromReader added in v0.14.0

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

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

type ValueMap added in v0.2.0

type ValueMap struct {
	// contains filtered or unexported fields
}

ValueMap represents a key/value map between AST term values. Any type of term can be used as a key in the map.

func NewValueMap added in v0.2.0

func NewValueMap() *ValueMap

NewValueMap returns a new ValueMap.

func (*ValueMap) Copy added in v0.2.0

func (vs *ValueMap) Copy() *ValueMap

Copy returns a shallow copy of the ValueMap.

func (*ValueMap) Delete added in v0.2.0

func (vs *ValueMap) Delete(k Value)

Delete removes a key k from the map.

func (*ValueMap) Equal added in v0.2.0

func (vs *ValueMap) Equal(other *ValueMap) bool

Equal returns true if this ValueMap equals the other.

func (*ValueMap) Get added in v0.2.0

func (vs *ValueMap) Get(k Value) Value

Get returns the value in the map for k.

func (*ValueMap) Hash added in v0.2.0

func (vs *ValueMap) Hash() int

Hash returns a hash code for this ValueMap.

func (*ValueMap) Iter added in v0.2.0

func (vs *ValueMap) Iter(iter func(Value, Value) bool) bool

Iter calls the iter function for each key/value pair in the map. If the iter function returns true, iteration stops.

func (*ValueMap) Len added in v0.2.0

func (vs *ValueMap) Len() int

Len returns the number of elements in the map.

func (*ValueMap) MarshalJSON added in v0.15.0

func (vs *ValueMap) MarshalJSON() ([]byte, error)

MarshalJSON provides a custom marshaller for the ValueMap which will include the key, value, and value type.

func (*ValueMap) Put added in v0.2.0

func (vs *ValueMap) Put(k, v Value)

Put inserts a key k into the map with value v.

func (*ValueMap) String added in v0.2.0

func (vs *ValueMap) String() string

type ValueResolver added in v0.4.9

type ValueResolver interface {
	Resolve(ref Ref) (Value, error)
}

ValueResolver defines the interface for resolving references to AST values.

type Var

type Var string

Var represents a variable as defined by the language.

func (Var) Compare added in v0.5.0

func (v Var) Compare(other Value) int

Compare compares v to other, return <0, 0, or >0 if it is less than, equal to, or greater than other.

func (Var) Equal

func (v Var) Equal(other Value) bool

Equal returns true if the other Value is a Variable and has the same value (name).

func (Var) Find added in v0.4.5

func (v Var) Find(path Ref) (Value, error)

Find returns the current value or a not found error.

func (Var) Hash

func (v Var) Hash() int

Hash returns the hash code for the Value.

func (Var) IsGenerated added in v0.5.11

func (v Var) IsGenerated() bool

IsGenerated returns true if this variable was generated during compilation.

func (Var) IsGround

func (Var) IsGround() bool

IsGround always returns false.

func (Var) IsWildcard added in v0.2.0

func (v Var) IsWildcard() bool

IsWildcard returns true if this is a wildcard variable.

func (Var) String

func (v Var) String() string

type VarSet

type VarSet map[Var]struct{}

VarSet represents a set of variables.

func NewVarSet

func NewVarSet(vs ...Var) VarSet

NewVarSet returns a new VarSet containing the specified variables.

func OutputVarsFromBody added in v0.20.0

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 added in v0.20.0

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.

func (VarSet) Add

func (s VarSet) Add(v Var)

Add updates the set to include the variable "v".

func (VarSet) Contains

func (s VarSet) Contains(v Var) bool

Contains returns true if the set contains the variable "v".

func (VarSet) Copy

func (s VarSet) Copy() VarSet

Copy returns a shallow copy of the VarSet.

func (VarSet) Diff

func (s VarSet) Diff(vs VarSet) VarSet

Diff returns a VarSet containing variables in s that are not in vs.

func (VarSet) Equal added in v0.2.1

func (s VarSet) Equal(vs VarSet) bool

Equal returns true if s contains exactly the same elements as vs.

func (VarSet) Intersect

func (s VarSet) Intersect(vs VarSet) VarSet

Intersect returns a VarSet containing variables in s that are in vs.

func (VarSet) Sorted added in v0.11.0

func (s VarSet) Sorted() []Var

Sorted returns a sorted slice of vars from s.

func (VarSet) String

func (s VarSet) String() string

func (VarSet) Update

func (s VarSet) Update(vs VarSet)

Update merges the other VarSet into this VarSet.

type VarVisitor added in v0.3.0

type VarVisitor struct {
	// contains filtered or unexported fields
}

VarVisitor walks AST nodes under a given node and collects all encountered variables. The collected variables can be controlled by specifying VarVisitorParams when creating the visitor.

func NewVarVisitor added in v0.3.0

func NewVarVisitor() *VarVisitor

NewVarVisitor returns a new VarVisitor object.

func (*VarVisitor) Vars added in v0.3.0

func (vis *VarVisitor) Vars() VarSet

Vars returns a VarSet that contains collected vars.

func (*VarVisitor) Walk added in v0.17.0

func (vis *VarVisitor) Walk(x interface{})

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 added in v0.3.0

func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor

WithParams sets the parameters in params on vis.

type VarVisitorParams added in v0.3.0

type VarVisitorParams struct {
	SkipRefHead     bool
	SkipRefCallHead bool
	SkipObjectKeys  bool
	SkipClosures    bool
	SkipWithTarget  bool
	SkipSets        bool
}

VarVisitorParams contains settings for a VarVisitor.

type Visitor

type Visitor interface {
	Visit(v interface{}) (w Visitor)
}

Visitor defines the interface for iterating AST elements. The Visit function can return a Visitor w which will be used to visit the children of the AST element v. If the Visit function returns nil, the children will not be visited. This is deprecated.

type WasmABIVersion added in v0.27.0

type WasmABIVersion struct {
	Version int `json:"version"`
	Minor   int `json:"minor_version"`
}

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

type With added in v0.4.1

type With struct {
	Location *Location `json:"-"`
	Target   *Term     `json:"target"`
	Value    *Term     `json:"value"`
}

With represents a modifier on an expression.

func (*With) Compare added in v0.4.1

func (w *With) Compare(other *With) int

Compare returns an integer indicating whether w is less than, equal to, or greater than other.

func (*With) Copy added in v0.4.1

func (w *With) Copy() *With

Copy returns a deep copy of w.

func (*With) Equal added in v0.4.1

func (w *With) Equal(other *With) bool

Equal returns true if this With is equals the other With.

func (With) Hash added in v0.4.1

func (w With) Hash() int

Hash returns the hash code of the With.

func (*With) Loc added in v0.9.2

func (w *With) Loc() *Location

Loc returns the Location of w.

func (*With) SetLoc added in v0.9.2

func (w *With) SetLoc(loc *Location)

SetLoc sets the location on w.

func (*With) SetLocation added in v0.7.0

func (w *With) SetLocation(loc *Location) *With

SetLocation sets the location on w.

func (*With) String added in v0.4.1

func (w *With) String() string

Directories

Path Synopsis
internal
Package location defines locations in Rego source code.
Package location defines locations in Rego source code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL