...

Package cue

import "cuelang.org/go/cue"
Overview
Index
Examples
Subdirectories

Overview ▾

Package cue is the main API for CUE evaluation.

Value is the main type that represents CUE evaluations. Values are created with a [cuecontext.Context]. Only values created from the same Context can be involved in the same operation. Values created from the same Context are not safe for concurrent use, which we intend to change in the future.

A Context defines the set of active packages, the translations of field names to unique codes, as well as the set of builtins. Use

import "cuelang.org/go/cue/cuecontext"

ctx := cuecontext.New()

to obtain a context.

Note that the following types are DEPRECATED and their usage should be avoided if possible:

[FieldInfo]
[Instance]
[Runtime]
[Struct]

Many types also have deprecated methods. Code that already uses deprecated methods can keep using them for at least some time. We aim to provide a go or cue fix solution to automatically rewrite code using the new API.

Index ▾

Variables
type AttrKind
type Attribute
    func (a *Attribute) Arg(i int) (key, value string)
    func (a *Attribute) Contents() string
    func (a *Attribute) Err() error
    func (a *Attribute) Flag(pos int, key string) (bool, error)
    func (a Attribute) Format(w fmt.State, verb rune)
    func (a *Attribute) Int(pos int) (int64, error)
    func (a *Attribute) Kind() AttrKind
    func (a *Attribute) Lookup(pos int, key string) (val string, found bool, err error)
    func (a *Attribute) Name() string
    func (a *Attribute) NumArgs() int
    func (a *Attribute) RawArg(i int) string
    func (a *Attribute) String(pos int) (string, error)
type BuildOption
    func Filename(filename string) BuildOption
    func ImportPath(path string) BuildOption
    func InferBuiltins(elide bool) BuildOption
    func Scope(scope Value) BuildOption
type Context
    func (c *Context) BuildExpr(x ast.Expr, options ...BuildOption) Value
    func (c *Context) BuildFile(f *ast.File, options ...BuildOption) Value
    func (c *Context) BuildInstance(i *build.Instance, options ...BuildOption) Value
    func (c *Context) BuildInstances(instances []*build.Instance) ([]Value, error)
    func (c *Context) CompileBytes(b []byte, options ...BuildOption) Value
    func (c *Context) CompileString(src string, options ...BuildOption) Value
    func (c *Context) Encode(x interface{}, option ...EncodeOption) Value
    func (c *Context) EncodeType(x interface{}, option ...EncodeOption) Value
    func (c *Context) NewList(v ...Value) Value
type EncodeOption
    func NilIsAny(isAny bool) EncodeOption
type FieldInfo
type Instance
    func Build(instances []*build.Instance) []*Instance
    func Merge(inst ...*Instance) *Instance
    func (inst *Instance) ID() string
    func (inst *Instance) Value() Value
type InstanceOrValue
type Iterator
    func (i *Iterator) FieldType() SelectorType
    func (i *Iterator) IsOptional() bool
    func (i *Iterator) Next() bool
    func (i *Iterator) Selector() Selector
    func (i *Iterator) Value() Value
type Kind
type Op
type Option
    func All() Option
    func Attributes(include bool) Option
    func Concrete(concrete bool) Option
    func Definitions(include bool) Option
    func DisallowCycles(disallow bool) Option
    func Docs(include bool) Option
    func ErrorsAsValues(show bool) Option
    func Final() Option
    func Hidden(include bool) Option
    func InlineImports(expand bool) Option
    func Optional(include bool) Option
    func Raw() Option
    func ResolveReferences(resolve bool) Option
    func Schema() Option
type Path
    func MakePath(selectors ...Selector) Path
    func ParsePath(s string) Path
    func (p Path) Err() error
    func (p Path) Optional() Path
    func (p Path) Selectors() []Selector
    func (p Path) String() string
type Runtime
    func (r *Runtime) Marshal(values ...InstanceOrValue) (b []byte, err error)
    func (r *Runtime) Unmarshal(b []byte) ([]*Instance, error)
type Selector
    func Def(s string) Selector
    func Hid(name, pkg string) Selector
    func Index(x int) Selector
    func Label(label ast.Label) Selector
    func Str(s string) Selector
    func (sel Selector) ConstraintType() SelectorType
    func (sel Selector) Index() int
    func (sel Selector) IsConstraint() bool
    func (sel Selector) IsDefinition() bool
    func (sel Selector) IsString() bool
    func (sel Selector) LabelType() SelectorType
    func (sel Selector) Optional() Selector
    func (sel Selector) PkgPath() string
    func (sel Selector) Required() Selector
    func (sel Selector) String() string
    func (sel Selector) Type() SelectorType
    func (sel Selector) Unquoted() string
type SelectorType
    func (t SelectorType) ConstraintType() SelectorType
    func (t SelectorType) IsDefinition() bool
    func (t SelectorType) IsHidden() bool
    func (t SelectorType) LabelType() SelectorType
    func (t SelectorType) String() string
type Struct
type Value
    func Dereference(v Value) Value
    func (v Value) Allows(sel Selector) bool
    func (v Value) AppendFloat(buf []byte, fmt byte, prec int) ([]byte, error)
    func (v Value) AppendInt(buf []byte, base int) ([]byte, error)
    func (v Value) Attribute(key string) Attribute
    func (v Value) Attributes(mask AttrKind) []Attribute
    func (v Value) Bool() (bool, error)
    func (v Value) BuildInstance() *build.Instance
    func (v Value) Bytes() ([]byte, error)
    func (v Value) Context() *Context
    func (v Value) Decode(x interface{}) error
    func (v Value) Default() (Value, bool)
    func (v Value) Doc() []*ast.CommentGroup
    func (v Value) Equals(other Value) bool
    func (v Value) Err() error
    func (v Value) Eval() Value
    func (v Value) Exists() bool
    func (v Value) Expr() (Op, []Value)
    func (v Value) Fields(opts ...Option) (*Iterator, error)
    func (v Value) FillPath(p Path, x interface{}) Value
    func (v Value) Float64() (float64, error)
    func (v Value) Format(state fmt.State, verb rune)
    func (v Value) IncompleteKind() Kind
    func (v Value) Int(z *big.Int) (*big.Int, error)
    func (v Value) Int64() (int64, error)
    func (v Value) IsConcrete() bool
    func (v Value) Kind() Kind
    func (v Value) Len() Value
    func (v Value) List() (Iterator, error)
    func (v Value) LookupPath(p Path) Value
    func (v Value) MantExp(mant *big.Int) (exp int, err error)
    func (v Value) MarshalJSON() (b []byte, err error)
    func (v Value) Null() error
    func (v Value) Path() Path
    func (v Value) Pos() token.Pos
    func (v Value) ReferencePath() (root Value, p Path)
    func (v Value) Source() ast.Node
    func (v Value) String() (string, error)
    func (v Value) Subsume(w Value, opts ...Option) error
    func (v Value) Syntax(opts ...Option) ast.Node
    func (v Value) Uint64() (uint64, error)
    func (v Value) Unify(w Value) Value
    func (v Value) UnifyAccept(w Value, accept Value) Value
    func (v Value) Validate(opts ...Option) error
    func (v Value) Walk(before func(Value) bool, after func(Value))

Examples

Context
Hid
Value.Allows
Value.Format

Package files

attribute.go build.go builtin.go context.go cue.go decode.go errors.go format.go instance.go marshal.go op.go path.go query.go types.go

Variables

var (

    // AnyIndex can be used to ask for any index.
    //
    // In paths it is used to select constraints that apply to all elements.
    AnyIndex = anyIndex

    // AnyString can be used to ask for any regular string field.
    //
    // In paths it is used to select constraints that apply to all elements.
    AnyString = anyString
)
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 AttrKind

AttrKind indicates the location of an attribute within CUE source.

type AttrKind int
const (
    // FieldAttr indicates a field attribute.
    // foo: bar @attr()
    FieldAttr AttrKind = AttrKind(internal.FieldAttr)

    // DeclAttr indicates a declaration attribute.
    // foo: {
    //     @attr()
    // }
    DeclAttr AttrKind = AttrKind(internal.DeclAttr)

    // A ValueAttr is a bit mask to request any attribute that is locally
    // associated with a field, instead of, for instance, an entire file.
    ValueAttr AttrKind = FieldAttr | DeclAttr
)

type Attribute

An Attribute contains metadata about a field.

By convention, an attribute is split into positional arguments according to the rules below. However, these are not mandatory. To access the raw contents of an attribute, use Attribute.Contents.

Arguments are of the form key[=value] where key and value each consist of an arbitrary number of CUE tokens with balanced brackets ((), [], and {}). These are the arguments retrieved by the Attribute methods.

Leading and trailing white space will be stripped from both key and value. If there is no value and the key consists of exactly one quoted string, it will be unquoted.

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

func (*Attribute) Arg

func (a *Attribute) Arg(i int) (key, value string)

Arg reports the contents of the ith comma-separated argument of a.

If the argument contains an unescaped equals sign, it returns a key-value pair. Otherwise it returns the contents in key.

func (*Attribute) Contents

func (a *Attribute) Contents() string

Contents reports the full contents of an attribute within parentheses, so contents in @attr(contents).

func (*Attribute) Err

func (a *Attribute) Err() error

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

func (*Attribute) Flag

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

func (a Attribute) Format(w fmt.State, verb rune)

Format implements fmt.Formatter.

func (*Attribute) Int

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

func (a *Attribute) Kind() AttrKind

Kind reports the type of location within CUE source where the attribute was specified.

func (*Attribute) Lookup

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

func (a *Attribute) Name() string

Name returns the name of the attribute, for instance, "json" for @json(...).

func (*Attribute) NumArgs

func (a *Attribute) NumArgs() int

NumArgs reports the number of arguments parsed for this attribute.

func (*Attribute) RawArg

func (a *Attribute) RawArg(i int) string

RawArg reports the raw contents of the ith comma-separated argument of a, including surrounding spaces.

func (*Attribute) String

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 BuildOption

A BuildOption defines options for the various build-related methods of Context.

type BuildOption func(o *runtime.Config)

func Filename

func Filename(filename string) BuildOption

Filename assigns a filename to parsed content.

func ImportPath

func ImportPath(path string) BuildOption

ImportPath defines the import path to use for building CUE. The import path influences the scope in which identifiers occurring in the input CUE are defined. Passing the empty string is equal to not specifying this option.

This option is typically not necessary when building using a build.Instance, but takes precedence otherwise.

func InferBuiltins

func InferBuiltins(elide bool) BuildOption

InferBuiltins allows unresolved references to bind to builtin packages with a unique package name.

This option is intended for evaluating expressions in a context where import statements cannot be used. It is not recommended to use this for evaluating CUE files.

func Scope

func Scope(scope Value) BuildOption

Scope defines a context in which to resolve unresolved identifiers.

Only one scope may be given. It panics if more than one scope is given or if the Context in which scope was created differs from the one where this option is used.

type Context

A Context is used for creating CUE Values.

A Context keeps track of loaded instances, indices of internal representations of values, and defines the set of supported builtins. Any operation that involves two Values should originate from the same Context.

Use

ctx := cuecontext.New()

to create a new Context.

type Context runtime.Runtime

Example

Code:

package cue_test

import (
    "fmt"

    "cuelang.org/go/cue"
    "cuelang.org/go/cue/cuecontext"
)

func ExampleContext() {
    ctx := cuecontext.New()

    v := ctx.CompileString(`
        a: 2
        b: 3
        "a+b": a + b
    `)

    p("lookups")
    p("a:     %v", v.LookupPath(cue.ParsePath("a")))
    p("b:     %v", v.LookupPath(cue.ParsePath("b")))
    p(`"a+b": %v`, v.LookupPath(cue.ParsePath(`"a+b"`)))
    p("")
    p("expressions")
    p("a + b: %v", ctx.CompileString("a + b", cue.Scope(v)))
    p("a * b: %v", ctx.CompileString("a * b", cue.Scope(v)))

    // Output:
    // lookups
    // a:     2
    // b:     3
    // "a+b": 5
    //
    // expressions
    // a + b: 5
    // a * b: 6
}

func p(format string, args ...interface{}) {
    fmt.Printf(format+"\n", args...)
}

func (*Context) BuildExpr

func (c *Context) BuildExpr(x ast.Expr, options ...BuildOption) Value

BuildExpr creates a Value from x.

The returned Value will represent an error, accessible through Err, if any error occurred.

func (*Context) BuildFile

func (c *Context) BuildFile(f *ast.File, options ...BuildOption) Value

BuildFile creates a Value from f.

The returned Value will represent an error, accessible through Err, if any error occurred.

func (*Context) BuildInstance

func (c *Context) BuildInstance(i *build.Instance, options ...BuildOption) Value

BuildInstance creates a Value from the given build.Instance.

The returned Value will represent an error, accessible through Err, if any error occurred.

func (*Context) BuildInstances

func (c *Context) BuildInstances(instances []*build.Instance) ([]Value, error)

BuildInstances creates a Value for each of the given instances and reports the combined errors or nil if there were no errors.

func (*Context) CompileBytes

func (c *Context) CompileBytes(b []byte, options ...BuildOption) Value

CompileBytes parses and build a Value from the given source bytes.

The returned Value will represent an error, accessible through Err, if any error occurred.

func (*Context) CompileString

func (c *Context) CompileString(src string, options ...BuildOption) Value

CompileString parses and build a Value from the given source string.

The returned Value will represent an error, accessible through Err, if any error occurred.

func (*Context) Encode

func (c *Context) Encode(x interface{}, option ...EncodeOption) Value

Encode converts a Go value to a CUE value.

The returned Value will represent an error, accessible through Err, if any error occurred.

Encode traverses the value v recursively. If an encountered value implements the json.Marshaler interface and is not a nil pointer, Encode calls its MarshalJSON method to produce JSON and convert that to CUE instead. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Encode calls its MarshalText method and encodes the result as a string.

Otherwise, Encode uses the following type-dependent default encodings:

Boolean values encode as CUE booleans.

Floating point, integer, and *big.Int and *big.Float values encode as CUE numbers.

String values encode as CUE strings coerced to valid UTF-8, replacing sequences of invalid bytes with the Unicode replacement rune as per Unicode's and W3C's recommendation.

Array and slice values encode as CUE lists, except that []byte encodes as a bytes value, and a nil slice encodes as the null.

Struct values encode as CUE structs. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

See the documentation for Go's json.Marshal for more details on the field tags and their meaning.

Anonymous struct fields are usually encoded as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

The Go visibility rules for struct fields are amended for when deciding which field to encode or decode. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:

1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.

2) If there is exactly one field (tagged or not according to the first rule), that is selected.

3) Otherwise there are multiple fields, and all are ignored; no error occurs.

Map values encode as CUE structs. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as CUE struct field names by applying the following rules, subject to the UTF-8 coercion described for string values above:

Pointer values encode as the value pointed to. A nil pointer encodes as the null CUE value.

Interface values encode as the value contained in the interface. A nil interface value encodes as the null CUE value. The NilIsAny EncodingOption can be used to interpret nil as any (_) instead.

Channel, complex, and function values cannot be encoded in CUE. Attempting to encode such a value results in the returned value being an error, accessible through the Err method.

func (*Context) EncodeType

func (c *Context) EncodeType(x interface{}, option ...EncodeOption) Value

Encode converts a Go type to a CUE value.

The returned Value will represent an error, accessible through Err, if any error occurred.

func (*Context) NewList

func (c *Context) NewList(v ...Value) Value

NewList creates a Value that is a list of the given values.

All Values must be created by c.

type EncodeOption

An EncodeOption defines options for the various encoding-related methods of Context.

type EncodeOption func(*encodeOptions)

func NilIsAny

func NilIsAny(isAny bool) EncodeOption

NilIsAny indicates whether a nil value is interpreted as null or _.

The default is to interpret nil as _.

type FieldInfo

FieldInfo contains information about a struct field.

Deprecated: only used by deprecated functions.

type FieldInfo struct {
    Selector string
    Name     string // Deprecated: use Selector
    Pos      int
    Value    Value

    SelectorType SelectorType

    IsDefinition bool
    IsOptional   bool
    IsHidden     bool
}

type Instance

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

Use of this type is being phased out in favor of Value. Any APIs currently taking an Instance should use InstanceOrValue to transition to the new type without breaking users.

type Instance struct {
    ImportPath  string
    Dir         string
    PkgName     string
    DisplayName 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
}

func Build

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

Deprecated: use Context.BuildInstances. The use of Instance is being phased out.

func Merge

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

DO NOT USE.

Deprecated: do not use.

func (*Instance) ID

func (inst *Instance) ID() string

ID returns the package identifier that uniquely qualifies module and package name.

func (*Instance) Value

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 InstanceOrValue

An InstanceOrValue is implemented by Value and *Instance.

This is a placeholder type that is used to allow Instance-based APIs to transition to Value-based APIs. The goals is to get rid of the Instance type before v1.0.0.

type InstanceOrValue interface {
    Value() Value
    // contains filtered or unexported methods
}

type Iterator

An Iterator iterates over values.

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

func (*Iterator) FieldType

func (i *Iterator) FieldType() SelectorType

FieldType reports the type of the field.

func (*Iterator) IsOptional

func (i *Iterator) IsOptional() bool

IsOptional reports if a field is optional.

func (*Iterator) Next

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

func (i *Iterator) Selector() Selector

Selector reports the field label of this iteration.

func (*Iterator) Value

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

Kind determines the underlying type of a Value.

type Kind = adt.Kind
const (
    // BottomKind represents the bottom value.
    BottomKind Kind = adt.BottomKind

    // NullKind indicates a null value.
    NullKind Kind = adt.NullKind

    // BoolKind indicates a boolean value.
    BoolKind Kind = adt.BoolKind

    // IntKind represents an integral number.
    IntKind Kind = adt.IntKind

    // 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.
    FloatKind Kind = adt.FloatKind

    // StringKind indicates any kind of string.
    StringKind Kind = adt.StringKind

    // BytesKind is a blob of data.
    BytesKind Kind = adt.BytesKind

    // StructKind is a kev-value map.
    StructKind Kind = adt.StructKind

    // ListKind indicates a list of values.
    ListKind Kind = adt.ListKind

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

    // TopKind represents the top value.
    TopKind Kind = adt.TopKind
)

type Op

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

type Op = adt.Op

Values of Op.

const (
    NoOp Op = adt.NoOp

    AndOp Op = adt.AndOp
    OrOp  Op = adt.OrOp

    SelectorOp Op = adt.SelectorOp
    IndexOp    Op = adt.IndexOp
    SliceOp    Op = adt.SliceOp
    CallOp     Op = adt.CallOp

    BooleanAndOp Op = adt.BoolAndOp
    BooleanOrOp  Op = adt.BoolOrOp

    EqualOp            Op = adt.EqualOp
    NotOp              Op = adt.NotOp
    NotEqualOp         Op = adt.NotEqualOp
    LessThanOp         Op = adt.LessThanOp
    LessThanEqualOp    Op = adt.LessEqualOp
    GreaterThanOp      Op = adt.GreaterThanOp
    GreaterThanEqualOp Op = adt.GreaterEqualOp

    RegexMatchOp    Op = adt.MatchOp
    NotRegexMatchOp Op = adt.NotMatchOp

    AddOp           Op = adt.AddOp
    SubtractOp      Op = adt.SubtractOp
    MultiplyOp      Op = adt.MultiplyOp
    FloatQuotientOp Op = adt.FloatQuotientOp
    IntQuotientOp   Op = adt.IntQuotientOp
    IntRemainderOp  Op = adt.IntRemainderOp
    IntDivideOp     Op = adt.IntDivideOp
    IntModuloOp     Op = adt.IntModuloOp

    InterpolationOp Op = adt.InterpolationOp
)

type Option

An Option defines modes of evaluation.

type Option option

func All

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

func Attributes(include bool) Option

Attributes indicates that attributes should be included.

func Concrete

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

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

func DisallowCycles

func DisallowCycles(disallow bool) Option

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

func Docs

func Docs(include bool) Option

Docs indicates whether docs should be included.

func ErrorsAsValues

func ErrorsAsValues(show bool) Option

ErrorsAsValues treats errors as a regular value, including them at the location in the tree where they occur, instead of interpreting them as a configuration-wide failure that is returned instead of root value. Used by Syntax.

func Final

func Final() Option

Final indicates a value is final. It implicitly closes all structs and lists in a value and selects defaults.

func Hidden

func Hidden(include bool) Option

Hidden indicates that definitions and hidden fields should be included.

func InlineImports

func InlineImports(expand bool) Option

InlineImports causes references to values within imported packages to be inlined. References to builtin packages are not inlined.

func Optional

func Optional(include bool) Option

Optional indicates that optional fields should be included.

func Raw

func Raw() Option

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

func ResolveReferences

func ResolveReferences(resolve bool) Option

ResolveReferences forces the evaluation of references when outputting.

Deprecated: Syntax will now always attempt to resolve dangling references and make the output self-contained. When Final or Concrete are used, it will already attempt to resolve all references. See also InlineImports.

func Schema

func Schema() Option

Schema specifies the input is a Schema. Used by Subsume.

type Path

A Path is series of selectors to query a CUE value.

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

func MakePath

func MakePath(selectors ...Selector) Path

MakePath creates a Path from a sequence of selectors.

func ParsePath

func ParsePath(s string) Path

ParsePath parses a CUE expression into a Path. Any error resulting from this conversion can be obtained by calling Err on the result.

Unlike with normal CUE expressions, the first element of the path may be a string literal.

A path may not contain hidden fields. To create a path with hidden fields, use MakePath and Ident.

func (Path) Err

func (p Path) Err() error

Err reports errors that occurred when generating the path.

func (Path) Optional

func (p Path) Optional() Path

Optional returns the optional form of a Path. For instance,

foo.bar  --> foo?.bar?

func (Path) Selectors

func (p Path) Selectors() []Selector

Selectors reports the individual selectors of a path.

func (Path) String

func (p Path) String() string

String reports the CUE representation of p.

type Runtime

A Runtime is used for creating CUE Values.

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

The zero value of Runtime works for legacy reasons, but should not be used. It may panic at some point.

Deprecated: use Context.

type Runtime runtime.Runtime

func (*Runtime) Marshal

func (r *Runtime) Marshal(values ...InstanceOrValue) (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) Unmarshal

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

Unmarshal returns a slice of instances from bytes generated by Runtime.Marshal.

type Selector

A Selector is a component of a path.

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

func Def

func Def(s string) Selector

A Def marks a string as a definition label. An # will be added if a string is not prefixed with a #. It will panic if s cannot be written as a valid identifier.

func Hid

func Hid(name, pkg string) Selector

Hid returns a selector for a hidden field. It panics if pkg is empty. Hidden fields are scoped by package, and pkg indicates for which package the hidden field must apply. For anonymous packages, it must be set to "_".

Example

Code:

const file = `
-- cue.mod/module.cue --
module: "mod.test"

-- main.cue --
import "mod.test/foo:bar"

bar
_foo: int // scoped in main (anonymous) package
baz: _foo

-- foo/bar.cue --
package bar

_foo: int // scoped within imported package
bar: _foo
`

v := load(file).Value()

v = v.FillPath(cue.MakePath(cue.Hid("_foo", "mod.test/foo:bar")), 1)
v = v.FillPath(cue.MakePath(cue.Hid("_foo", "_")), 2)
fmt.Println(v.LookupPath(cue.ParsePath("bar")).Int64())
fmt.Println(v.LookupPath(cue.ParsePath("baz")).Int64())

Output:

1 <nil>
2 <nil>

func Index

func Index(x int) Selector

An Index selects a list element by index.

func Label

func Label(label ast.Label) Selector

Label converts an AST label to a Selector.

func Str

func Str(s string) Selector

A Str is a CUE string label. Definition selectors are defined with Def.

func (Selector) ConstraintType

func (sel Selector) ConstraintType() SelectorType

ConstraintType returns the type of the constraint part of a selector.

func (Selector) Index

func (sel Selector) Index() int

Index returns the index of the selector. It panics unless sel.Type is IndexLabel.

func (Selector) IsConstraint

func (sel Selector) IsConstraint() bool

IsConstraint reports whether s is optional or a pattern constraint. Fields that are constraints are considered non-existing and their values may be erroneous for a configuration to be valid..

func (Selector) IsDefinition

func (sel Selector) IsDefinition() bool

IsDefinition reports whether sel is a non-hidden definition and non-constraint label type.

func (Selector) IsString

func (sel Selector) IsString() bool

IsString reports whether sel represents an optional, required, or regular member field.

func (Selector) LabelType

func (sel Selector) LabelType() SelectorType

LabelType returns the type of the label part of a selector.

func (Selector) Optional

func (sel Selector) Optional() Selector

Optional converts sel into an optional constraint equivalent. It's a no-op if the selector is already optional.

foo  -> foo?
foo! -> foo?

func (Selector) PkgPath

func (sel Selector) PkgPath() string

PkgPath reports the package path associated with a hidden label or "" if this is not a hidden label.

func (Selector) Required

func (sel Selector) Required() Selector

Required converts sel into a required constraint equivalent. It's a no-op if the selector is already a required constraint.

foo  -> foo!
foo? -> foo!

func (Selector) String

func (sel Selector) String() string

String reports the CUE representation of a selector.

func (Selector) Type

func (sel Selector) Type() SelectorType

Type returns the type of the selector.

func (Selector) Unquoted

func (sel Selector) Unquoted() string

Unquoted returns the unquoted value of a string label. It panics unless sel.LabelType is StringLabel and has a concrete name.

type SelectorType

SelectorType represents the kind of a selector. It indicates both the label type as well as whether it is a constraint or an actual value.

type SelectorType uint16
const (
    // StringLabel represents a regular non-definition field.
    StringLabel SelectorType = 1 << iota
    // IndexLabel represents a numeric index into an array.
    IndexLabel
    // DefinitionLabel represents a definition.
    DefinitionLabel
    // HiddenLabel represents a hidden non-definition field.
    HiddenLabel
    // HiddenDefinitionLabel represents a hidden definition.
    HiddenDefinitionLabel

    // OptionalConstraint represents an optional constraint (?).
    OptionalConstraint
    // RequiredConstraint represents a required constraint (!).
    RequiredConstraint
    // PatternConstraint represents a selector of fields in a struct
    // or array that match a constraint.
    PatternConstraint

    InvalidSelectorType SelectorType = 0
)

func (SelectorType) ConstraintType

func (t SelectorType) ConstraintType() SelectorType

ConstraintType reports the constraint type of t.

func (SelectorType) IsDefinition

func (t SelectorType) IsDefinition() bool

IsDefinition reports whether t describes a definition, regardless of whether or not this is a constraint.

func (SelectorType) IsHidden

func (t SelectorType) IsHidden() bool

IsHidden reports whether t describes a hidden field, regardless of whether or not this is a constraint.

func (SelectorType) LabelType

func (t SelectorType) LabelType() SelectorType

LabelType reports the label type of t.

func (SelectorType) String

func (t SelectorType) String() string

type Struct

Struct represents a CUE struct value.

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

type Value

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

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

func Dereference

func Dereference(v Value) Value

Dereference reports the value v refers to if v is a reference or v itself otherwise.

func (Value) Allows

func (v Value) Allows(sel Selector) bool

Allows reports whether a field with the given selector could be added to v.

Allows does not take into account validators like list.MaxItems(4). This may change in the future.

Example

Code:

ctx := cuecontext.New()

const file = `
a: [1, 2, ...int]

b: #Point
#Point: {
    x:  int
    y:  int
    z?: int
}

c: [string]: int

d: #C
#C: [>"m"]: int
`

v := ctx.CompileString(file)

a := v.LookupPath(cue.ParsePath("a"))
fmt.Println("a allows:")
fmt.Println("  index 4:       ", a.Allows(cue.Index(4)))
fmt.Println("  any index:     ", a.Allows(cue.AnyIndex))
fmt.Println("  any string:    ", a.Allows(cue.AnyString))

b := v.LookupPath(cue.ParsePath("b"))
fmt.Println("b allows:")
fmt.Println("  field x:       ", b.Allows(cue.Str("x")))
fmt.Println("  field z:       ", b.Allows(cue.Str("z")))
fmt.Println("  field foo:     ", b.Allows(cue.Str("foo")))
fmt.Println("  index 4:       ", b.Allows(cue.Index(4)))
fmt.Println("  any string:    ", b.Allows(cue.AnyString))

c := v.LookupPath(cue.ParsePath("c"))
fmt.Println("c allows:")
fmt.Println("  field z:       ", c.Allows(cue.Str("z")))
fmt.Println("  field foo:     ", c.Allows(cue.Str("foo")))
fmt.Println("  index 4:       ", c.Allows(cue.Index(4)))
fmt.Println("  any string:    ", c.Allows(cue.AnyString))

d := v.LookupPath(cue.ParsePath("d"))
fmt.Println("d allows:")
fmt.Println("  field z:       ", d.Allows(cue.Str("z")))
fmt.Println("  field foo:     ", d.Allows(cue.Str("foo")))
fmt.Println("  index 4:       ", d.Allows(cue.Index(4)))
fmt.Println("  any string:    ", d.Allows(cue.AnyString))

Output:

a allows:
  index 4:        true
  any index:      true
  any string:     false
b allows:
  field x:        true
  field z:        true
  field foo:      false
  index 4:        false
  any string:     false
c allows:
  field z:        true
  field foo:      true
  index 4:        false
  any string:     true
d allows:
  field z:        true
  field foo:      false
  index 4:        false
  any string:     false

func (Value) AppendFloat

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

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

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

func (v Value) Attributes(mask AttrKind) []Attribute

Attributes reports all field attributes for the Value.

To retrieve attributes of multiple kinds, you can bitwise-or kinds together. Use ValueKind to query attributes associated with a value.

func (Value) Bool

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

func (v Value) BuildInstance() *build.Instance

If v exactly represents a package, BuildInstance returns the build instance corresponding to the value; otherwise it returns nil.

The value returned by Value.ReferencePath will commonly represent a package.

func (Value) Bytes

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

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

func (Value) Context

func (v Value) Context() *Context

Context reports the Context with which this value was created.

func (Value) Decode

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

Decode initializes the value pointed to by x with Value v. An error is returned if x is nil or not a pointer.

If x is a struct, Decode will validate the constraints specified in the field tags.

If x contains a Value, that part of x will be set to the value at the corresponding part of v. This allows decoding values that aren't entirely concrete into a Go type.

func (Value) Default

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

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

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

func (Value) Equals

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

func (v Value) Err() error

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

func (Value) Eval

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

func (v Value) Exists() bool

Exists reports whether this value existed in the configuration.

func (Value) Expr

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

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

func (v Value) FillPath(p Path, x interface{}) Value

FillPath creates a new value by unifying v with the value of x at the given path.

If x is an cue/ast.Expr, it will be evaluated within the context of the given path: identifiers that are not resolved within the expression are resolved as if they were defined at the path position.

If x is a Value, it will be used as is. It panics if x is not created from the same Runtime as v.

Otherwise, the given Go value will be converted to CUE using the same rules as Context.Encode.

Any reference in v referring to the value at the given path will resolve to x in the newly created value. The resulting value is not validated.

func (Value) Float64

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

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

Format prints a CUE value.

WARNING: although we are narrowing down the semantics, the verbs and options are still subject to change. this API is experimental although it is likely getting close to the final design.

It recognizes the following verbs:

v    print CUE value

The verbs support the following flags:

#    print as schema and include definitions.
     The result is printed as a self-contained file, instead of an the
     expression format.
+    evaluate: resolve defaults and error on incomplete errors

Indentation can be controlled as follows:

width      indent the cue block by <width> tab stops (e.g. %2v)
precision  convert tabs to <precision> spaces (e.g. %.2v), where
           a value of 0 means no indentation or newlines (TODO).

If the value kind corresponds to one of the following Go types, the usual Go formatting verbs for that type can be used:

Int:          b,d,o,O,q,x,X
Float:        f,e,E,g,G
String/Bytes: s,q,x,X

The %v directive will be used if the type is not supported for that verb.

Example

Code:

ctx := cuecontext.New()

v := ctx.CompileString(`
        a: 2 + b
        b: *3 | int
        s: "foo\nbar"
    `)

fmt.Println("### ALL")
fmt.Println(v)
fmt.Println("---")
fmt.Printf("%#v\n", v)
fmt.Println("---")
fmt.Printf("%+v\n", v)

a := v.LookupPath(cue.ParsePath("a"))
fmt.Println("\n### INT")
fmt.Printf("%%v:   %v\n", a)
fmt.Printf("%%05d: %05d\n", a)

s := v.LookupPath(cue.ParsePath("s"))
fmt.Println("\n### STRING")
fmt.Printf("%%v: %v\n", s)
fmt.Printf("%%s: %s\n", s)
fmt.Printf("%%q: %q\n", s)

v = ctx.CompileString(`
        #Def: a: [string]: int
        b: #Def
        b: a: {
            a: 3
            b: 3
        }
    `)
b := v.LookupPath(cue.ParsePath("b.a"))
fmt.Println("\n### DEF")
fmt.Println(b)
fmt.Println("---")
// This will indicate that the result is closed by including a hidden
// definition.
fmt.Printf("%#v\n", b)

Output:

### ALL
{
	a: 5
	b: *3 | int
	s: """
		foo
		bar
		"""
}
---
a: 2 + b
b: *3 | int
s: "foo\nbar"
---
{
	a: 5
	b: 3
	s: """
		foo
		bar
		"""
}

### INT
%v:   5
%05d: 00005

### STRING
%v: """
	foo
	bar
	"""
%s: foo
bar
%q: "foo\nbar"

### DEF
{
	a: 3
	b: 3
}
---
_#def
_#def: {
	{
		[string]: int
	}
	a: 3
	b: 3
}

func (Value) IncompleteKind

func (v Value) IncompleteKind() Kind

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

func (Value) Int

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

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

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 this method on Value.Default.

func (Value) Kind

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

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

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

func (v Value) LookupPath(p Path) Value

LookupPath reports the value for path p relative to v.

func (Value) MantExp

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

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

MarshalJSON marshalls this value into valid JSON.

func (Value) Null

func (v Value) Null() error

Null reports an error if v is not null.

func (Value) Path

func (v Value) Path() Path

Path returns the path to this value from the root of an Instance.

This is currently only defined for values that have a fixed path within a configuration, and thus not those that are derived from Elem, Template, or programmatically generated values such as those returned by Unify.

func (Value) Pos

func (v Value) Pos() token.Pos

Pos returns position information.

Use v.Expr to get positions for all conjuncts and disjuncts.

func (Value) ReferencePath

func (v Value) ReferencePath() (root Value, p Path)

ReferencePath returns the value and path referred to by this value such that value.LookupPath(path) resolves to the same value, or no path if this value is not a reference.

func (Value) Source

func (v Value) Source() ast.Node

Source returns the original node for this value. The return value may not be an ast.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 Value.Expr to get all source values that apply to a field.

func (Value) String

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

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

func (Value) Subsume

func (v Value) Subsume(w Value, opts ...Option) error

Subsume reports nil when w is an instance of v or an error otherwise.

Without options, the entire value is considered for assumption, which means Subsume tests whether v is a backwards compatible (newer) API version of w.

Use the Final option to check subsumption if a w is known to be final, and should assumed to be closed.

Use the Raw option to do a low-level subsumption, taking defaults into account.

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

func (Value) Syntax

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

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

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

func (v Value) UnifyAccept(w Value, accept Value) Value

UnifyAccept is as v.Unify(w), but will disregard the closedness rules for v and w, and will, instead, only allow fields that are present in accept.

UnifyAccept is used to piecemeal unify individual conjuncts obtained from accept without violating closedness rules.

func (Value) Validate

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.

Note that by default not all errors are reported, unless options like Concrete are used. The Final option can be used to check for missing required fields.

func (Value) Walk

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 definitions and optional, required, and hidden fields.

Subdirectories

Name Synopsis
..
ast Package ast declares the types used to represent syntax trees for CUE packages.
astutil
build Package build defines data types and utilities for defining CUE configuration instances.
cuecontext
errors Package errors defines shared types for handling CUE errors.
format Package format implements standard formatting of CUE configurations.
interpreter
wasm Package wasm allows users to write their own functions and make them available to CUE via Wasm modules.
literal Package literal implements conversions to and from string representations of basic data types.
load Package load loads CUE instances.
parser Package parser implements a parser for CUE source files.
scanner Package scanner implements a scanner for CUE source text.
stats Package stats is an experimental package for getting statistics on CUE evaluations.
token Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).