adt

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2023 License: Apache-2.0 Imports: 21 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 referenced 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.

Package eval contains the high level CUE evaluation strategy.

CUE allows for a significant amount of freedom in order of evaluation due to the commutativity of the unification operation. This package implements one of the possible strategies.

Index

Constants

This section is empty.

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.

View Source
var DebugSort int

DebugSort specifies that arcs be sorted consistently between implementations.

0: default
1: sort by Feature: this should be consistent between implementations where
	   there is no change in the compiler and indexing code.
2: alphabetical
View Source
var Verbosity int

Verbosity sets the log level. There are currently only two levels:

0: no logging
1: logging

Functions

func Accept

func Accept(ctx *OpContext, n *Vertex, f Feature) (found, required bool)

Accept determines whether f is allowed in n. It uses the OpContext for caching administrative fields.

func AddStats added in v0.5.0

func AddStats(ctx *OpContext)

AddStats adds the stats of the given OpContext to the global counters.

func AssertConcreteIsPossible

func AssertConcreteIsPossible(op Op, x Expr) bool

Assert that the given expression can evaluate to a concrete value.

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

func DebugSortArcs(c *OpContext, n *Vertex)

func DebugSortFields added in v0.4.3

func DebugSortFields(c *OpContext, a []Feature)

func Equal

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

func HiddenKey added in v0.5.0

func HiddenKey(s, pkgPath string) string

HiddenKey constructs the uniquely identifying string for a hidden fields and its package.

func IsConcrete

func IsConcrete(v Value) bool

IsConcrete returns whether a value is concrete.

func IsDef

func IsDef(x Expr) bool

IsDef reports whether an expressions is a reference that references a definition anywhere in its selection path.

TODO(performance): this should be merged with resolve(). But for now keeping this code isolated makes it easier to see what it is for.

func Pos

func Pos(n Node) token.Pos

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

func TotalStats added in v0.5.0

func TotalStats() stats.Counts

TotalStats returns the aggregate counts of all operations calling AddStats.

Types

type ArcType added in v0.6.0

type ArcType uint8
const (
	// ArcMember means that this arc is a normal non-optional field
	// (including regular, hidden, and definition fields).
	ArcMember ArcType = iota

	// ArcRequired is like optional, but requires that a field be specified.
	// Fields are of the form foo!.
	ArcRequired

	// ArcOptional represents fields of the form foo? and defines constraints
	// for foo in case it is defined.
	ArcOptional

	// ArcPending means that it is not known yet whether an arc exists and that
	// its conjuncts need to be processed to find out. This happens when an arc
	// is provisionally added as part of a comprehension, but when this
	// comprehension has not yet yielded any results.
	ArcPending

	// ArcNotPresent indicates that this arc is not present and, unlike
	// ArcPending, needs no further processing.
	ArcNotPresent
)

func ConstraintFromToken added in v0.6.0

func ConstraintFromToken(t token.Token) ArcType

ConstraintFromToken converts a given AST constraint token to the corresponding ArcType.

func (ArcType) Suffix added in v0.6.0

func (a ArcType) Suffix() string

Suffix reports the field suffix for the given ArcType if it is a constraint or the empty string otherwise.

func (ArcType) Token added in v0.6.0

func (a ArcType) Token() (t token.Token)

Token reports the token corresponding to the constraint represented by a, or token.ILLEGAL otherwise.

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.Node
	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
	// Permanent indicates whether an incomplete error can be
	// resolved later without making the configuration more specific.
	// This may happen when an arc isn't fully resolved yet.
	Permanent    bool
	HasRecursive bool
	ChildError   bool // Err is the error of the child
	NotExists    bool // This error originated from a failed lookup.
	ForCycle     bool // this is a for cycle
	// 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 NewRequiredNotPresentError added in v0.6.0

func NewRequiredNotPresentError(ctx *OpContext, v *Vertex) *Bottom

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

type CloseInfo struct {

	// IsClosed is true if this conjunct represents a single level of closing
	// as indicated by the closed builtin.
	IsClosed bool

	// FromEmbed indicates whether this conjunct was inserted because of an
	// embedding.  This flag is sticky: it will be set for conjuncts created
	// from fields defined by this conjunct.
	// NOTE: only used when using closeContext.
	FromEmbed bool

	// FromDef indicates whether this conjunct was inserted because of a
	// definition. This flag is sticky: it will be set for conjuncts created
	// from fields defined by this conjunct.
	// NOTE: only used when using closeContext.
	FromDef bool

	// FieldTypes indicates which kinds of fields (optional, dynamic, patterns,
	// etc.) are contained in this conjunct.
	FieldTypes OptionalType

	CycleInfo
	// contains filtered or unexported fields
}

TODO: merge with closeInfo: this is a leftover of the refactoring.

func (*CloseInfo) AddPositions

func (c *CloseInfo) AddPositions(ctx *OpContext)

TODO(perf): remove: error positions should always be computed on demand in dedicated error types.

func (CloseInfo) IsInOneOf

func (c CloseInfo) IsInOneOf(t SpanType) bool

IsInOneOf reports whether c is contained within any of the span types in the given mask.

func (CloseInfo) Location

func (c CloseInfo) Location() Node

func (CloseInfo) RootSpanType

func (c CloseInfo) RootSpanType() SpanType

func (CloseInfo) SpawnEmbed

func (c CloseInfo) SpawnEmbed(x Node) CloseInfo

TODO(perf): use on StructInfo. Then if parent and expression are the same it is possible to use cached value.

func (CloseInfo) SpawnGroup

func (c CloseInfo) SpawnGroup(x Expr) CloseInfo

SpawnGroup is used for structs that contain embeddings that may end up closing the struct. This is to force that `b` is not allowed in

a: {#foo} & {b: int}

func (CloseInfo) SpawnRef

func (c CloseInfo) SpawnRef(arc *Vertex, isDef bool, x Expr) CloseInfo

func (CloseInfo) SpawnSpan

func (c CloseInfo) SpawnSpan(x Node, t SpanType) CloseInfo

SpawnSpan is used to track that a value is introduced by a comprehension or constraint. Definition and embedding spans are introduced with SpawnRef and SpawnEmbed, respectively.

type Comprehension added in v0.4.3

type Comprehension struct {
	Syntax ast.Node

	// Clauses is the list of for, if, and other clauses of a comprehension,
	// not including the yielded value (in curly braces).
	Clauses []Yielder

	// Value can be either a StructLit if this is a compiled expression or
	// a Field if this is a computed Comprehension. Value holds a Field,
	// rather than an Expr, in the latter case to preserve as much position
	// information as possible.
	Value Node
	// contains filtered or unexported fields
}

func (*Comprehension) DidResolve added in v0.5.0

func (x *Comprehension) DidResolve() bool

DidResolve reports whether a comprehension was processed and resulted in at least one yielded value.

func (*Comprehension) Envs added in v0.5.0

func (c *Comprehension) Envs() []*Environment

Envs returns all Environments yielded from an evaluated comprehension. Together with the Comprehension value, each Environment represents a result value of the comprehension.

func (*Comprehension) Nest added in v0.5.0

func (c *Comprehension) Nest() int

Nest returns the nesting level of void arcs of this comprehension.

func (*Comprehension) Source added in v0.4.3

func (x *Comprehension) 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
	Format func(Node) string
}

type Conjunct

type Conjunct struct {
	Env *Environment

	// CloseInfo is a unique number that tracks a group of conjuncts that need
	// belong to a single originating definition.
	CloseInfo CloseInfo
	// 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 CloseInfo) 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) Elem added in v0.4.3

func (c *Conjunct) Elem() Elem

Elem retrieves the Elem form of the contained conjunct. If it is a Field, it will return the field value.

func (*Conjunct) Expr

func (c *Conjunct) Expr() Expr

Expr retrieves the expression form of the contained conjunct. If it is a field or comprehension, it will return its associated value.

func (*Conjunct) Field

func (c *Conjunct) Field() Node

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

type Constraints struct {
	// Pairs lists Pattern-Constraint pairs.
	Pairs []PatternConstraint // TODO(perf): move to Arcs?

	// Allowed is a Value that defines the set of all allowed fields.
	// To check if a field is allowed, its correpsonding CUE value can be
	// unified with this value.
	Allowed Value
}

Constraints keeps track of pattern constraints and the set of allowed fields.

type CycleInfo added in v0.5.0

type CycleInfo struct {
	// IsCyclic indicates whether this conjunct, or any of its ancestors,
	// had a violating cycle.
	IsCyclic bool

	// Inline is used to detect expressions referencing themselves, for instance:
	//     {x: out, out: x}.out
	Inline bool

	// TODO(perf): pack this in with CloseInfo. Make an uint32 pointing into
	// a buffer maintained in OpContext, using a mark-release mechanism.
	Refs *RefNode
}

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
	// NumDefaults values are default values.
	Values []Value

	Errors *Bottom // []bottom

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

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

	ArcType ArcType
	Key     Expr
	Value   Expr
}

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

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

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 FieldReference, but with a computed label.

Example: an X referring to

X=(x): v
X="\(x)": v
X=[string]: v

func (*DynamicReference) EvaluateLabel added in v0.5.0

func (x *DynamicReference) EvaluateLabel(ctx *OpContext, env *Environment) Feature

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

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

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

type EvaluatorVersion int
const (
	DefaultVersion EvaluatorVersion = iota

	// The DevVersion is used for new implementations of the evaluator that
	// do not cover all features of the CUE language yet.
	DevVersion
)

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.

func ToExpr added in v0.5.0

func ToExpr(n Node) Expr

ToExpr extracts the underlying expression for a Node. If something is already an Expr, it will return it as is, if it is a field, it will return its value, and for comprehensions it returns the yielded struct.

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

	// MaxIndex indicates the maximum number of unique strings that are used for
	// labels within this CUE implementation.
	MaxIndex = 1<<(32-indexShift) - 1
)

InvalidLabel is an encoding of an erroneous label.

var (
	AnyDefinition Feature = makeLabel(MaxIndex, DefinitionLabel)
	AnyHidden     Feature = makeLabel(MaxIndex, HiddenLabel)
	AnyString     Feature = makeLabel(MaxIndex, StringLabel)
	AnyIndex      Feature = makeLabel(MaxIndex, IntLabel)
)

These labels can be used for wildcard queries.

func LabelFromValue added in v0.6.0

func LabelFromValue(c *OpContext, src Expr, v Value) Feature

func MakeIdentLabel

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

MakeIdentLabel creates a label for the given identifier.

func MakeIntLabel added in v0.5.0

func MakeIntLabel(t FeatureType, i int64) Feature

MakeIntLabel creates an integer label.

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

func MakeLetLabel(r StringIndexer, s string) Feature

MakeLetLabel creates a label for the given let identifier s.

A let declaration is always logically unique within its scope and will never unify with a let field of another struct. This is enforced by ensuring that the let identifier is unique across an entire configuration. This, in turn, is done by adding a unique number to each let identifier.

func MakeNamedLabel added in v0.5.0

func MakeNamedLabel(r StringIndexer, t FeatureType, s string) Feature

MakeNamedLabel creates a feature for the given name and feature type.

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

func (f Feature) IsLet() bool

IsLet reports whether this label is a let field (like `let X = value`).

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

func (f Feature) RawString(index StringIndexer) string

RawString reports the underlying string value of f without interpretation.

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 (
	InvalidLabelType FeatureType = iota
	StringLabel
	IntLabel
	DefinitionLabel
	HiddenLabel
	HiddenDefinitionLabel
	LetLabel
)

func (FeatureType) IsDef

func (f FeatureType) IsDef() bool

func (FeatureType) IsHidden

func (f FeatureType) IsHidden() bool

func (FeatureType) IsLet added in v0.5.0

func (f FeatureType) IsLet() bool

type Field

type Field struct {
	Src *ast.Field

	ArcType ArcType
	Label   Feature
	Value   Expr
}

Field represents a regular field or field constraint with a fixed label. The label 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 FieldInfo

type FieldInfo struct {
	Label Feature
}

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 Flag

type Flag uint16
const (
	// IgnoreOptional allows optional information to be ignored. This only
	// applies when CheckStructural is given.
	IgnoreOptional Flag = 1 << iota

	// CheckStructural indicates that closedness information should be
	// considered for equality. Equal may return false even when values are
	// equal.
	CheckStructural Flag = 1 << iota
)

type ForClause

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

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
}

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.

Example: strings in

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.

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

	CompositKind = StructKind | ListKind
)

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.

Example: an X referring to

[X=Pattern]: b: a

func (*LabelReference) Source

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

type LetClause

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

A LetClause represents a let clause in a comprehension.

let x = y

func (*LetClause) Source

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

type LetField added in v0.5.0

type LetField struct {
	Src   *ast.LetClause
	Label Feature
	// IsMulti is true when this let field should be replicated for each
	// incarnation. This is the case when its expression refers to the
	// variables of a for comprehension embedded within a struct.
	IsMulti bool
	Value   Expr
}

A LetField represents a field that is only visible in the local scope.

let X = expr

func (*LetField) Source added in v0.5.0

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

Example: an X referring to

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

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.Expr
	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 {
	Runtime
	Format func(Node) string

	Version EvaluatorVersion

	// The current call is a validator. A builtin may return a boolean false
	// along with an error message describing a validation error. If the latter
	// is wrapped in an internal.ValidationError, it will only be interpreted
	// as an error if this is true.
	// TODO: strictly separate validators and functions.
	IsValidator bool
	// contains filtered or unexported fields
}

An OpContext implements CUE's unification operation. It only operates on values that are created with the Runtime with which an OpContext is associated. An OpContext is not goroutine safe and only one goroutine may use an OpContext at a time.

func New

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

New creates an operation context.

func NewContext

func NewContext(r Runtime, 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) CloseInfo added in v0.5.0

func (c *OpContext) CloseInfo() CloseInfo

func (*OpContext) Elems

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

Elems returns the evaluated 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) Label

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

func (*OpContext) Logf

func (c *OpContext) Logf(v *Vertex, format string, args ...interface{})

func (*OpContext) Lookup added in v0.5.0

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

Lookup looks up r in env without further resolving the value.

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

func (c *OpContext) PathToString(r Runtime, path []Feature) string

PathToString creates a pretty-printed path of the given list of features.

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

func (c *OpContext) PushConjunct(x Conjunct) (saved frame)

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

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

RawElems returns the elements of the list without evaluating them.

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(x Conjunct, 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) Stats

func (c *OpContext) Stats() *stats.Counts

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.

type OptionalType

type OptionalType int8

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
	HasComplexPattern                          // anything but a basic type
	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 PatternConstraint added in v0.7.0

type PatternConstraint struct {
	Pattern    Value
	Constraint *Vertex
}

A PatternConstraint represents a single

[pattern]: T.

The Vertex holds a list of conjuncts to represent the constraints. We use a Vertex so that these can be evaluated and compared for equality. Unlike for regular Vertex values, CloseInfo.closeContext is set for constraints: it is needed when matching subfields to ensure that conjuncts get inserted into the proper groups.

type RefNode added in v0.5.0

type RefNode struct {
	Ref Resolver
	Arc *Vertex // Ref points to this Vertex

	// Node is the Vertex of which Ref is evaluated as a conjunct.
	// If there is a cyclic reference (not structural cycle), then
	// the reference will have the same node. This allows detecting reference
	// cycles for nodes referring to nodes with an evaluation cycle
	// (mode tracked to Evaluating status). Examples:
	//
	//      a: x
	//      Y: x
	//      x: {Y}
	//
	// and
	//
	//      Y: x.b
	//      a: x
	//      x: b: {Y} | null
	//
	// In both cases there are not structural cycles and thus need to be
	// distinguished from regular structural cycles.
	Node *Vertex

	Next  *RefNode
	Depth int32
}

A RefNode is a linked list of associated references.

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 nil if no import for this package could be found.
	LoadImport(importPath string) *Vertex

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

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

type SpanType uint8

A SpanType is used to indicate whether a CUE value is within the scope of a certain CUE language construct, the span type.

const (
	// EmbeddingSpan means that this value was embedded at some point and should
	// not be included as a possible root node in the todo field of OpContext.
	EmbeddingSpan SpanType = 1 << iota
	ConstraintSpan
	ComprehensionSpan
	DefinitionSpan
)

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

	// NextUniqueID returns a new unique identifier.
	NextUniqueID() uint64
}

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

type StructInfo

type StructInfo struct {
	*StructLit

	Env *Environment

	CloseInfo

	// Embed indicates the struct in which this struct is embedded (originally),
	// or nil if this is a root structure.
	// Embed   *StructInfo
	// Context *RefInfo // the location from which this struct originates.
	Disable bool

	Embedding bool
}

func (*StructInfo) MatchAndInsert

func (o *StructInfo) MatchAndInsert(c *OpContext, arc *Vertex)

MatchAndInsert finds matching optional parts for a given Arc and adds its conjuncts. Bulk fields are only applied if no fields match, and additional constraints are only added if neither regular nor bulk fields match.

type StructLit

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

	// field marks the optional conjuncts of all explicit Fields.
	// Required Fields are marked as empty
	Fields []FieldInfo

	Dynamic []*DynamicField

	// excluded are all literal fields that already exist.
	Bulk []*BulkOptionalField

	Additional []*Ellipsis
	HasEmbed   bool
	IsOpen     bool // has a ...
	// contains filtered or unexported fields
}

A StructLit represents an unevaluated struct literal or file body.

func (*StructLit) HasOptional

func (x *StructLit) HasOptional() bool

func (*StructLit) Init

func (o *StructLit) Init()

func (*StructLit) IsFile

func (o *StructLit) IsFile() bool

func (*StructLit) MarkField

func (o *StructLit) MarkField(f Feature)

TODO: remove this method

func (*StructLit) OptionalTypes

func (o *StructLit) OptionalTypes() OptionalType

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 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, v itself for lists and structs, or nil if v is an undefined type.

type ValueClause

type ValueClause struct {
	Node
	// contains filtered or unexported fields
}

ValueClause represents a wrapper Environment in a chained clause list to account for the unwrapped struct. It is never created by the compiler and serves as a dynamic element only.

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

func (v *ValueError) AddClosedPositions(c CloseInfo)

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

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

A ValueReference represents a lexical reference to a value.

Example: an X referring to

a: X=b

func (*ValueReference) Source added in v0.4.0

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

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

	// Closed indicates whether this Vertex is recursively closed. This is the
	// case, for instance, if it is a node in a definition or if one of the
	// conjuncts, or ancestor conjuncts, is a definition.
	Closed bool

	// MultiLet indicates whether multiple let fields were added from
	// different sources. If true, a LetReference must be resolved using
	// the per-Environment value cache.
	MultiLet bool

	// After this is set, no more arcs may be added during evaluation. This is
	// set, for instance, after a Vertex is used as a source for comprehensions,
	// or any other operation that relies on the set of arcs being constant.
	LockArcs bool

	// IsDynamic signifies whether this struct is computed as part of an
	// expression and not part of the static evaluation tree.
	// Used for cycle detection.
	IsDynamic bool

	// ArcType indicates the level of optionality of this arc.
	ArcType ArcType

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

	// PatternConstraints are additional constraints that match more nodes.
	// Constraints that match existing Arcs already have their conjuncts
	// mixed in.
	// TODO: either put in StructMarker/ListMarker or integrate with Arcs
	// so that this pointer is unnecessary.
	PatternConstraints *Constraints

	// 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 []*StructInfo
	// 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

TODO: return error instead of boolean? (or at least have version that does.)

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

func (v *Vertex) AddStruct(s *StructLit, env *Environment, ci CloseInfo) *StructInfo

func (*Vertex) Clone added in v0.4.1

func (v *Vertex) Clone() *Vertex

func (*Vertex) CompleteArcs added in v0.6.0

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

CompleteArcs ensures the set of arcs has been computed.

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) *Bottom

func (*Vertex) Finalize

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

func (*Vertex) ForceDone added in v0.6.0

func (v *Vertex) ForceDone()

ForceDone prevents v from being evaluated.

func (*Vertex) GetArc

func (v *Vertex) GetArc(c *OpContext, f Feature, t ArcType) (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) Indirect added in v0.4.2

func (v *Vertex) Indirect() *Vertex

Indirect unrolls indirections of Vertex values. These may be introduced, for instance, by temporary bindings such as comprehension values. It returns v itself if v does not point to another Vertex.

func (*Vertex) IsClosedList added in v0.3.1

func (v *Vertex) IsClosedList() bool

func (*Vertex) IsClosedStruct added in v0.3.1

func (v *Vertex) IsClosedStruct() bool

func (*Vertex) IsConcrete

func (x *Vertex) IsConcrete() bool

func (*Vertex) IsConstraint added in v0.6.0

func (v *Vertex) IsConstraint() bool

IsConstraint reports whether the Vertex is an optional or required field.

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

func (v *Vertex) IsDefined(c *OpContext) bool

IsDefined indicates whether this arc is defined meaning it is not a required or optional constraint and not a "void" arc. It will evaluate the arc, and thus evaluate any comprehension, to make this determination.

func (*Vertex) IsErr

func (v *Vertex) IsErr() bool

func (*Vertex) IsInOneOf added in v0.4.0

func (v *Vertex) IsInOneOf(mask SpanType) bool

IsInOneOf reports whether any of the Structs associated with v is contained within any of the span types in the given mask.

func (*Vertex) IsList

func (v *Vertex) IsList() bool

func (*Vertex) IsOptional

func (v *Vertex) IsOptional(label Feature) bool

IsOptional reports whether a field is explicitly defined as optional, as opposed to whether it is allowed by a pattern constraint.

func (*Vertex) IsRecursivelyClosed added in v0.4.0

func (v *Vertex) IsRecursivelyClosed() bool

IsRecursivelyClosed returns true if this value is either a definition or unified with a definition.

func (*Vertex) IsUnprocessed added in v0.6.0

func (v *Vertex) IsUnprocessed() bool

IsUnprocessed reports whether v is unprocessed.

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)

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.

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.

NOTE: this is for debugging purposes only.

func (*Vertex) Rooted added in v0.6.0

func (v *Vertex) Rooted() bool

Rooted reports whether there is a path from the root of the tree to this Vertex.

func (*Vertex) SetValue

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

SetValue sets the value of a node.

func (*Vertex) Source

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

func (*Vertex) Status

func (v *Vertex) Status() vertexStatus

func (*Vertex) ToDataAll

func (v *Vertex) ToDataAll(ctx *OpContext) *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) Value

func (v *Vertex) Value() Value

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

type YieldFunc

type YieldFunc func(env *Environment)

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