cue

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2024 License: Apache-2.0 Imports: 41 Imported by: 553

Documentation

Overview

Package cue is the main API for CUE evaluation.

Value is the main type that represents CUE evaluations. Values are created with a cuelang.org/go/cue/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:

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

Examples

Constants

This section is empty.

Variables

View Source
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
)
View Source
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")
)

Functions

This section is empty.

Types

type AttrKind added in v0.3.0

type AttrKind int

AttrKind indicates the location of an attribute within CUE source.

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

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

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.

func (*Attribute) Arg added in v0.3.0

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

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

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

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

func (a *Attribute) Name() string

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

func (*Attribute) NumArgs added in v0.3.0

func (a *Attribute) NumArgs() int

NumArgs reports the number of arguments parsed for this attribute.

func (*Attribute) RawArg added in v0.3.0

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

type BuildOption func(o *runtime.Config)

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

func Filename added in v0.4.0

func Filename(filename string) BuildOption

Filename assigns a filename to parsed content.

func ImportPath added in v0.4.0

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

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

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

type Context runtime.Runtime

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.

Example
package main

import (
	"fmt"

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

func main() {
	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)))

}

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

lookups
a:     2
b:     3
"a+b": 5

expressions
a + b: 5
a * b: 6

func (*Context) BuildExpr added in v0.4.0

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

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

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

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

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

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

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:

  • keys of any string type are used directly
  • encoding.TextMarshalers are marshaled
  • integer keys are converted to strings

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

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

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

type EncodeOption func(*encodeOptions)

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

func NilIsAny added in v0.4.0

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 deprecated added in v0.0.5

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

	SelectorType SelectorType

	IsDefinition bool
	IsOptional   bool
	IsHidden     bool
}

FieldInfo contains information about a struct field.

Deprecated: only used by deprecated functions.

type Instance

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
}

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.

func Build deprecated

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

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

func Merge deprecated

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

DO NOT USE.

Deprecated: do not use.

func (*Instance) ID added in v0.3.0

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

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

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 Iterator

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

An Iterator iterates over values.

func (*Iterator) FieldType added in v0.6.0

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 Iterator.Value or Iterator.Selector.

func (*Iterator) Selector added in v0.4.0

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 Iterator.Next advanced past the last entry.

type Kind

type Kind = adt.Kind

Kind determines the underlying type of a Value.

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

type Op = adt.Op

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

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
)

Values of Op.

type Option

type Option option

An Option defines modes of evaluation.

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

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

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

func Docs(include bool) Option

Docs indicates whether docs should be included.

func ErrorsAsValues added in v0.5.0

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

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

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

func Raw() Option

Raw tells Syntax to generate the value as is without any simplifications and without ensuring a value is self contained. Any references are left dangling. The generated syntax tree can be compiled by passing the Value from which it was generated to scope.

The option InlineImports overrides this option with respect to ensuring the output is self contained.

func ResolveReferences deprecated added in v0.1.0

func ResolveReferences(resolve bool) Option

ResolveReferences forces the evaluation of references when outputting.

Deprecated: Value.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 added in v0.1.0

func Schema() Option

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

type Path added in v0.3.0

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

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

func MakePath added in v0.3.0

func MakePath(selectors ...Selector) Path

MakePath creates a Path from a sequence of selectors.

func ParsePath added in v0.3.0

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

func (p Path) Err() error

Err reports errors that occurred when generating the path.

func (Path) Optional added in v0.3.1

func (p Path) Optional() Path

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

foo.bar  --> foo?.bar?

func (Path) Selectors added in v0.3.0

func (p Path) Selectors() []Selector

Selectors reports the individual selectors of a path.

func (Path) String added in v0.3.0

func (p Path) String() string

String reports the CUE representation of p.

type Runtime deprecated

type Runtime runtime.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.

func (*Runtime) Marshal added in v0.0.5

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

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

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

type Selector added in v0.3.0

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

A Selector is a component of a path.

func Def added in v0.3.0

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

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
package main

import (
	"fmt"
	"os"

	"cuelang.org/go/cue"
	"cuelang.org/go/internal/cuetxtar"
	"golang.org/x/tools/txtar"
)

func load(file string) *cue.Instance {
	dir, _ := os.MkdirTemp("", "*")
	defer os.RemoveAll(dir)

	inst := cue.Build(cuetxtar.Load(txtar.Parse([]byte(file)), dir))[0]
	if err := inst.Err; err != nil {
		panic(err)
	}
	return inst
}

func main() {
	const file = `
-- cue.mod/module.cue --
module: "mod.test"
language: version: "v0.9.0"

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

func Index(x int) Selector

An Index selects a list element by index.

func Label added in v0.3.0

func Label(label ast.Label) Selector

Label converts an AST label to a Selector.

func Str added in v0.3.0

func Str(s string) Selector

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

func (Selector) ConstraintType added in v0.5.0

func (sel Selector) ConstraintType() SelectorType

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

func (Selector) Index added in v0.5.0

func (sel Selector) Index() int

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

func (Selector) IsConstraint added in v0.5.0

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

func (sel Selector) IsDefinition() bool

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

func (Selector) IsString added in v0.3.0

func (sel Selector) IsString() bool

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

func (Selector) LabelType added in v0.5.0

func (sel Selector) LabelType() SelectorType

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

func (Selector) Optional added in v0.3.1

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

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

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

func (sel Selector) String() string

String reports the CUE representation of a selector.

func (Selector) Type added in v0.5.0

func (sel Selector) Type() SelectorType

Type returns the type of the selector.

func (Selector) Unquoted added in v0.5.0

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

type SelectorType uint16

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.

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

func (t SelectorType) ConstraintType() SelectorType

ConstraintType reports the constraint type of t.

func (SelectorType) IsDefinition added in v0.5.0

func (t SelectorType) IsDefinition() bool

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

func (SelectorType) IsHidden added in v0.5.0

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

func (t SelectorType) LabelType() SelectorType

LabelType reports the label type of t.

func (SelectorType) String added in v0.5.0

func (t SelectorType) String() string

type Struct added in v0.0.5

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

Struct represents a CUE struct value.

type Value

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 Dereference added in v0.1.0

func Dereference(v Value) Value

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

func (Value) Allows added in v0.3.1

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
package main

import (
	"fmt"

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

func main() {
	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 added in v0.3.0

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

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

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

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

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
package main

import (
	"fmt"

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

func main() {
	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) IsNull added in v0.9.0

func (v Value) IsNull() bool

IsNull reports whether v is null.

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

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

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

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

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

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.

Directories

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

Jump to

Keyboard shortcuts

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