go: cuelang.org/go/cue Index | Examples | Files | Directories

package cue

import "cuelang.org/go/cue"

Package cue creates, evaluates and manipulates CUE configurations.



Package Files

ast.go attr.go binop.go build.go builtin.go builtins.go builtinutil.go context.go copy.go debug.go doc.go errors.go eval.go evaluator.go export.go go.go instance.go kind.go lit.go marshal.go op.go rewrite.go strip.go subsume.go types.go validate.go value.go


var (
    // ErrBelow indicates that a value was rounded down in a conversion.
    ErrBelow = errors.New("value was rounded down")

    // ErrAbove indicates that a value was rounded up in a conversion.
    ErrAbove = errors.New("value was rounded up")

    // ErrInfinite indicates that a value is infinite.
    ErrInfinite = errors.New("infinite")

type Attribute Uses

type Attribute struct {
    // contains filtered or unexported fields

An Attribute contains meta data about a field.

func (*Attribute) Err Uses

func (a *Attribute) Err() error

Err returns the error associated with this Attribute or nil if this attribute is valid.

func (*Attribute) Flag Uses

func (a *Attribute) Flag(pos int, key string) (bool, error)

Flag reports whether an entry with the given name exists at position pos or onwards or an error if the attribute is invalid or if the first pos-1 entries are not defined.

func (*Attribute) Int Uses

func (a *Attribute) Int(pos int) (int64, error)

Int reports the integer at the given position or an error if the attribute is invalid, the position does not exist, or the value at the given position is not an integer.

func (*Attribute) Lookup Uses

func (a *Attribute) Lookup(pos int, key string) (val string, found bool, err error)

Lookup searches for an entry of the form key=value from position pos onwards and reports the value if found. It reports an error if the attribute is invalid or if the first pos-1 entries are not defined.

func (*Attribute) String Uses

func (a *Attribute) String(pos int) (string, error)

String reports the possibly empty string value at the given position or an error the attribute is invalid or if the position does not exist.

type FieldInfo Uses

type FieldInfo struct {
    Name  string
    Pos   int
    Value Value

    IsDefinition bool
    IsOptional   bool
    IsHidden     bool

FieldInfo contains information about a struct field.

type Instance Uses

type Instance struct {
    ImportPath string
    Dir        string
    Name       string

    Incomplete bool         // true if Pkg and all its dependencies are free of errors
    Err        errors.Error // non-nil if the package had errors
    // contains filtered or unexported fields

An Instance defines a single configuration based on a collection of underlying CUE files.

func Build Uses

func Build(instances []*build.Instance) []*Instance

Build creates one Instance for each build.Instance. A returned Instance may be incomplete, in which case its Err field is set.


inst := cue.Build(load.Load(args))

func Merge Uses

func Merge(inst ...*Instance) *Instance

Merge unifies the given instances into a single one.

Errors regarding conflicts are included in the result, but not reported, so that these will only surface during manifestation. This allows non-conflicting parts to be used.

func (*Instance) Build Uses

func (inst *Instance) Build(p *build.Instance) *Instance

Build creates a new instance from the build instances, allowing unbound identifier to bind to the top-level field in inst. The top-level fields in inst take precedence over predeclared identifier and builtin functions.

func (*Instance) Doc Uses

func (inst *Instance) Doc() []*ast.CommentGroup

Doc returns the package comments for this instance.

func (*Instance) Eval Uses

func (inst *Instance) Eval(expr ast.Expr) Value

Eval evaluates an expression within an existing instance.

Expressions may refer to builtin packages if they can be uniquely identified.

func (*Instance) Fill Uses

func (inst *Instance) Fill(x interface{}, path ...string) (*Instance, error)

Fill creates a new instance with the values of the old instance unified with the given value. It is not possible to update the emit value.

func (*Instance) Lookup Uses

func (inst *Instance) Lookup(path ...string) Value

Lookup reports the value at a path starting from the top level struct (not the emitted value). The Exists method of the returned value will report false if the path did not exist. The Err method reports if any error occurred during evaluation. The empty path returns the top-level configuration struct, regardless of whether an emit value was specified.

func (*Instance) LookupField Uses

func (inst *Instance) LookupField(path ...string) (f FieldInfo, err error)

LookupField reports a Field at a path starting from v, or an error if the path is not. The empty path returns v itself.

It cannot look up hidden or unexported fields.

func (*Instance) Value Uses

func (inst *Instance) Value() Value

Value returns the root value of the configuration. If the configuration defines in emit value, it will be that value. Otherwise it will be all top-level values.

type Iterator Uses

type Iterator struct {
    // contains filtered or unexported fields

An Iterator iterates over values.

func (*Iterator) IsHidden Uses

func (i *Iterator) IsHidden() bool

IsHidden reports if a field is hidden from the data model.

func (*Iterator) IsOptional Uses

func (i *Iterator) IsOptional() bool

IsOptional reports if a field is optional.

func (*Iterator) Label Uses

func (i *Iterator) Label() string

Label reports the label of the value if i iterates over struct fields and "" otherwise.

func (*Iterator) Next Uses

func (i *Iterator) Next() bool

Next advances the iterator to the next value and reports whether there was any. It must be called before the first call to Value or Key.

func (*Iterator) Value Uses

func (i *Iterator) Value() Value

Value returns the current value in the list. It will panic if Next advanced past the last entry.

type Kind Uses

type Kind int

Kind determines the underlying type of a Value.

const (
    // NullKind indicates a null value.
    NullKind Kind = 1 << iota

    // BoolKind indicates a boolean value.

    // IntKind represents an integral number.

    // FloatKind represents a decimal float point number that cannot be
    // converted to an integer. The underlying number may still be integral,
    // but resulting from an operation that enforces the float type.

    // StringKind indicates any kind of string.

    // BytesKind is a blob of data.

    // StructKind is a kev-value map.

    // ListKind indicates a list of values.

    // NumberKind represents any kind of number.
    NumberKind = IntKind | FloatKind
const BottomKind Kind = 0

func (Kind) String Uses

func (k Kind) String() string

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


will return:


type Op Uses

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








Values of Op.

func (Op) String Uses

func (o Op) String() string

type Option Uses

type Option option

An Option defines modes of evaluation.

func All Uses

func All() Option

All indicates that all fields and values should be included in processing even if they can be elided or omitted.

func Attributes Uses

func Attributes(include bool) Option

Attributes indicates that attributes should be included.

func Concrete Uses

func Concrete(concrete bool) Option

Concrete ensures that all values are concrete.

For Validate this means it returns an error if this is not the case. In other cases a non-concrete value will be replaced with an error.

func Definitions Uses

func Definitions(include bool) Option

Definitions indicates whether definitions should be included.

Definitions may still be included for certain functions if they are referred to by other other values.

func DisallowCycles Uses

func DisallowCycles(disallow bool) Option

DisallowCycles forces validation in the precense of cycles, even if non-concrete values are allowed. This is implied by Concrete(true).

func Hidden Uses

func Hidden(include bool) Option

Hidden indicates that definitions and hidden fields should be included.

Deprecated: Hidden fields are deprecated.

func Optional Uses

func Optional(include bool) Option

Optional indicates that optional fields should be included.

func Raw Uses

func Raw() Option

Raw tells Syntax to generate the value as is without any simplifications.

type Runtime Uses

type Runtime struct {
    // contains filtered or unexported fields

A Runtime is used for creating CUE interpretations.

Any operation that involves two Values or Instances should originate from the same Runtime.

The zero value of a Runtime is ready to use.

func (*Runtime) Build Uses

func (r *Runtime) Build(instance *build.Instance) (*Instance, error)

Build creates an Instance from the given build.Instance. A returned Instance may be incomplete, in which case its Err field is set.

func (*Runtime) Compile Uses

func (r *Runtime) Compile(filename string, source interface{}) (*Instance, error)

Compile compiles the given source into an Instance. The source code may be provided as a string, byte slice, io.Reader. The name is used as the file name in position information. The source may import builtin packages. Use Build to allow importing non-builtin packages.

func (*Runtime) CompileExpr Uses

func (r *Runtime) CompileExpr(expr ast.Expr) (*Instance, error)

CompileExpr compiles the given source expression into an Instance. The source may import builtin packages. Use Build to allow importing non-builtin packages.

func (*Runtime) CompileFile Uses

func (r *Runtime) CompileFile(file *ast.File) (*Instance, error)

CompileFile compiles the given source file into an Instance. The source may import builtin packages. Use Build to allow importing non-builtin packages.

func (*Runtime) FromExpr Uses

func (r *Runtime) FromExpr(expr ast.Expr) (*Instance, error)

FromExpr creates an instance from an expression. Any references must be resolved beforehand.

Deprecated: use CompileExpr

func (*Runtime) Marshal Uses

func (r *Runtime) Marshal(instances ...*Instance) (b []byte, err error)

Marshal creates bytes from a group of instances. Imported instances will be included in the emission.

The stored instances are functionally the same, but preserving of file information is only done on a best-effort basis.

func (*Runtime) Parse Uses

func (r *Runtime) Parse(name string, source interface{}) (*Instance, error)

Parse parses a CUE source value into a CUE Instance. The source code may be provided as a string, byte slice, or io.Reader. The name is used as the file name in position information. The source may import builtin packages.

Deprecated: use Compile


const config = `
	msg:   "Hello \(place)!"
	place: string | *"world"

var r cue.Runtime

instance, err := r.Compile("test", config)
if err != nil {
    // handle error

str, _ := instance.Lookup("msg").String()

instance, _ = instance.Fill("you", "place")
str, _ = instance.Lookup("msg").String()


Hello world!
Hello you!

func (*Runtime) Unmarshal Uses

func (r *Runtime) Unmarshal(b []byte) ([]*Instance, error)

Unmarshal creates an Instance from bytes generated by the MarshalBinary method of an instance.

type Struct Uses

type Struct struct {
    // contains filtered or unexported fields

Struct represents a CUE struct value.

func (*Struct) Field Uses

func (s *Struct) Field(i int) FieldInfo

field reports information about the ith field, i < o.Len().

func (*Struct) FieldByName Uses

func (s *Struct) FieldByName(name string) (FieldInfo, error)

func (*Struct) Fields Uses

func (s *Struct) Fields(opts ...Option) Iterator

Fields creates an iterator over the Struct's fields.

func (*Struct) Len Uses

func (s *Struct) Len() int

type Value Uses

type Value struct {
    // contains filtered or unexported fields

Value holds any value, which may be a Boolean, Error, List, Null, Number, Struct, or String.

func (Value) AppendFloat Uses

func (v Value) AppendFloat(buf []byte, fmt byte, prec int) ([]byte, error)

AppendFloat appends to buf the string form of the floating-point number x. It returns an error if v is not a number.

func (Value) AppendInt Uses

func (v Value) AppendInt(buf []byte, base int) ([]byte, error)

AppendInt appends the string representation of x in the given base to buf and returns the extended buffer, or an error if the underlying number was not an integer.

func (Value) Attribute Uses

func (v Value) Attribute(key string) Attribute

Attribute returns the attribute data for the given key. The returned attribute will return an error for any of its methods if there is no attribute for the requested key.

func (Value) Bool Uses

func (v Value) Bool() (bool, error)

Bool returns the bool value of v or false and an error if v is not a boolean.

func (Value) Bytes Uses

func (v Value) Bytes() ([]byte, error)

Bytes returns a byte slice if v represents a list of bytes or an error otherwise.

func (Value) Decode Uses

func (v Value) Decode(x interface{}) error

Decode initializes x with Value v. If x is a struct, it will validate the constraints specified in the field tags.


type ab struct{ A, B int }

var x ab

var r cue.Runtime

i, _ := r.Compile("test", `{A: 2, B: 4}`)
_ = i.Value().Decode(&x)

i, _ = r.Compile("test", `{B: "foo"}`)
err := i.Value().Decode(&x)


{2 4}
json: cannot unmarshal string into Go struct field ab.B of type int

func (Value) Default Uses

func (v Value) Default() (Value, bool)

Default reports the default value and whether it existed. It returns the normal value if there is no default.

func (Value) Doc Uses

func (v Value) Doc() []*ast.CommentGroup

Doc returns all documentation comments associated with the field from which the current value originates.

func (Value) Elem Uses

func (v Value) Elem() (Value, bool)

Elem returns the value of undefined element types of lists and structs.

func (Value) Equals Uses

func (v Value) Equals(other Value) bool

Equals reports whether two values are equal, ignoring optional fields. The result is undefined for incomplete values.

func (Value) Err Uses

func (v Value) Err() error

Err returns the error represented by v or nil v is not an error.

func (Value) Eval Uses

func (v Value) Eval() Value

Eval resolves the references of a value and returns the result. This method is not necessary to obtain concrete values.

func (Value) Exists Uses

func (v Value) Exists() bool

Exists reports whether this value existed in the configuration.

func (Value) Expr Uses

func (v Value) Expr() (Op, []Value)

Expr reports the operation of the underlying expression and the values it operates on.

For unary expressions, it returns the single value of the expression.

For binary expressions it returns first the left and right value, in that order. For associative operations however, (for instance '&' and '|'), it may return more than two values, where the operation is to be applied in sequence.

For selector and index expressions it returns the subject and then the index. For selectors, the index is the string value of the identifier.

For interpolations it returns a sequence of values to be concatenated, some of which will be literal strings and some unevaluated expressions.

A builtin call expression returns the value of the builtin followed by the args of the call.

func (Value) Fields Uses

func (v Value) Fields(opts ...Option) (Iterator, error)

Fields creates an iterator over v's fields if v is a struct or an error otherwise.

func (Value) Float64 Uses

func (v Value) Float64() (float64, error)

Float64 returns the float64 value nearest to x. It reports an error if v is not a number. If x is too small to be represented by a float64 (|x| < math.SmallestNonzeroFloat64), the result is (0, ErrBelow) or (-0, ErrAbove), respectively, depending on the sign of x. If x is too large to be represented by a float64 (|x| > math.MaxFloat64), the result is (+Inf, ErrAbove) or (-Inf, ErrBelow), depending on the sign of x.

func (Value) Format Uses

func (v Value) Format(state fmt.State, verb rune)

Format prints a debug version of a value.

func (Value) IncompleteKind Uses

func (v Value) IncompleteKind() Kind

IncompleteKind returns a mask of all kinds that this value may be.

func (Value) Int Uses

func (v Value) Int(z *big.Int) (*big.Int, error)

Int converts the underlying integral number to an big.Int. It reports an error if the underlying value is not an integer type. If a non-nil *Int argument z is provided, Int stores the result in z instead of allocating a new Int.

func (Value) Int64 Uses

func (v Value) Int64() (int64, error)

Int64 converts the underlying integral number to int64. It reports an error if the underlying value is not an integer type or cannot be represented as an int64. The result is (math.MinInt64, ErrAbove) for x < math.MinInt64, and (math.MaxInt64, ErrBelow) for x > math.MaxInt64.

func (Value) IsConcrete Uses

func (v Value) IsConcrete() bool

IsConcrete reports whether the current value is a concrete scalar value (not relying on default values), a terminal error, a list, or a struct. It does not verify that values of lists or structs are concrete themselves. To check whether there is a concrete default, use v.Default().IsConcrete().

func (Value) IsIncomplete Uses

func (v Value) IsIncomplete() bool

Deprecated: IsIncomplete

It indicates that the value cannot be fully evaluated due to insufficient information.

func (Value) Kind Uses

func (v Value) Kind() Kind

Kind returns the kind of value. It returns BottomKind for atomic values that are not concrete. For instance, it will return BottomKind for the bounds >=0.

func (Value) Label Uses

func (v Value) Label() (string, bool)

Label reports he label used to obtain this value from the enclosing struct.

TODO: get rid of this somehow. Probably by including a FieldInfo struct or the like.

func (Value) Len Uses

func (v Value) Len() Value

Len returns the number of items of the underlying value. For lists it reports the capacity of the list. For structs it indicates the number of fields, for bytes the number of bytes.

func (Value) List Uses

func (v Value) List() (Iterator, error)

List creates an iterator over the values of a list or reports an error if v is not a list.

func (Value) Lookup Uses

func (v Value) Lookup(path ...string) Value

Lookup reports the value at a path starting from v. The empty path returns v itself.

The Exists() method can be used to verify if the returned value existed. Lookup cannot be used to look up hidden or optional fields or definitions.

func (Value) LookupField Uses

func (v Value) LookupField(path string) (FieldInfo, error)

LookupField reports information about a field of v.

func (Value) MantExp Uses

func (v Value) MantExp(mant *big.Int) (exp int, err error)

MantExp breaks x into its mantissa and exponent components and returns the exponent. If a non-nil mant argument is provided its value is set to the mantissa of x. The components satisfy x == mant × 10**exp. It returns an error if v is not a number.

The components are not normalized. For instance, 2.00 is represented mant == 200 and exp == -2. Calling MantExp with a nil argument is an efficient way to get the exponent of the receiver.

func (Value) MarshalJSON Uses

func (v Value) MarshalJSON() (b []byte, err error)

MarshalJSON marshalls this value into valid JSON.

func (Value) Null Uses

func (v Value) Null() error

Null reports an error if v is not null.

func (Value) Pos Uses

func (v Value) Pos() token.Pos

Pos returns position information.

func (Value) Reader Uses

func (v Value) Reader() (io.Reader, error)

Reader returns a new Reader if v is a string or bytes type and an error otherwise.

func (Value) Reference Uses

func (v Value) Reference() (inst *Instance, path []string)

Reference returns the instance and path referred to by this value such that inst.Lookup(path) resolves to the same value, or no path if this value is not a reference. If a reference contains index selection (foo[bar]), it will only return a reference if the index resolves to a concrete value.

func (Value) References Uses

func (v Value) References() [][]string

References reports all references used to evaluate this value. It does not report references for sub fields if v is a struct.

Deprecated: can be implemented in terms of Reference and Expr.

func (Value) Source Uses

func (v Value) Source() ast.Node

Source returns the original node for this value. The return value may not be a syntax.Expr. For instance, a struct kind may be represented by a struct literal, a field comprehension, or a file. It returns nil for computed nodes. Use Split to get all source values that apply to a field.

func (Value) Split Uses

func (v Value) Split() []Value

Split returns a list of values from which v originated such that the unification of all these values equals v and for all returned values. It will also split unchecked unifications (embeddings), so unifying the split values may fail if actually unified. Source returns a non-nil value.

Deprecated: use Expr.

func (Value) String Uses

func (v Value) String() (string, error)

String returns the string value if v is a string or an error otherwise.

func (Value) Struct Uses

func (v Value) Struct(opts ...Option) (*Struct, error)

Struct returns the underlying struct of a value or an error if the value is not a struct.

func (Value) Subsumes Uses

func (v Value) Subsumes(w Value) bool

Subsumes reports whether w is an instance of v.

Value v and w must be obtained from the same build. TODO: remove this requirement.


// Check compatibility of successive APIs.
var r cue.Runtime

inst, err := r.Compile("apis", `
	// Release notes:
	// - You can now specify your age and your hobby!
	V1 :: {
		age:   >=0 & <=100
		hobby: string

	// Release notes:
	// - People get to be older than 100, so we relaxed it.
	// - It seems not many people have a hobby, so we made it optional.
	V2 :: {
		age:    >=0 & <=150 // people get older now
		hobby?: string      // some people don't have a hobby

	// Release notes:
	// - Actually no one seems to have a hobby nowadays anymore,
	//   so we dropped the field.
	V3 :: {
		age: >=0 & <=150

if err != nil {
    // handle error
v1, err1 := inst.LookupField("V1")
v2, err2 := inst.LookupField("V2")
v3, err3 := inst.LookupField("V3")
if err1 != nil || err2 != nil || err3 != nil {
    log.Println(err1, err2, err3)

// Is V2 backwards compatible with V1? In other words, does V2 subsume V1?
pass := v2.Value.Subsumes(v1.Value)
fmt.Println("V2 is backwards compatible with V1:", pass)

pass = v3.Value.Subsumes(v2.Value)
fmt.Println("V3 is backwards compatible with V2:", pass)


V2 is backwards compatible with V1: true
V3 is backwards compatible with V2: false

func (Value) Syntax Uses

func (v Value) Syntax(opts ...Option) ast.Node

Syntax converts the possibly partially evaluated value into syntax. This can use used to print the value with package format.

func (Value) Template Uses

func (v Value) Template() func(label string) Value

Template returns a function that represents the template definition for a struct in a configuration file. It returns nil if v is not a struct kind or if there is no template associated with the struct.

The returned function returns the value that would be unified with field given its name.

func (Value) Uint64 Uses

func (v Value) Uint64() (uint64, error)

Uint64 converts the underlying integral number to uint64. It reports an error if the underlying value is not an integer type or cannot be represented as a uint64. The result is (0, ErrAbove) for x < 0, and (math.MaxUint64, ErrBelow) for x > math.MaxUint64.

func (Value) Unify Uses

func (v Value) Unify(w Value) Value

Unify reports the greatest lower bound of v and w.

Value v and w must be obtained from the same build. TODO: remove this requirement.

func (Value) Validate Uses

func (v Value) Validate(opts ...Option) error

Validate reports any errors, recursively. The returned error may represent more than one error, retrievable with errors.Errors, if more than one exists.

func (Value) Walk Uses

func (v Value) Walk(before func(Value) bool, after func(Value))

Walk descends into all values of v, calling f. If f returns false, Walk will not descent further. It only visits values that are part of the data model, so this excludes optional fields, hidden fields, and definitions.


astPackage ast declares the types used to represent syntax trees for CUE packages.
buildPackage build defines data types and utilities for defining CUE configuration instances.
encodingPackage encoding provides support for managing data format files supported by CUE.
errorsPackage errors defines shared types for handling CUE errors.
formatPackage format implements standard formatting of CUE configurations.
literalPackage literal implements conversions to and from string representations of basic data types.
loadPackage load loads CUE instances.
parserPackage parser implements a parser for CUE source files.
scannerPackage scanner implements a scanner for CUE source text.
tokenPackage token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).

Package cue imports 47 packages (graph) and is imported by 48 packages. Updated 2020-01-24. Refresh now. Tools for package owners.