ast

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2016 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

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
)

Variables

View Source
var Abs = &Builtin{
	Name:      Var("abs"),
	NumArgs:   2,
	TargetPos: []int{1},
}

Abs returns the number without its sign.

View Source
var BuiltinMap map[Var]*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 Count = &Builtin{
	Name:      Var("count"),
	NumArgs:   2,
	TargetPos: []int{1},
}

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

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 Divide = &Builtin{
	Name:      Var("div"),
	NumArgs:   3,
	TargetPos: []int{2},
}

Divide divides the first number by the second number.

View Source
var Equality = &Builtin{
	Name:      Var("="),
	Alias:     Var("eq"),
	NumArgs:   2,
	TargetPos: []int{0, 1},
}

Equality represents the "=" operator.

View Source
var GreaterThan = &Builtin{
	Name:    Var(">"),
	Alias:   Var("gt"),
	NumArgs: 2,
}

GreaterThan represents the ">" comparison operator.

View Source
var GreaterThanEq = &Builtin{
	Name:    Var(">="),
	Alias:   Var("gte"),
	NumArgs: 2,
}

GreaterThanEq represents the ">=" comparison operator.

View Source
var Keywords = [...]string{
	"package", "import", "not",
}

Keywords is an array of reserved keywords in the language. These are reserved names that cannot be used for variables.

View Source
var LessThan = &Builtin{
	Name:    Var("<"),
	Alias:   Var("lt"),
	NumArgs: 2,
}

LessThan represents the "<" comparison operator.

View Source
var LessThanEq = &Builtin{
	Name:    Var("<="),
	Alias:   Var("lte"),
	NumArgs: 2,
}

LessThanEq represents the "<=" comparison operator.

View Source
var Max = &Builtin{
	Name:      Var("max"),
	NumArgs:   2,
	TargetPos: []int{1},
}

Max returns the maximum value in a collection.

View Source
var Minus = &Builtin{
	Name:      Var("minus"),
	NumArgs:   3,
	TargetPos: []int{2},
}

Minus subtracts the second number from the first number.

View Source
var Multiply = &Builtin{
	Name:      Var("mul"),
	NumArgs:   3,
	TargetPos: []int{2},
}

Multiply multiplies two numbers together.

View Source
var NotEqual = &Builtin{
	Name:    Var("!="),
	Alias:   Var("neq"),
	NumArgs: 2,
}

NotEqual represents the "!=" comparison operator.

View Source
var Plus = &Builtin{
	Name:      Var("plus"),
	NumArgs:   3,
	TargetPos: []int{2},
}

Plus adds two numbers together.

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

ReservedVars is the set of reserved variable names.

View Source
var Round = &Builtin{
	Name:      Var("round"),
	NumArgs:   2,
	TargetPos: []int{1},
}

Round rounds the number up to the nearest integer.

View Source
var Sum = &Builtin{
	Name:      Var("sum"),
	NumArgs:   2,
	TargetPos: []int{1},
}

Sum takes an array of numbers and sums them.

View Source
var ToNumber = &Builtin{
	Name:      Var("to_number"),
	NumArgs:   2,
	TargetPos: []int{1},
}

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

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.

Functions

func MustParseStatement

func MustParseStatement(input string) interface{}

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

func MustParseStatements

func MustParseStatements(input string) []interface{}

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

func Parse

func Parse(filename string, b []byte, opts ...Option) (interface{}, error)

Parse parses the data from b using filename as information in the error messages.

func ParseFile

func ParseFile(filename string, opts ...Option) (interface{}, error)

ParseFile parses the file identified by filename.

func ParseReader

func ParseReader(filename string, r io.Reader, opts ...Option) (interface{}, error)

ParseReader parses the data from r using filename as information in the error messages.

func ParseStatement

func ParseStatement(input string) (interface{}, error)

ParseStatement returns exactly one statement. A statement might be a term, expression, rule, etc. Regardless, this function expects *exactly* one statement. If multiple statements are parsed, an error is returned.

func ParseStatements

func ParseStatements(filename, input string) ([]interface{}, error)

ParseStatements returns a slice of parsed statements. This is the default return value from the parser.

func RegisterBuiltin

func RegisterBuiltin(b *Builtin)

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

func Walk

func Walk(v Visitor, x interface{})

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

func WalkClosures

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

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

func WalkRefs

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.

Types

type Array

type Array []*Term

Array represents an array as defined by the language. Arrays are similar to the same types as defined by JSON with the exception that they can contain Vars and References.

func (Array) Equal

func (arr Array) Equal(other Value) bool

Equal returns true if the other Value is an Array and the elements of the other Array are equal to the elements of this Array. The elements are ordered.

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

func (arr Array) Query(ref Ref, iter QueryIterator) error

Query invokes the iterator for each referenced value inside the array.

func (Array) String

func (arr Array) String() string

type ArrayComprehension

type ArrayComprehension struct {
	Term *Term
	Body Body
}

ArrayComprehension represents an array comprehension as defined in the language.

func (*ArrayComprehension) Equal

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

Equal returns true if this array comprehension is syntactically equal to another.

func (*ArrayComprehension) Hash

func (ac *ArrayComprehension) Hash() int

Hash returns the hash code of the Value.

func (*ArrayComprehension) IsGround

func (ac *ArrayComprehension) IsGround() bool

IsGround returns true if the Term and Body are ground.

func (*ArrayComprehension) String

func (ac *ArrayComprehension) String() string

type Body

type Body []*Expr

Body represents one or more expressios contained inside a rule.

func MustParseBody

func MustParseBody(input string) Body

MustParseBody returns a parsed body. If an error occurs during parsing, panic.

func ParseBody

func ParseBody(input string) (Body, error)

ParseBody returns exactly one body. If multiple bodies are parsed, an error is returned.

func (Body) Contains

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

Contains returns true if this body contains the given expression.

func (Body) Equal

func (body Body) Equal(other Body) bool

Equal returns true if this Body is equal to the other Body. Two bodies are equal if consist of equal, ordered expressions.

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

func (body Body) OutputVars(safe VarSet) VarSet

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

func (Body) String

func (body Body) String() string

func (Body) Vars

func (body Body) Vars(skipClosures bool) VarSet

Vars returns a VarSet containing all of the variables in the body. If skipClosures is true, variables contained inside closures within the body will be ignored.

type Boolean

type Boolean bool

Boolean represents a boolean value defined by JSON.

func (Boolean) Equal

func (bol Boolean) Equal(other Value) bool

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

func (Boolean) Hash

func (bol Boolean) Hash() int

Hash returns the hash code for the Value.

func (Boolean) IsGround

func (bol Boolean) IsGround() bool

IsGround always returns true.

func (Boolean) String

func (bol Boolean) String() string

type Builtin

type Builtin struct {
	Name      Var
	Alias     Var
	NumArgs   int
	TargetPos []int
}

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

func (*Builtin) Expr

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

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

func (*Builtin) GetPrintableName

func (b *Builtin) GetPrintableName() string

GetPrintableName returns a printable name for the builtin. Some built-ins have names that are used for infix operators but when printing we want to use something a bit more readable, e.g., "gte(a,b)" instead of ">=(a,b)".

func (*Builtin) IsTargetPos

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

IsTargetPos returns true if a variable in the i-th position will be bound when the expression is evaluated.

type Compiler

type Compiler struct {

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

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

	// Exports contains a mapping of package paths to variables. The variables
	// represent externally accessible symbols. For now the only type of
	// externally visible symbol is a rule. For example:
	//
	// package a.b.c
	//
	// import data.e.f
	//
	// p = true :- q[x] = 1         # "p" is an export
	// q[x] :- f.r[x], not f.m[x]   # "q" is an export
	//
	// In this case, the mapping would be:
	//
	// {
	//   a.b.c: [p, q]
	// }
	Exports *util.HashMap

	// Globals contains a mapping of modules to globally accessible variables
	// within each module. Each variable is mapped to the value which represents
	// the fully qualified name of the variable. For example:
	//
	// package a.b.c
	//
	// import data.e.f
	// import y as z
	//
	// p = true :- q[x] = 1
	// q[x] :- f.r[x], not f.m[x]
	//
	// In this case, the mapping would be
	//
	// {
	//  <modptr>: {q: data.a.b.c.q, f: data.e.f, p: data.a.b.c.p, z: y}
	// }
	Globals map[*Module]map[Var]Value

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

	// RuleGraph represents the rule dependencies.
	// An edge (u, v) is added to the graph if rule "u" depends on rule "v".
	// A rule depends on another rule if it refers to it.
	RuleGraph map[*Rule]map[*Rule]struct{}
	// contains filtered or unexported fields
}

Compiler contains the state of a compilation process.

func NewCompiler

func NewCompiler() *Compiler

NewCompiler returns a new empty compiler.

func (*Compiler) Compile

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

Compile runs the compilation process on the input modules. The output of the compilation process can be obtained from the Errors or Modules attributes of the Compiler.

func (*Compiler) Failed

func (c *Compiler) Failed() bool

Failed returns true if a compilation error has been encountered.

func (*Compiler) FlattenErrors

func (c *Compiler) FlattenErrors() string

FlattenErrors returns a single message that contains a flattened version of the compiler error messages. This must only be called when the compilation process has failed.

type DocKind

type DocKind int

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

type Expr

type Expr struct {
	Location *Location `json:"-"`
	Negated  bool      `json:",omitempty"`
	Terms    interface{}
}

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

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

func (expr *Expr) Complement() *Expr

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

func (*Expr) Equal

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

Equal returns true if this Expr equals the other Expr. Two expressions are considered equal if both expressions are negated (or not), are built-ins (or not), and have the same ordered terms.

func (*Expr) Hash

func (expr *Expr) Hash() int

Hash returns the hash code of the Expr.

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

func (expr *Expr) OutputVars(safe VarSet) VarSet

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

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(skipClosures bool) VarSet

Vars returns a VarSet containing all of the variables in the expression. If skipClosures is true then variables contained inside closures within this expression will not be included in the VarSet.

type GenericVisitor

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

GenericVisitor implements the Visitor interface to provide a utility to walk over AST nodes using a closure. If the closure returns true, the visitor will not walk over AST nodes under x.

func (*GenericVisitor) Visit

func (vis *GenericVisitor) Visit(x interface{}) Visitor

Visit calls the function f on the GenericVisitor.

type Import

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

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

func (*Import) Equal

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

Equal returns true if this Import has the same path and alias as the other Import.

func (*Import) Loc

func (imp *Import) Loc() *Location

Loc returns the location of the Import in the definition.

func (*Import) String

func (imp *Import) String() string

type Location

type Location struct {
	Text []byte // The original text fragment from the source.
	File string // The name of the source file (which may be empty).
	Row  int    // The line in the source.
	Col  int    // The column in the row.
}

Location records a position in source code

func NewLocation

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

NewLocation returns a new Location object.

func (*Location) Errorf

func (loc *Location) Errorf(f string, a ...interface{}) error

Errorf returns a new error value with a message formatted to include the location info (e.g., line, column, filename, etc.)

func (*Location) Wrapf

func (loc *Location) Wrapf(err error, f string, a ...interface{}) error

Wrapf returns a new error value that wraps an existing error with a message formatted to include the location info (e.g., line, column, filename, etc.)

type Module

type Module struct {
	Package *Package
	Imports []*Import
	Rules   []*Rule
}

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 (*Module) Equal

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

Equal returns true if this Module equals the other Module. Two modules are equal if they contain the same package, ordered imports, and ordered rules.

type ModuleTreeNode

type ModuleTreeNode struct {
	Key      string
	Modules  []*Module
	Children map[string]*ModuleTreeNode
}

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

func NewModuleTree

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

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

func (*ModuleTreeNode) Size

func (n *ModuleTreeNode) Size() int

Size returns the number of modules in the tree.

type Null

type Null struct{}

Null represents the null value defined by JSON.

func (Null) Equal

func (null Null) Equal(other Value) bool

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

func (Null) Hash

func (null Null) Hash() int

Hash returns the hash code for the Value.

func (Null) IsGround

func (null Null) IsGround() bool

IsGround always returns true.

func (Null) String

func (null Null) String() string

type Number

type Number float64

Number represents a numeric value as defined by JSON.

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

func (num Number) Hash() int

Hash returns the hash code for the Value.

func (Number) IsGround

func (num Number) IsGround() bool

IsGround always returns true.

func (Number) String

func (num Number) String() string

type Object

type Object [][2]*Term

Object represents an object as defined by the language. Objects are similar to the same types as defined by JSON with the exception that they can contain Vars and References.

func (Object) Diff

func (obj Object) Diff(other Object) Object

Diff returns a new Object that contains only the key/value pairs that exist in obj.

func (Object) Equal

func (obj Object) Equal(other Value) bool

Equal returns true if the other Value is an Object and the key/value pairs of the Other object are equal to the key/value pairs of this Object. The key/value pairs are ordered.

func (Object) Hash

func (obj Object) Hash() int

Hash returns the hash code for the Value.

func (Object) Intersect

func (obj Object) Intersect(other Object) [][3]*Term

Intersect returns a slice of term triplets that represent the intersection of keys between obj and other. For each intersecting key, the values from obj and other are included as the last two terms in the triplet (respectively).

func (Object) IsGround

func (obj Object) IsGround() bool

IsGround returns true if all of the Object key/value pairs are ground.

func (Object) Merge

func (obj Object) Merge(other Object) (Object, bool)

Merge returns a new Object containing the non-overlapping keys of obj and other. If there are overlapping keys between obj and other, the values of associated with the keys are merged. Only objects can be merged with other objects. If the values cannot be merged, the second turn value will be false.

func (Object) Query

func (obj Object) Query(ref Ref, iter QueryIterator) error

Query invokes the iterator for each referenced value inside the object.

func (Object) String

func (obj Object) String() string

type Option

type Option func(*parser) Option

Option is a function that can set an option on the parser. It returns the previous setting as an Option.

func Debug

func Debug(b bool) Option

Debug creates an Option to set the debug flag to b. When set to true, debugging information is printed to stdout while parsing.

The default is false.

func Memoize

func Memoize(b bool) Option

Memoize creates an Option to set the memoize flag to b. When set to true, the parser will cache all results so each expression is evaluated only once. This guarantees linear parsing time even for pathological cases, at the expense of more memory and slower times for typical cases.

The default is false.

func Recover

func Recover(b bool) Option

Recover creates an Option to set the recover flag to b. When set to true, this causes the parser to recover from panics and convert it to an error. Setting it to false can be useful while debugging to access the full stack trace.

The default is true.

type Package

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

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

func (*Package) Equal

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

Equal returns true if this Package has the same path as the other Package.

func (*Package) Loc

func (pkg *Package) Loc() *Location

Loc returns the location of the Package in the definition.

func (*Package) String

func (pkg *Package) String() string

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 (Ref) Equal

func (ref Ref) Equal(other Value) bool

Equal returns true if the other Value is a Ref and the elements of the other Ref are equal to the this Ref.

func (Ref) Hash

func (ref Ref) Hash() int

Hash returns the hash code for the Value.

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

func (ref Ref) String() string

func (Ref) Underlying

func (ref Ref) Underlying() ([]interface{}, error)

Underlying returns a slice of underlying Go values. If the slice is not ground, an error is returned.

type Rule

type Rule struct {
	Location *Location `json:"-"`
	Name     Var
	Key      *Term `json:",omitempty"`
	Value    *Term `json:",omitempty"`
	Body     Body
}

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

func MustParseRule

func MustParseRule(input string) *Rule

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

func ParseConstantRule

func ParseConstantRule(body Body) *Rule

ParseConstantRule attempts to return a rule from a body. Equality expressions of the form <var> = <ground term> can be converted into rules of the form <var> = <ground term> :- true. This is a concise way of defining constants inside modules.

func ParseRule

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

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

func (*Rule) DocKind

func (rule *Rule) DocKind() DocKind

DocKind returns the type of document produced by this rule.

func (*Rule) Equal

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

Equal returns true if this Rule has the same name, arguments, and body as the other Rule.

func (*Rule) HeadVars

func (rule *Rule) HeadVars() VarSet

HeadVars returns map where keys represent all of the variables found in the head of the rule. The values of the map are ignored.

func (*Rule) Loc

func (rule *Rule) Loc() *Location

Loc returns the location of the Rule in the definition.

func (*Rule) String

func (rule *Rule) String() string

type Statement

type Statement interface {
	Loc() *Location
}

Statement represents a single statement within a module.

type String

type String string

String represents a string value as defined by JSON.

func (String) Equal

func (str String) Equal(other Value) bool

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

func (String) Hash

func (str String) Hash() int

Hash returns the hash code for the Value.

func (String) IsGround

func (str String) IsGround() bool

IsGround always returns true.

func (String) String

func (str String) String() string

type Term

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

Term is an argument to a function.

func ArrayComprehensionTerm

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

func NullTerm() *Term

NullTerm creates a new Term with a Null value.

func NumberTerm

func NumberTerm(n float64) *Term

NumberTerm creates a new Term with a Number 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 StringTerm

func StringTerm(s string) *Term

StringTerm creates a new Term with a String value.

func VarTerm

func VarTerm(v string) *Term

VarTerm creates a new Term with a Variable value.

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) 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 terms' Value is ground.

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

type Value interface {
	// Equal returns true if this value equals the other value.
	Equal(other Value) bool

	// IsGround returns true if this value is not a variable or contains no variables.
	IsGround() bool

	// String returns a human readable string representation of the value.
	String() string

	// Returns hash code of the value.
	Hash() int
}

Value declares the common interface for all Term values. Every kind of Term value in the language is represented as a type that implements this interface:

- Null, Boolean, Number, String - Object, Array - Variables - References - Array Comprehensions

func InterfaceToValue

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

InterfaceToValue converts a native Go value x to a Value.

type Var

type Var string

Var represents a variable as defined by the language.

func (Var) Equal

func (variable Var) Equal(other Value) bool

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

func (Var) Hash

func (variable Var) Hash() int

Hash returns the hash code for the Value.

func (Var) IsGround

func (variable Var) IsGround() bool

IsGround always returns false.

func (Var) String

func (variable 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 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) Intersect

func (s VarSet) Intersect(vs VarSet) VarSet

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

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

Jump to

Keyboard shortcuts

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