adt

package
v0.3.0-alpha6 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2020 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package adt represents partially and fully evaluated CUE types.

This package introduces several categories of types that indicate some set of values that may be used in a certain situation. Concrete types may belong to multiple categories.

Abstract Types

The following types describe the a place where a value may be used:

Decl       a value than can be used as a StructLit element.
Elem       a value than can be used as a ListLit element.
Expr       represents an Expr in the CUE grammar.
Value      a fully evaluated value that has no references (except for
           children in composite values).
Node       any of the above values.

The following types categorize nodes by function:

Resolver   a reference to position in the result tree.
Evaluator  evaluates to 1 value.
Yielder    evaluates to 0 or more values.
Validator  validates another value.

Reference resolution algorithm

A Resolver is resolved within the context of an Environment. In CUE, a reference is evaluated by substituting it with a copy of the value to which it refers. If the copied value itself contains references we can distinguish two different cases. References that refer to values within the copied reference (not regarding selectors) will henceforth point to the copied node. References that point to outside the referened value will keep referring to their original value.

a: b: {
  c: int
  d: c
  e: f
}
f: 4
g: a.b { // d.c points to inside the referred value, e.f, not.
  c: 3
}

The implementation doesn't actually copy referred values, but rather resolves references with the aid of an Environment. During compile time, each references is associated with the label and a number indicating in which parent scope (offset from the current) this label needs to be looked up. An Environment keeps track of the point at which a value was referenced, providing enough information to look up the labeled value. This Environment is the identical for all references within a fields conjunct. Often, an Environment can even be shared among conjuncts.

Values

Values are fully evaluated expressions. As this means that all references will have been eliminated, Values are fully defined without the need for an Environment. Additionally, Values represent a fully evaluated form, stripped of any comprehensions, optional fields or embeddings.

Index

Constants

View Source
const MaxIndex int64 = 1<<28 - 1

MaxIndex indicates the maximum number of unique strings that are used for labeles within this CUE implementation.

Variables

View Source
var Debug bool = os.Getenv("CUE_DEBUG") != "0"

Debug sets whether extra aggressive checking should be done. This should typically default to true for pre-releases and default to false otherwise.

Functions

func Assertf

func Assertf(b bool, format string, args ...interface{})

Assert panics if the condition is false. Assert can be used to check for conditions that are considers to break an internal variant or unexpected condition, but that nonetheless probably will be handled correctly down the line. For instance, a faulty condition could lead to to error being caught down the road, but resulting in an inaccurate error message. In production code it is better to deal with the bad error message than to panic.

It is advisable for each use of Assert to document how the error is expected to be handled down the line.

func Equal

func Equal(ctx *OpContext, v, w Value) bool

func IsConcrete

func IsConcrete(v Value) bool

IsConcrete returns whether a value is concrete.

func Pos

func Pos(n Node) token.Pos

Pos returns the file position of n, or token.NoPos if it is unknown.

Types

type Acceptor

type Acceptor interface {
	// Accept reports whether a given field is accepted as output.
	// Pass an InvalidLabel to determine whether this is always open.
	Accept(ctx *OpContext, f Feature) bool

	// MatchAndInsert finds the conjuncts for optional fields, pattern
	// constraints, and additional constraints that match f and inserts them in
	// arc. Use f is 0 to match all additional constraints only.
	MatchAndInsert(c *OpContext, arc *Vertex)

	// OptionalTypes returns a bit field with the type of optional constraints
	// that are represented by this Acceptor.
	OptionalTypes() OptionalType

	// IsOptional reports whether a field is explicitly defined as optional,
	// as opposed to whether it is allowed by a pattern constraint.
	IsOptional(f Feature) bool
}

Acceptor is a single interface that reports whether feature f is a valid field label for this vertex.

TODO: combine this with the StructMarker functionality?

type BaseValue

type BaseValue interface {
	Kind() Kind
}

A BaseValue is any Value or a *Marker. It indicates the type of a Vertex.

type BasicType

type BasicType struct {
	Src *ast.Ident
	K   Kind
}

BasicType represents all values of a certain Kind. It can be used as a Value and Expr.

string
int
num
bool

func (*BasicType) Concreteness

func (*BasicType) Concreteness() Concreteness

func (*BasicType) Kind

func (x *BasicType) Kind() Kind

func (*BasicType) Source

func (x *BasicType) Source() ast.Node

type BinaryExpr

type BinaryExpr struct {
	Src *ast.BinaryExpr
	Op  Op
	X   Expr
	Y   Expr
}

BinaryExpr is a binary expression.

X + Y
X & Y

func (*BinaryExpr) Source

func (x *BinaryExpr) Source() ast.Node

type Bool

type Bool struct {
	Src ast.Node
	B   bool
}

Bool is a boolean value. It can be used as a Value and Expr.

func (*Bool) Concreteness

func (*Bool) Concreteness() Concreteness

func (*Bool) Kind

func (x *Bool) Kind() Kind

func (*Bool) Source

func (x *Bool) Source() ast.Node

type Bottom

type Bottom struct {
	Src ast.Node
	Err errors.Error

	Code         ErrorCode
	HasRecursive bool
	ChildError   bool // Err is the error of the child
	// Value holds the computed value so far in case
	Value Value
}

Bottom represents an error or bottom symbol.

Although a Bottom node holds control data, it should not be created until the control information already resulted in an error.

func CombineErrors

func CombineErrors(src ast.Node, x, y Value) *Bottom

CombineErrors combines two errors that originate at the same Vertex.

func (*Bottom) Concreteness

func (*Bottom) Concreteness() Concreteness

func (*Bottom) IsIncomplete

func (b *Bottom) IsIncomplete() bool

func (*Bottom) Kind

func (x *Bottom) Kind() Kind

func (*Bottom) Source

func (x *Bottom) Source() ast.Node

func (*Bottom) Specialize

func (x *Bottom) Specialize(k Kind) Value

type BoundExpr

type BoundExpr struct {
	Src  *ast.UnaryExpr
	Op   Op
	Expr Expr
}

BoundExpr represents an unresolved unary comparator.

<a
=~MyPattern

func (*BoundExpr) Source

func (x *BoundExpr) Source() ast.Node

type BoundValue

type BoundValue struct {
	Src   ast.Expr
	Op    Op
	Value Value
}

A BoundValue is a fully evaluated unary comparator that can be used to validate other values.

<5
=~"Name$"

func (*BoundValue) Concreteness

func (*BoundValue) Concreteness() Concreteness

func (*BoundValue) Kind

func (x *BoundValue) Kind() Kind

func (*BoundValue) Source

func (x *BoundValue) Source() ast.Node

type Builtin

type Builtin struct {
	// TODO:  make these values for better type checking.
	Params []Param
	Result Kind
	Func   func(c *OpContext, args []Value) Expr

	Package Feature
	Name    string
}

A Builtin is a value representing a native function call.

func (*Builtin) BareValidator

func (x *Builtin) BareValidator() *BuiltinValidator

func (*Builtin) Concreteness

func (*Builtin) Concreteness() Concreteness

func (*Builtin) IsValidator

func (b *Builtin) IsValidator(numArgs int) bool

IsValidator reports whether b should be interpreted as a Validator for the given number of arguments.

func (*Builtin) Kind

func (x *Builtin) Kind() Kind

Kind here represents the case where Builtin is used as a Validator.

func (*Builtin) Source

func (x *Builtin) Source() ast.Node

func (*Builtin) WriteName

func (x *Builtin) WriteName(w io.Writer, c *OpContext)

type BuiltinValidator

type BuiltinValidator struct {
	Src     *CallExpr
	Builtin *Builtin
	Args    []Value // any but the first value
}

A BuiltinValidator is a Value that results from evaluation a partial call to a builtin (using CallExpr).

strings.MinRunes(4)

func (*BuiltinValidator) Concreteness

func (*BuiltinValidator) Concreteness() Concreteness

func (*BuiltinValidator) Kind

func (x *BuiltinValidator) Kind() Kind

func (*BuiltinValidator) Pos

func (x *BuiltinValidator) Pos() token.Pos

func (*BuiltinValidator) Source

func (x *BuiltinValidator) Source() ast.Node

type BulkOptionalField

type BulkOptionalField struct {
	Src    *ast.Field // Elipsis or Field
	Filter Expr
	Value  Expr
	Label  Feature // for reference and formatting
}

A BulkOptionalField represents a set of optional field.

[expr]: expr

func (*BulkOptionalField) Source

func (x *BulkOptionalField) Source() ast.Node

type Bytes

type Bytes struct {
	Src ast.Node
	B   []byte
	RE  *regexp.Regexp // only set if needed
}

Bytes is a bytes value. It can be used as a Value and Expr.

func (*Bytes) Concreteness

func (*Bytes) Concreteness() Concreteness

func (*Bytes) Kind

func (x *Bytes) Kind() Kind

func (*Bytes) Source

func (x *Bytes) Source() ast.Node

type CallExpr

type CallExpr struct {
	Src  *ast.CallExpr
	Fun  Expr
	Args []Expr
}

A CallExpr represents a call to a builtin.

len(x)
strings.ToLower(x)

func (*CallExpr) Source

func (x *CallExpr) Source() ast.Node

type Concreteness

type Concreteness int

Concreteness is a measure of the level of concreteness of a value, where lower values mean more concrete.

const (
	BottomLevel Concreteness = iota

	// Concrete indicates a concrete scalar value, list or struct.
	Concrete

	// Constraint indicates a non-concrete scalar value that is more specific,
	// than a top-level type.
	Constraint

	// PrimitiveType indicates a top-level specific type, for instance, string,
	// bytes, number, or bool.
	Type

	// Any indicates any value, or top.
	Any
)

type Config

type Config struct {
	Runtime
	Unifier

	Format func(Node) string
}

type Conjunct

type Conjunct struct {
	Env *Environment

	// CloseID is a unique number that tracks a group of conjuncts that need
	// belong to a single originating definition.
	CloseID ID
	// contains filtered or unexported fields
}

An Conjunct is an Environment-Expr pair. The Environment is the starting point for reference lookup for any reference contained in X.

func MakeConjunct

func MakeConjunct(env *Environment, x Node, id ID) Conjunct

func MakeRootConjunct

func MakeRootConjunct(env *Environment, x Node) Conjunct

MakeRootConjunct creates a conjunct from the given environment and node. It panics if x cannot be used as an expression.

func (*Conjunct) Expr

func (c *Conjunct) Expr() Expr

func (*Conjunct) Field

func (c *Conjunct) Field() Node

func (*Conjunct) ID

func (c *Conjunct) ID() ID

func (*Conjunct) Source

func (c *Conjunct) Source() ast.Node

type Conjunction

type Conjunction struct {
	Src    ast.Expr
	Values []Value
}

A Conjunction is a conjunction of values that cannot be represented as a single value. It is the result of unification.

func (*Conjunction) Concreteness

func (*Conjunction) Concreteness() Concreteness

func (*Conjunction) Kind

func (x *Conjunction) Kind() Kind

func (*Conjunction) Source

func (x *Conjunction) Source() ast.Node

type Decl

type Decl interface {
	Node
	// contains filtered or unexported methods
}

A Decl represents all valid StructLit elements.

type Disjunct

type Disjunct struct {
	Val     Expr
	Default bool
}

A Disjunct is used in Disjunction.

type Disjunction

type Disjunction struct {
	Src ast.Expr

	// Values are the non-error disjuncts of this expression. The first
	// NumDefault values are default values.
	Values []*Vertex

	Errors *Bottom // []bottom

	// NumDefaults indicates the number of default values.
	NumDefaults int
}

A disjunction is a disjunction of values. It is the result of expanding a DisjunctionExpr if the expression cannot be represented as a single value.

func (*Disjunction) Concreteness

func (*Disjunction) Concreteness() Concreteness

func (*Disjunction) Default

func (d *Disjunction) Default() Value

func (*Disjunction) Kind

func (x *Disjunction) Kind() Kind

func (*Disjunction) Source

func (x *Disjunction) Source() ast.Node

type DisjunctionExpr

type DisjunctionExpr struct {
	Src    *ast.BinaryExpr
	Values []Disjunct

	HasDefaults bool
}

A Disjunction represents a disjunction, where each disjunct may or may not be marked as a default.

func (*DisjunctionExpr) Source

func (x *DisjunctionExpr) Source() ast.Node

type DynamicField

type DynamicField struct {
	Src   *ast.Field
	Key   Expr
	Value Expr
}

A DynamicField represents a regular field for which the key is computed.

"\(expr)": expr
(expr): expr

func (*DynamicField) IsOptional

func (x *DynamicField) IsOptional() bool

func (*DynamicField) Source

func (x *DynamicField) Source() ast.Node

type DynamicReference

type DynamicReference struct {
	Src     *ast.Ident
	UpCount int32
	Label   Expr

	// TODO: only use aliases and store the actual expression only in the scope.
	// The feature is unique for every instance. This will also allow dynamic
	// fields to be ordered among normal fields.
	//
	// This could also be used to assign labels to embedded values, if they
	// don't match a label.
	Alias Feature
}

A DynamicReference is like a LabelReference, but with a computed label.

X=(x): X
X="\(x)": X

func (*DynamicReference) Source

func (x *DynamicReference) Source() ast.Node

type Elem

type Elem interface {
	Decl
	// contains filtered or unexported methods
}

An Elem represents all value ListLit elements.

All Elem values can be used as a Decl.

type Ellipsis

type Ellipsis struct {
	Src   *ast.Ellipsis
	Value Expr
}

A Ellipsis represents a set of optional fields of a given type.

...T

func (*Ellipsis) Source

func (x *Ellipsis) Source() ast.Node

type Environment

type Environment struct {
	Up     *Environment
	Vertex *Vertex

	// DynamicLabel is only set when instantiating a field from a pattern
	// constraint. It is used to resolve label references.
	DynamicLabel Feature

	// Cyclic indicates a structural cycle was detected for this conjunct or one
	// of its ancestors.
	Cyclic bool

	// Deref keeps track of nodes that should dereference to Vertex. It is used
	// for detecting structural cycle.
	//
	// The detection algorithm is based on Tomabechi's quasi-destructive graph
	// unification. This detection requires dependencies to be resolved into
	// fully dereferenced vertices. This is not the case in our algorithm:
	// the result of evaluating conjuncts is placed into dereferenced vertices
	// _after_ they are evaluated, but the Environment still points to the
	// non-dereferenced context.
	//
	// In order to be able to detect structural cycles, we need to ensure that
	// at least one node that is part of a cycle in the context in which
	// conjunctions are evaluated dereferences correctly.
	//
	// The only field necessary to detect a structural cycle, however, is
	// the Status field of the Vertex. So rather than dereferencing a node
	// proper, it is sufficient to copy the Status of the dereferenced nodes
	// to these nodes (will always be EvaluatingArcs).
	Deref []*Vertex

	// Cycles contains vertices for which cycles are detected. It is used
	// for tracking self-references within structural cycles.
	//
	// Unlike Deref, Cycles is not incremented with child nodes.
	// TODO: Cycles is always a tail end of Deref, so this can be optimized.
	Cycles []*Vertex
	// contains filtered or unexported fields
}

An Environment links the parent scopes for identifier lookup to a composite node. Each conjunct that make up node in the tree can be associated with a different environment (although some conjuncts may share an Environment).

type ErrorCode

type ErrorCode int

ErrorCode indicates the type of error. The type of error may influence control flow. No other aspects of an error may influence control flow.

const (
	// An EvalError is a fatal evaluation error.
	EvalError ErrorCode = iota

	// A UserError is a fatal error originating from the user.
	UserError

	// NotExistError is used to indicate a value does not exist.
	// Mostly used for legacy reasons.
	NotExistError

	// StructuralCycleError means a structural cycle was found. Structural
	// cycles are permanent errors, but they are not passed up recursively,
	// as a unification of a value with a structural cycle with one that
	// doesn't may still give a useful result.
	StructuralCycleError

	// IncompleteError means an evaluation could not complete because of
	// insufficient information that may still be added later.
	IncompleteError

	// A CycleError indicates a reference error. It is considered to be
	// an incomplete error, as reference errors may be broken by providing
	// a concrete value.
	CycleError
)

func (ErrorCode) String

func (c ErrorCode) String() string

type Evaluator

type Evaluator interface {
	Node
	// contains filtered or unexported methods
}

An Evaluator provides a method to convert to a value.

type Expr

type Expr interface {
	Elem
	// contains filtered or unexported methods
}

An Expr corresponds to an ast.Expr.

All Expr values can be used as an Elem or Decl.

type Feature

type Feature uint32

A Feature is an encoded form of a label which comprises a compact representation of an integer or string label as well as a label type.

const InvalidLabel Feature = 0x7 // 0xb111

InvalidLabel is an encoding of an erroneous label.

func MakeIdentLabel

func MakeIdentLabel(r StringIndexer, s, pkgpath string) Feature

MakeIdentLabel creates a label for the given identifier.

func MakeLabel

func MakeLabel(src ast.Node, index int64, f FeatureType) (Feature, errors.Error)

MakeLabel creates a label. It reports an error if the index is out of range.

func MakeStringLabel

func MakeStringLabel(r StringIndexer, s string) Feature

MakeStringLabel creates a label for the given string.

func (Feature) IdentString

func (f Feature) IdentString(index StringIndexer) string

IdentString reports the identifier of f. The result is undefined if f is not an identifier label.

func (Feature) Index

func (f Feature) Index() int

Index reports the abstract index associated with f.

func (Feature) IsDef

func (f Feature) IsDef() bool

IsDef reports whether the label is a definition (an identifier starting with # or #_.

func (Feature) IsHidden

func (f Feature) IsHidden() bool

IsHidden reports whether this label is hidden (an identifier starting with _ or #_).

func (Feature) IsInt

func (f Feature) IsInt() bool

IsInt reports whether this is an integer index.

func (Feature) IsRegular

func (f Feature) IsRegular() bool

IsRegular reports whether a label represents a data field.

func (Feature) IsString

func (f Feature) IsString() bool

IsString reports whether a label represents a regular field.

func (Feature) IsValid

func (f Feature) IsValid() bool

IsValid reports whether f is a valid label.

func (Feature) PkgID

func (f Feature) PkgID(index StringIndexer) string

PkgID returns the package identifier, composed of the module and package name, associated with this identifier. It will return "" if this is not a hidden label.

func (Feature) SelectorString

func (f Feature) SelectorString(index StringIndexer) string

SelectorString reports the shortest string representation of f when used as a selector.

func (Feature) StringValue

func (f Feature) StringValue(index StringIndexer) string

StringValue reports the string value of f, which must be a string label.

func (Feature) ToValue

func (f Feature) ToValue(ctx *OpContext) Value

ToValue converts a label to a value, which will be a Num for integer labels and a String for string labels. It panics when f is not a regular label.

func (Feature) Typ

func (f Feature) Typ() FeatureType

Typ reports the type of label.

type FeatureType

type FeatureType int8

A FeatureType indicates the type of label.

const (
	StringLabel           FeatureType = 0 // 0b000
	IntLabel              FeatureType = 1 // 0b001
	DefinitionLabel       FeatureType = 3 // 0b011
	HiddenLabel           FeatureType = 6 // 0b110
	HiddenDefinitionLabel FeatureType = 7 // 0b111

)

type Field

type Field struct {
	Src *ast.Field

	Label Feature
	Value Expr
}

Field represents a field with a fixed label. It can be a regular field, definition or hidden field.

foo: bar
#foo: bar
_foo: bar

Legacy:

Foo :: bar

func (*Field) Source

func (x *Field) Source() ast.Node

type FieldReference

type FieldReference struct {
	Src     *ast.Ident
	UpCount int32
	Label   Feature
}

A FieldReference represents a lexical reference to a field.

a

func (*FieldReference) Source

func (x *FieldReference) Source() ast.Node

type ForClause

type ForClause struct {
	Syntax *ast.ForClause
	Key    Feature
	Value  Feature
	Src    Expr
	Dst    Yielder
}

A ForClause represents a for clause of a comprehension. It can be used as a struct or list element.

for k, v in src {}

func (*ForClause) Source

func (x *ForClause) Source() ast.Node

type ID

type ID int32

type IfClause

type IfClause struct {
	Src       *ast.IfClause
	Condition Expr
	Dst       Yielder
}

An IfClause represents an if clause of a comprehension. It can be used as a struct or list element.

if cond {}

func (*IfClause) Source

func (x *IfClause) Source() ast.Node

type ImportReference

type ImportReference struct {
	Src        *ast.Ident
	ImportPath Feature
	Label      Feature // for informative purposes
}

An ImportReference refers to an imported package.

import "strings"

strings.ToLower("Upper")

func (*ImportReference) Source

func (x *ImportReference) Source() ast.Node

type IndexExpr

type IndexExpr struct {
	Src   *ast.IndexExpr
	X     Expr
	Index Expr
}

IndexExpr is like a selector, but selects an index.

X[Index]

func (*IndexExpr) Source

func (x *IndexExpr) Source() ast.Node

type Interpolation

type Interpolation struct {
	Src   *ast.Interpolation
	K     Kind   // string or bytes
	Parts []Expr // odd: strings, even sources
}

An Interpolation is a string interpolation.

"a \(b) c"

func (*Interpolation) Source

func (x *Interpolation) Source() ast.Node

type Kind

type Kind uint16

Kind reports the Value kind.

const (
	NullKind Kind = (1 << iota)
	BoolKind
	IntKind
	FloatKind
	StringKind
	BytesKind
	FuncKind
	ListKind
	StructKind

	NumberKind = IntKind | FloatKind

	BottomKind Kind = 0

	NumKind          = IntKind | FloatKind
	TopKind     Kind = (allKinds - 1) // all kinds, but not references
	ScalarKinds      = NullKind | BoolKind |
		IntKind | FloatKind | StringKind | BytesKind
)

func (Kind) CanString

func (k Kind) CanString() bool

CanString reports whether the given type can convert to a string.

func (Kind) IsAnyOf

func (k Kind) IsAnyOf(of Kind) bool

IsAnyOf reports whether k is any of the given kinds.

For instances, k.IsAnyOf(String|Bytes) reports whether k overlaps with the String or Bytes kind.

func (Kind) String

func (k Kind) String() string

String returns the representation of the Kind as a CUE expression. For example:

(IntKind|ListKind).String()

will return:

(int|[...])

func (Kind) TypeString

func (k Kind) TypeString() string

TypeString is like String, but returns a string representation of a valid CUE type.

type LabelReference

type LabelReference struct {
	Src     *ast.Ident
	UpCount int32
}

A LabelReference refers to the string or integer value of a label.

[X=Pattern]: b: X

func (*LabelReference) Source

func (x *LabelReference) Source() ast.Node

type LetClause

type LetClause struct {
	Src   *ast.LetClause
	Label Feature
	Expr  Expr
	Dst   Yielder
}

An LetClause represents a let clause in a comprehension.

for k, v in src {}

func (*LetClause) Source

func (x *LetClause) Source() ast.Node

type LetReference

type LetReference struct {
	Src     *ast.Ident
	UpCount int32
	Label   Feature // for informative purposes
	X       Expr
}

A LetReference evaluates a let expression in its original environment.

let X = x

func (*LetReference) Source

func (x *LetReference) Source() ast.Node

type ListLit

type ListLit struct {
	Src *ast.ListLit

	// scalars, comprehensions, ...T
	Elems []Elem
}

A ListLit represents an unevaluated list literal.

[a, for x in src { ... }, b, ...T]

func (*ListLit) Source

func (x *ListLit) Source() ast.Node

type ListMarker

type ListMarker struct {
	Src    ast.Node
	IsOpen bool
}

func (*ListMarker) Kind

func (x *ListMarker) Kind() Kind

func (*ListMarker) Source

func (x *ListMarker) Source() ast.Node

type Node

type Node interface {
	Source() ast.Node
	// contains filtered or unexported methods
}

A Node is any abstract data type representing an value or expression.

type NodeLink struct {
	Node *Vertex
}

A NodeLink is used during computation to refer to an existing Vertex. It is used to signal a potential cycle or reference. Note that a NodeLink may be used as a value. This should be taken into account.

func (*NodeLink) Concreteness

func (x *NodeLink) Concreteness() Concreteness

func (*NodeLink) Kind

func (x *NodeLink) Kind() Kind

func (*NodeLink) Source

func (x *NodeLink) Source() ast.Node

type Null

type Null struct {
	Src ast.Node
}

Null represents null. It can be used as a Value and Expr.

func (*Null) Concreteness

func (*Null) Concreteness() Concreteness

func (*Null) Kind

func (x *Null) Kind() Kind

func (*Null) Source

func (x *Null) Source() ast.Node

type Num

type Num struct {
	Src ast.Node
	K   Kind        // needed?
	X   apd.Decimal // Is integer if the apd.Decimal is an integer.
}

Num is a numeric value. It can be used as a Value and Expr.

func (*Num) Cmp

func (a *Num) Cmp(b *Num) int

func (*Num) Concreteness

func (*Num) Concreteness() Concreteness

func (*Num) Impl

func (n *Num) Impl() *apd.Decimal

func (*Num) Kind

func (x *Num) Kind() Kind

func (*Num) Negative

func (n *Num) Negative() bool

func (*Num) Source

func (x *Num) Source() ast.Node

type Op

type Op int

Op indicates the operation at the top of an expression tree of the expression use to evaluate a value.

const (
	NoOp Op = iota

	AndOp
	OrOp

	SelectorOp
	IndexOp
	SliceOp
	CallOp

	BoolAndOp
	BoolOrOp

	EqualOp
	NotOp
	NotEqualOp
	LessThanOp
	LessEqualOp
	GreaterThanOp
	GreaterEqualOp

	MatchOp
	NotMatchOp

	AddOp
	SubtractOp
	MultiplyOp
	FloatQuotientOp
	IntQuotientOp
	IntRemainderOp
	IntDivideOp
	IntModuloOp

	InterpolationOp
)

Values of Op.

func OpFromToken

func OpFromToken(t token.Token) Op

OpFromToken converts a token.Token to an Op.

func (Op) String

func (o Op) String() string

func (Op) Token

func (op Op) Token() token.Token

Token returns the token.Token corresponding to the Op.

type OpContext

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

An OpContext associates a Runtime and Unifier to allow evaluating the types defined in this package. It tracks errors provides convenience methods for evaluating values.

func New

func New(v *Vertex, cfg *Config) *OpContext

New creates an operation context.

func NewContext

func NewContext(r Runtime, u Unifier, v *Vertex) *OpContext

NewContext creates an operation context.

func (*OpContext) Add

func (c *OpContext) Add(a, b *Num) Value

func (*OpContext) AddBottom

func (c *OpContext) AddBottom(b *Bottom)

AddBottom records an error in OpContext.

func (*OpContext) AddErr

func (c *OpContext) AddErr(err errors.Error) *Bottom

AddErr records an error in OpContext. It returns errors collected so far.

func (*OpContext) AddErrf

func (c *OpContext) AddErrf(format string, args ...interface{}) *Bottom

AddErrf records an error in OpContext. It returns errors collected so far.

func (*OpContext) AddPosition

func (c *OpContext) AddPosition(n Node)

func (*OpContext) Assertf

func (c *OpContext) Assertf(pos token.Pos, b bool, format string, args ...interface{})

Assertf either panics or reports an error to c if the condition is not met.

func (*OpContext) BoolValue

func (c *OpContext) BoolValue(v Value) bool

func (*OpContext) Concrete

func (c *OpContext) Concrete(env *Environment, x Expr, msg interface{}) (result Value, complete bool)

Concrete returns the concrete value of x after evaluating it. msg is used to mention the context in which an error occurred, if any.

func (*OpContext) Elems

func (c *OpContext) Elems(v Value) []*Vertex

Elems returns the elements of a list.

func (*OpContext) Env

func (c *OpContext) Env(upCount int32) *Environment

func (*OpContext) Err

func (c *OpContext) Err() *Bottom

func (*OpContext) Evaluate

func (c *OpContext) Evaluate(env *Environment, x Expr) (result Value, complete bool)

Evaluate evaluates an expression within the given environment and indicates whether the result is complete. It will always return a non-nil result.

func (*OpContext) HasErr

func (c *OpContext) HasErr() bool

HasErr reports whether any error was reported, including whether value was incomplete.

func (*OpContext) Impl

func (c *OpContext) Impl() Runtime

Impl is for internal use only. This will go.

func (*OpContext) Int64

func (c *OpContext) Int64(v Value) int64

func (*OpContext) IntDiv

func (c *OpContext) IntDiv(a, b *Num) Value

func (*OpContext) IntMod

func (c *OpContext) IntMod(a, b *Num) Value

func (*OpContext) IntQuo

func (c *OpContext) IntQuo(a, b *Num) Value

func (*OpContext) IntRem

func (c *OpContext) IntRem(a, b *Num) Value

func (*OpContext) IsTentative

func (c *OpContext) IsTentative() bool

If IsTentative is set, evaluation of an arc should not finalize to non-concrete values.

func (*OpContext) Label

func (c *OpContext) Label(src Expr, x Value) Feature

func (*OpContext) MarkPositions

func (c *OpContext) MarkPositions() int

MarkPositions marks the current position stack.

func (*OpContext) Mul

func (c *OpContext) Mul(a, b *Num) Value

func (*OpContext) NewErrf

func (c *OpContext) NewErrf(format string, args ...interface{}) *Bottom

NewErrf creates a *Bottom value and returns it. The returned uses the current source as the point of origin of the error.

func (*OpContext) NewInt64

func (c *OpContext) NewInt64(n int64, sources ...Node) Value

func (*OpContext) NewList

func (c *OpContext) NewList(values ...Value) *Vertex

NewList returns a new list for the given values.

func (*OpContext) NewPosf

func (c *OpContext) NewPosf(p token.Pos, format string, args ...interface{}) *ValueError

func (*OpContext) NewString

func (c *OpContext) NewString(s string) Value

func (*OpContext) Newf

func (c *OpContext) Newf(format string, args ...interface{}) *ValueError

func (*OpContext) Num

func (c *OpContext) Num(v Value, as interface{}) *Num

func (*OpContext) PopArc

func (c *OpContext) PopArc(saved *Vertex)

PopArc signals completion of processing the current arc.

func (*OpContext) PopState

func (c *OpContext) PopState(s frame) *Bottom

func (*OpContext) Pos

func (c *OpContext) Pos() token.Pos

func (*OpContext) Pow

func (c *OpContext) Pow(a, b *Num) Value

func (*OpContext) PushArc

func (c *OpContext) PushArc(v *Vertex) (saved *Vertex)

PushArc signals c that arc v is currently being processed for the purpose of error reporting. PopArc should be called with the returned value once processing of v is completed.

func (*OpContext) PushState

func (c *OpContext) PushState(env *Environment, src ast.Node) (saved frame)

func (*OpContext) Quo

func (c *OpContext) Quo(a, b *Num) Value

func (*OpContext) ReleasePositions

func (c *OpContext) ReleasePositions(p int)

ReleasePositions sets the position state to one from a call to MarkPositions.

func (*OpContext) Resolve

func (c *OpContext) Resolve(env *Environment, r Resolver) (*Vertex, *Bottom)

Resolve finds a node in the tree.

Should only be used to insert Conjuncts. TODO: perhaps only return Conjuncts and error.

func (*OpContext) Source

func (c *OpContext) Source() ast.Node

func (*OpContext) Str

func (c *OpContext) Str(x Node) string

Str reports a debug string of x.

func (*OpContext) StringLabel

func (c *OpContext) StringLabel(s string) Feature

StringLabel converts s to a string label.

func (*OpContext) StringValue

func (c *OpContext) StringValue(v Value) string

func (*OpContext) Sub

func (c *OpContext) Sub(a, b *Num) Value

func (*OpContext) ToBytes

func (c *OpContext) ToBytes(v Value) []byte

ToBytes returns the bytes value of a scalar value.

func (*OpContext) ToString

func (c *OpContext) ToString(v Value) string

ToString returns the string value of a scalar value.

func (*OpContext) Validate

func (c *OpContext) Validate(check Validator, value Value) *Bottom

Validate calls validates value for the given validator.

TODO(errors): return boolean instead: only the caller has enough information to generate a proper error message.

func (*OpContext) Yield

func (c *OpContext) Yield(env *Environment, y Yielder, f YieldFunc) *Bottom

Yield evaluates a Yielder and calls f for each result.

type OptionalField

type OptionalField struct {
	Src   *ast.Field
	Label Feature
	Value Expr
}

An OptionalField represents an optional regular field.

foo?: expr

func (*OptionalField) Source

func (x *OptionalField) Source() ast.Node

type OptionalType

type OptionalType int

OptionalType is a bit field of the type of optional constraints in use by an Acceptor.

const (
	HasField      OptionalType = 1 << iota // X: T
	HasDynamic                             // (X): T or "\(X)": T
	HasPattern                             // [X]: T
	HasAdditional                          // ...T
	IsOpen                                 // Defined for all fields
)

type Param

type Param struct {
	Name  Feature // name of the argument; mostly for documentation
	Value Value   // Could become Value later, using disjunctions for defaults.
}

func (Param) Default

func (p Param) Default() Value

Default reports the default value for this Param or nil if there is none.

func (Param) Kind

func (p Param) Kind() Kind

Kind returns the kind mask of this parameter.

type Resolver

type Resolver interface {
	Node
	// contains filtered or unexported methods
}

A Resolver represents a reference somewhere else within a tree that resolves a value.

type Runtime

type Runtime interface {
	// StringIndexer allows for converting string labels to and from a
	// canonical numeric representation.
	StringIndexer

	// LoadImport loads a unique Vertex associated with a given import path. It
	// returns an error if no import for this package could be found.
	LoadImport(importPath string) (*Vertex, errors.Error)

	// StoreType associates a CUE expression with a Go type.
	StoreType(t reflect.Type, src ast.Expr, expr Expr)

	// LoadType retrieves a previously stored CUE expression for a given Go
	// type if available.
	LoadType(t reflect.Type) (src ast.Expr, expr Expr, ok bool)
}

Runtime defines an interface for low-level representation conversion and lookup.

type SelectorExpr

type SelectorExpr struct {
	Src *ast.SelectorExpr
	X   Expr
	Sel Feature
}

A SelectorExpr looks up a fixed field in an expression.

X.Sel

func (*SelectorExpr) Source

func (x *SelectorExpr) Source() ast.Node

type SliceExpr

type SliceExpr struct {
	Src    *ast.SliceExpr
	X      Expr
	Lo     Expr
	Hi     Expr
	Stride Expr
}

A SliceExpr represents a slice operation. (Not currently in spec.)

X[Lo:Hi:Stride]

func (*SliceExpr) Source

func (x *SliceExpr) Source() ast.Node

type String

type String struct {
	Src ast.Node
	Str string
	RE  *regexp.Regexp // only set if needed
}

String is a string value. It can be used as a Value and Expr.

func (*String) Concreteness

func (*String) Concreteness() Concreteness

func (*String) Kind

func (x *String) Kind() Kind

func (*String) Source

func (x *String) Source() ast.Node

type StringIndexer

type StringIndexer interface {
	// ToIndex returns a unique positive index for s (0 < index < 2^28-1).
	//
	// For each pair of strings s and t it must return the same index if and
	// only if s == t.
	StringToIndex(s string) (index int64)

	// ToString returns a string s for index such that ToIndex(s) == index.
	IndexToString(index int64) string
}

A StringIndexer coverts strings to and from an index that is unique for a given string.

type StructLit

type StructLit struct {
	Src   ast.Node // ast.File or ast.StructLit
	Decls []Decl
}

A StructLit represents an unevaluated struct literal or file body.

func (*StructLit) Source

func (x *StructLit) Source() ast.Node

type StructMarker

type StructMarker struct {
	// NeedClose is used to signal that the evaluator should close this struct.
	// It is only set by the close builtin.
	NeedClose bool
}

func (*StructMarker) Kind

func (x *StructMarker) Kind() Kind

func (*StructMarker) Source

func (x *StructMarker) Source() ast.Node

type Top

type Top struct{ Src *ast.Ident }

Top represents all possible values. It can be used as a Value and Expr.

func (*Top) Concreteness

func (*Top) Concreteness() Concreteness

func (*Top) Kind

func (x *Top) Kind() Kind

func (*Top) Source

func (x *Top) Source() ast.Node

type UnaryExpr

type UnaryExpr struct {
	Src *ast.UnaryExpr
	Op  Op
	X   Expr
}

UnaryExpr is a unary expression.

Op X
-X !X +X

func (*UnaryExpr) Source

func (x *UnaryExpr) Source() ast.Node

type Unifier

type Unifier interface {
	// Unify fully unifies all values of a Vertex to completion and stores
	// the result in the Vertex. If Unify was called on v before it returns
	// the cached results.
	Unify(c *OpContext, v *Vertex, state VertexStatus) // error or bool?

	// Evaluate returns the evaluated value associated with v. It may return a
	// partial result. That is, if v was not yet unified, it may return a
	// concrete value that must be the result assuming the configuration has no
	// errors.
	//
	// This semantics allows CUE to break reference cycles in a straightforward
	// manner.
	//
	// Vertex v must still be evaluated at some point to catch the underlying
	// error.
	//
	Evaluate(c *OpContext, v *Vertex) Value
}

A Unifier implements a strategy for CUE's unification operation. It must handle the following aspects of CUE evaluation:

  • Structural and reference cycles
  • Non-monotic validation
  • Fixed-point computation of comprehension

type Validator

type Validator interface {
	Value
	// contains filtered or unexported methods
}

A Validator validates a Value. All Validators are Values.

func SimplifyValidator

func SimplifyValidator(ctx *OpContext, v, w Validator) Validator

SimplifyValidator simplifies non-bound validators.

Currently this only checks for pure equality. In the future this can be used to simplify certain builtin validators analogously to how we simplify bounds now.

type Value

type Value interface {
	Expr
	Concreteness() Concreteness
	Kind() Kind
}

A Value represents a node in the evaluated data graph.

All Values values can also be used as a Expr.

func BinOp

func BinOp(c *OpContext, op Op, left, right Value) Value

BinOp handles all operations except AndOp and OrOp. This includes processing unary comparators such as '<4' and '=~"foo"'.

BinOp returns nil if not both left and right are concrete.

func Default

func Default(v Value) Value

Default returns the default value or itself if there is no default.

func SimplifyBounds

func SimplifyBounds(ctx *OpContext, k Kind, x, y *BoundValue) Value

SimplifyBounds collapses bounds if possible. The bound values must be concrete. It returns nil if the bound values cannot be collapsed.

k represents additional type constraints, such as `int`.

func Unwrap

func Unwrap(v Value) Value

Unwrap returns the possibly non-concrete scalar value of v or nil if v is a list, struct or of undefined type.

type ValueClause

type ValueClause struct {
	*StructLit
}

A ValueClause represents the value part of a comprehension.

func (*ValueClause) Source

func (x *ValueClause) Source() ast.Node

type ValueError

type ValueError struct {
	errors.Message
	// contains filtered or unexported fields
}

A ValueError is returned as a result of evaluating a value.

func (*ValueError) AddPosition

func (v *ValueError) AddPosition(n Node)

func (*ValueError) Error

func (e *ValueError) Error() string

func (*ValueError) InputPositions

func (e *ValueError) InputPositions() (a []token.Pos)

func (*ValueError) Path

func (e *ValueError) Path() (a []string)

func (*ValueError) Position

func (e *ValueError) Position() token.Pos

type Vertex

type Vertex struct {
	// Parent links to a parent Vertex. This parent should only be used to
	// access the parent's Label field to find the relative location within a
	// tree.
	Parent *Vertex

	// Label is the feature leading to this vertex.
	Label Feature

	// EvalCount keeps track of temporary dereferencing during evaluation.
	// If EvalCount > 0, status should be considered to be EvaluatingArcs.
	EvalCount int

	// SelfCount is used for tracking self-references.
	SelfCount int

	// BaseValue is the value associated with this vertex. For lists and structs
	// this is a sentinel value indicating its kind.
	BaseValue BaseValue

	// ChildErrors is the collection of all errors of children.
	ChildErrors *Bottom

	// The parent of nodes can be followed to determine the path within the
	// configuration of this node.
	// Value  Value
	Arcs []*Vertex // arcs are sorted in display order.

	// Conjuncts lists the structs that ultimately formed this Composite value.
	// This includes all selected disjuncts.
	//
	// This value may be nil, in which case the Arcs are considered to define
	// the final value of this Vertex.
	Conjuncts []Conjunct

	// Structs is a slice of struct literals that contributed to this value.
	// This information is used to compute the topological sort of arcs.
	Structs []*StructLit

	// Closed contains information about how to interpret field labels for the
	// various conjuncts with respect to which fields are allowed in this
	// Vertex. If allows all fields if it is nil.
	// The evaluator will first check existing fields before using this. So for
	// simple cases, an Acceptor can always return false to close the Vertex.
	Closed Acceptor
	// contains filtered or unexported fields
}

A Vertex is a node in the value tree. It may be a leaf or internal node. It may have arcs to represent elements of a fully evaluated struct or list.

For structs, it only contains definitions and concrete fields. optional fields are dropped.

It maintains source information such as a list of conjuncts that contributed to the value.

func Resolve

func Resolve(ctx *OpContext, c Conjunct) *Vertex

func ToVertex

func ToVertex(v Value) *Vertex

ToVertex wraps v in a new Vertex, if necessary.

func (*Vertex) Accept

func (v *Vertex) Accept(ctx *OpContext, f Feature) bool

func (*Vertex) AddChildError

func (v *Vertex) AddChildError(recursive *Bottom)

AddChildError updates x to record an error that occurred in one of its descendent arcs. The resulting error will record the worst error code of the current error or recursive error.

If x is not already an error, the value is recorded in the error for reference.

func (*Vertex) AddConjunct

func (v *Vertex) AddConjunct(c Conjunct) *Bottom

AddConjunct adds the given Conjuncts to v if it doesn't already exist.

func (*Vertex) AddErr

func (v *Vertex) AddErr(ctx *OpContext, b *Bottom)

func (*Vertex) AddStructs

func (v *Vertex) AddStructs(a ...*StructLit)

func (*Vertex) Concreteness

func (x *Vertex) Concreteness() Concreteness

func (*Vertex) Default

func (v *Vertex) Default() *Vertex

Default returns the default value or itself if there is no default.

It also closes a list, representing its default value.

func (*Vertex) Elems

func (v *Vertex) Elems() []*Vertex

Elems returns the regular elements of a list.

func (*Vertex) Err

func (v *Vertex) Err(c *OpContext, state VertexStatus) *Bottom

func (*Vertex) Finalize

func (v *Vertex) Finalize(c *OpContext)

func (*Vertex) GetArc

func (v *Vertex) GetArc(f Feature) (arc *Vertex, isNew bool)

GetArc returns a Vertex for the outgoing arc with label f. It creates and ads one if it doesn't yet exist.

func (*Vertex) IsClosed

func (v *Vertex) IsClosed(ctx *OpContext) bool

func (*Vertex) IsConcrete

func (x *Vertex) IsConcrete() bool

func (*Vertex) IsData

func (v *Vertex) IsData() bool

IsData reports whether v should be interpreted in data mode. In other words, it tells whether optional field matching and non-regular fields, like definitions and hidden fields, should be ignored.

func (*Vertex) IsErr

func (v *Vertex) IsErr() bool

func (*Vertex) IsList

func (v *Vertex) IsList() bool

func (*Vertex) Kind

func (v *Vertex) Kind() Kind

func (*Vertex) Lookup

func (v *Vertex) Lookup(f Feature) *Vertex

Lookup returns the Arc with label f if it exists or nil otherwise.

func (*Vertex) MatchAndInsert

func (v *Vertex) MatchAndInsert(ctx *OpContext, arc *Vertex)

func (*Vertex) OptionalTypes

func (v *Vertex) OptionalTypes() OptionalType

func (*Vertex) Path

func (v *Vertex) Path() []Feature

Path computes the sequence of Features leading from the root to of the instance to this Vertex.

func (*Vertex) SetValue

func (v *Vertex) SetValue(ctx *OpContext, state VertexStatus, value BaseValue) *Bottom

func (*Vertex) Source

func (v *Vertex) Source() ast.Node

func (*Vertex) Status

func (v *Vertex) Status() VertexStatus

func (*Vertex) ToDataAll

func (v *Vertex) ToDataAll() *Vertex

ToDataAll returns a new v where v and all its descendents contain only the regular fields.

func (*Vertex) ToDataSingle

func (v *Vertex) ToDataSingle() *Vertex

ToDataSingle creates a new Vertex that represents just the regular fields of this vertex. Arcs are left untouched. It is used by cue.Eval to convert nodes to data on per-node basis.

func (*Vertex) UpdateStatus

func (v *Vertex) UpdateStatus(s VertexStatus)

func (*Vertex) Value

func (v *Vertex) Value() Value

Value returns the Value of v without definitions if it is a scalar or itself otherwise.

type VertexStatus

type VertexStatus int8

VertexStatus indicates the evaluation progress of a Vertex.

const (
	// Unprocessed indicates a Vertex has not been processed before.
	// Value must be nil.
	Unprocessed VertexStatus = iota

	// Evaluating means that the current Vertex is being evaluated. If this is
	// encountered it indicates a reference cycle. Value must be nil.
	Evaluating

	// Partial indicates that the result was only partially evaluated. It will
	// need to be fully evaluated to get a complete results.
	//
	// TODO: this currently requires a renewed computation. Cache the
	// nodeContext to allow reusing the computations done so far.
	Partial

	// EvaluatingArcs indicates that the arcs of the Vertex are currently being
	// evaluated. If this is encountered it indicates a structural cycle.
	// Value does not have to be nil
	EvaluatingArcs

	// Finalized means that this node is fully evaluated and that the results
	// are save to use without further consideration.
	Finalized
)

type YieldFunc

type YieldFunc func(env *Environment, s *StructLit)

type Yielder

type Yielder interface {
	Node
	// contains filtered or unexported methods
}

A Yielder represents 0 or more labeled values of structs or lists.

Jump to

Keyboard shortcuts

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