cty

package
v1.15.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2024 License: MIT Imports: 13 Imported by: 2,656

Documentation

Overview

Package cty (pronounced see-tie) provides some infrastructure for a type system that might be useful for applications that need to represent configuration values provided by the user whose types are not known at compile time, particularly if the calling application also allows such values to be used in expressions.

The type system consists of primitive types Number, String and Bool, as well as List and Map collection types and Object types that can have arbitrarily-typed sets of attributes.

A set of operations is defined on these types, which is accessible via the wrapper struct Value, which annotates the raw, internal representation of a value with its corresponding type.

This package is oriented towards being a building block for configuration languages used to bootstrap an application. It is not optimized for use in tight loops where CPU time or memory pressure are a concern.

Index

Constants

This section is empty.

Variables

View Source
var NilType = Type{}

NilType is an invalid type used when a function is returning an error and has no useful type to return. It should not be used and any methods called on it will panic.

View Source
var NilVal = Value{
	// contains filtered or unexported fields
}

NilVal is an invalid Value that can be used as a placeholder when returning with an error from a function that returns (Value, error).

NilVal is *not* a valid error and so no operations may be performed on it. Any attempt to use it will result in a panic.

This should not be confused with the idea of a Null value, as returned by NullVal. NilVal is a nil within the *Go* type system, and is invalid in the cty type system. Null values *do* exist in the cty type system.

Functions

func CanListVal added in v1.8.1

func CanListVal(vals []Value) bool

CanListVal returns false if the given Values can not be coalesced into a single List due to inconsistent element types.

func CanMapVal added in v1.8.1

func CanMapVal(vals map[string]Value) bool

CanMapVal returns false if the given Values can not be coalesced into a single Map due to inconsistent element types.

func CanSetVal added in v1.8.1

func CanSetVal(vals []Value) bool

CanSetVal returns false if the given Values can not be coalesced into a single Set due to inconsistent element types.

func NormalizeString

func NormalizeString(s string) string

NormalizeString applies the same normalization that cty applies when constructing string values.

A return value from this function can be meaningfully compared byte-for-byte with a Value.AsString result.

func Walk

func Walk(val Value, cb func(Path, Value) (bool, error)) error

Walk visits all of the values in a possibly-complex structure, calling a given function for each value.

For example, given a list of strings the callback would first be called with the whole list and then called once for each element of the list.

The callback function may prevent recursive visits to child values by returning false. The callback function my halt the walk altogether by returning a non-nil error. If the returned error is about the element currently being visited, it is recommended to use the provided path value to produce a PathError describing that context.

The path passed to the given function may not be used after that function returns, since its backing array is re-used for other calls.

Types

type CapsuleOps added in v1.2.0

type CapsuleOps struct {
	// GoString provides the GoString implementation for values of the
	// corresponding type. Conventionally this should return a string
	// representation of an expression that would produce an equivalent
	// value.
	GoString func(val interface{}) string

	// TypeGoString provides the GoString implementation for the corresponding
	// capsule type itself.
	TypeGoString func(goTy reflect.Type) string

	// Equals provides the implementation of the Equals operation. This is
	// called only with known, non-null values of the corresponding type,
	// but if the corresponding type is a compound type then it must be
	// ready to detect and handle nested unknown or null values, usually
	// by recursively calling Value.Equals on those nested values.
	//
	// The result value must always be of type cty.Bool, or the Equals
	// operation will panic.
	//
	// If RawEquals is set without also setting Equals, the RawEquals
	// implementation will be used as a fallback implementation. That fallback
	// is appropriate only for leaf types that do not contain any nested
	// cty.Value that would need to distinguish Equals vs. RawEquals for their
	// own equality.
	//
	// If RawEquals is nil then Equals must also be nil, selecting the default
	// pointer-identity comparison instead.
	Equals func(a, b interface{}) Value

	// RawEquals provides the implementation of the RawEquals operation.
	// This is called only with known, non-null values of the corresponding
	// type, but if the corresponding type is a compound type then it must be
	// ready to detect and handle nested unknown or null values, usually
	// by recursively calling Value.RawEquals on those nested values.
	//
	// If RawEquals is nil, values of the corresponding type are compared by
	// pointer identity of the encapsulated value.
	RawEquals func(a, b interface{}) bool

	// HashKey provides a hashing function for values of the corresponding
	// capsule type. If defined, cty will use the resulting hashes as part
	// of the implementation of sets whose element type is or contains the
	// corresponding capsule type.
	//
	// If a capsule type defines HashValue then the function _must_ return
	// an equal hash value for any two values that would cause Equals or
	// RawEquals to return true when given those values. If a given type
	// does not uphold that assumption then sets including this type will
	// not behave correctly.
	HashKey func(v interface{}) string

	// ConversionFrom can provide conversions from the corresponding type to
	// some other type when values of the corresponding type are used with
	// the "convert" package. (The main cty package does not use this operation.)
	//
	// This function itself returns a function, allowing it to switch its
	// behavior depending on the given source type. Return nil to indicate
	// that no such conversion is available.
	ConversionFrom func(src Type) func(interface{}, Path) (Value, error)

	// ConversionTo can provide conversions to the corresponding type from
	// some other type when values of the corresponding type are used with
	// the "convert" package. (The main cty package does not use this operation.)
	//
	// This function itself returns a function, allowing it to switch its
	// behavior depending on the given destination type. Return nil to indicate
	// that no such conversion is available.
	ConversionTo func(dst Type) func(Value, Path) (interface{}, error)

	// ExtensionData is an extension point for applications that wish to
	// create their own extension features using capsule types.
	//
	// The key argument is any value that can be compared with Go's ==
	// operator, but should be of a named type in a package belonging to the
	// application defining the key. An ExtensionData implementation must
	// check to see if the given key is familar to it, and if so return a
	// suitable value for the key.
	//
	// If the given key is unrecognized, the ExtensionData function must
	// return a nil interface. (Importantly, not an interface containing a nil
	// pointer of some other type.)
	// The common implementation of ExtensionData is a single switch statement
	// over "key" which has a default case returning nil.
	//
	// The meaning of any given key is entirely up to the application that
	// defines it. Applications consuming ExtensionData from capsule types
	// should do so defensively: if the result of ExtensionData is not valid,
	// prefer to ignore it or gracefully produce an error rather than causing
	// a panic.
	ExtensionData func(key interface{}) interface{}
}

CapsuleOps represents a set of overloaded operations for a capsule type.

Each field is a reference to a function that can either be nil or can be set to an implementation of the corresponding operation. If an operation function is nil then it isn't supported for the given capsule type.

type ElementCallback

type ElementCallback func(key Value, val Value) (stop bool)

ElementCallback is a callback type used for iterating over elements of collections and attributes of objects.

The types of key and value depend on what type is being iterated over. Return true to stop iterating after the current element, or false to continue iterating.

type ElementIterator

type ElementIterator interface {
	Next() bool
	Element() (key Value, value Value)
}

ElementIterator is the interface type returned by Value.ElementIterator to allow the caller to iterate over elements of a collection-typed value.

Its usage pattern is as follows:

it := val.ElementIterator()
for it.Next() {
    key, val := it.Element()
    // ...
}

type GetAttrStep

type GetAttrStep struct {
	Name string
	// contains filtered or unexported fields
}

GetAttrStep is a Step implementation representing retrieving an attribute from a value, which must be of an object type.

func (GetAttrStep) Apply

func (s GetAttrStep) Apply(val Value) (Value, error)

Apply returns the value of our named attribute from the given value, which must be of an object type that has a value of that name.

func (GetAttrStep) GoString

func (s GetAttrStep) GoString() string

type IndexStep

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

IndexStep is a Step implementation representing applying the index operation to a value, which must be of either a list, map, or set type.

When describing a path through a *type* rather than a concrete value, the Key may be an unknown value, indicating that the step applies to *any* key of the given type.

When indexing into a set, the Key is actually the element being accessed itself, since in sets elements are their own identity.

func (IndexStep) Apply

func (s IndexStep) Apply(val Value) (Value, error)

Apply returns the value resulting from indexing the given value with our key value.

func (IndexStep) GoString

func (s IndexStep) GoString() string

type Path

type Path []PathStep

A Path is a sequence of operations to locate a nested value within a data structure.

The empty Path represents the given item. Any PathSteps within represent taking a single step down into a data structure.

Path has some convenience methods for gradually constructing a path, but callers can also feel free to just produce a slice of PathStep manually and convert to this type, which may be more appropriate in environments where memory pressure is a concern.

Although a Path is technically mutable, by convention callers should not mutate a path once it has been built and passed to some other subsystem. Instead, use Copy and then mutate the copy before using it.

func GetAttrPath

func GetAttrPath(name string) Path

GetAttrPath is a convenience method to start a new Path with a GetAttrStep.

func IndexIntPath added in v1.4.0

func IndexIntPath(v int) Path

IndexIntPath is a typed convenience method for IndexPath.

func IndexPath

func IndexPath(v Value) Path

IndexPath is a convenience method to start a new Path with an IndexStep.

func IndexStringPath added in v1.4.0

func IndexStringPath(v string) Path

IndexStringPath is a typed convenience method for IndexPath.

func (Path) Apply

func (p Path) Apply(val Value) (Value, error)

Apply applies each of the steps in turn to successive values starting with the given value, and returns the result. If any step returns an error, the whole operation returns an error.

func (Path) Copy

func (p Path) Copy() Path

Copy makes a shallow copy of the receiver. Often when paths are passed to caller code they come with the constraint that they are valid only until the caller returns, due to how they are constructed internally. Callers can use Copy to conveniently produce a copy of the value that _they_ control the validity of.

func (Path) Equals added in v1.1.0

func (p Path) Equals(other Path) bool

Equals compares 2 Paths for exact equality.

func (Path) GetAttr

func (p Path) GetAttr(name string) Path

GetAttr returns a new Path that is the reciever with a GetAttrStep appended to the end.

This is provided as a convenient way to construct paths, but each call will create garbage so it should not be used where memory pressure is a concern.

func (Path) HasPrefix added in v1.1.0

func (p Path) HasPrefix(prefix Path) bool

HasPrefix determines if the path p contains the provided prefix.

func (Path) Index

func (p Path) Index(v Value) Path

Index returns a new Path that is the reciever with an IndexStep appended to the end.

This is provided as a convenient way to construct paths, but each call will create garbage so it should not be used where memory pressure is a concern.

func (Path) IndexInt added in v1.4.0

func (p Path) IndexInt(v int) Path

IndexInt is a typed convenience method for Index.

func (Path) IndexString added in v1.4.0

func (p Path) IndexString(v string) Path

IndexString is a typed convenience method for Index.

func (Path) LastStep

func (p Path) LastStep(val Value) (Value, PathStep, error)

LastStep applies the given path up to the last step and then returns the resulting value and the final step.

This is useful when dealing with assignment operations, since in that case the *value* of the last step is not important (and may not, in fact, present at all) and we care only about its location.

Since LastStep applies all steps except the last, it will return errors for those steps in the same way as Apply does.

If the path has *no* steps then the returned PathStep will be nil, representing that any operation should be applied directly to the given value.

func (Path) NewError

func (p Path) NewError(err error) error

NewError creates a new PathError for the current path, wrapping the given error.

func (Path) NewErrorf

func (p Path) NewErrorf(f string, args ...interface{}) error

NewErrorf creates a new PathError for the current path by passing the given format and arguments to fmt.Errorf and then wrapping the result similarly to NewError.

type PathError

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

PathError is a specialization of error that represents where in a potentially-deep data structure an error occured, using a Path.

type PathSet

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

PathSet represents a set of Path objects. This can be used, for example, to talk about a subset of paths within a value that meet some criteria, without directly modifying the values at those paths.

func NewPathSet

func NewPathSet(paths ...Path) PathSet

NewPathSet creates and returns a PathSet, with initial contents optionally set by the given arguments.

func (PathSet) Add

func (s PathSet) Add(path Path)

Add inserts a single given path into the set.

Paths are immutable after construction by convention. It is particularly important not to mutate a path after it has been placed into a PathSet. If a Path is mutated while in a set, behavior is undefined.

func (PathSet) AddAllSteps

func (s PathSet) AddAllSteps(path Path)

AddAllSteps is like Add but it also adds all of the steps leading to the given path.

For example, if given a path representing "foo.bar", it will add both "foo" and "bar".

func (PathSet) Empty

func (s PathSet) Empty() bool

Empty returns true if the length of the receiving set is zero.

func (PathSet) Equal

func (s PathSet) Equal(other PathSet) bool

Equal returns true if and only if both the receiver and the given other set contain exactly the same paths.

func (PathSet) Has

func (s PathSet) Has(path Path) bool

Has returns true if the given path is in the receiving set.

func (PathSet) Intersection

func (s PathSet) Intersection(other PathSet) PathSet

Intersection returns a new set whose contents are the intersection of the receiver and the given other set.

func (PathSet) List

func (s PathSet) List() []Path

List makes and returns a slice of all of the paths in the receiving set, in an undefined but consistent order.

func (PathSet) Remove

func (s PathSet) Remove(path Path)

Remove modifies the receving set to no longer include the given path. If the given path was already absent, this is a no-op.

func (PathSet) Subtract

func (s PathSet) Subtract(other PathSet) PathSet

Subtract returns a new set whose contents are those from the receiver with any elements of the other given set subtracted.

func (PathSet) SymmetricDifference

func (s PathSet) SymmetricDifference(other PathSet) PathSet

SymmetricDifference returns a new set whose contents are the symmetric difference of the receiver and the given other set.

func (PathSet) Union

func (s PathSet) Union(other PathSet) PathSet

Union returns a new set whose contents are the union of the receiver and the given other set.

type PathStep

type PathStep interface {
	Apply(Value) (Value, error)
	// contains filtered or unexported methods
}

PathStep represents a single step down into a data structure, as part of a Path. PathStep is a closed interface, meaning that the only permitted implementations are those within this package.

type PathValueMarks added in v1.7.0

type PathValueMarks struct {
	Path  Path
	Marks ValueMarks
}

PathValueMarks is a structure that enables tracking marks and the paths where they are located in one type

func (PathValueMarks) Equal added in v1.7.0

func (p PathValueMarks) Equal(o PathValueMarks) bool

type RefinementBuilder added in v1.13.0

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

RefinementBuilder is a supporting type for the Value.Refine method, using the builder pattern to apply zero or more constraints before constructing a new value with all of those constraints applied.

Most of the methods of this type return the same reciever to allow for method call chaining. End call chains with a call to RefinementBuilder.NewValue to obtain the newly-refined value.

func (*RefinementBuilder) CollectionLength added in v1.13.0

func (b *RefinementBuilder) CollectionLength(length int) *RefinementBuilder

CollectionLength is a shorthand for passing the same length to both [CollectionLengthLowerBound] and [CollectionLengthUpperBound].

A collection with a refined length with equal bounds can sometimes collapse to a known value. Refining to length zero always produces a known value. The behavior for other lengths varies by collection type kind.

If the unknown value is of a set type, it's only valid to use this method if the caller knows that there will be the given number of _unique_ values in the set. If any values might potentially coalesce together once known, use [CollectionLengthUpperBound] instead.

func (*RefinementBuilder) CollectionLengthLowerBound added in v1.13.0

func (b *RefinementBuilder) CollectionLengthLowerBound(min int) *RefinementBuilder

CollectionLengthLowerBound constrains the lower bound of the length of a collection value, or panics if this builder is not refining a collection value.

func (*RefinementBuilder) CollectionLengthUpperBound added in v1.13.0

func (b *RefinementBuilder) CollectionLengthUpperBound(max int) *RefinementBuilder

CollectionLengthUpperBound constrains the upper bound of the length of a collection value, or panics if this builder is not refining a collection value.

The upper bound must be a known, non-null number or this function will panic.

func (*RefinementBuilder) NewValue added in v1.13.0

func (b *RefinementBuilder) NewValue() (ret Value)

NewValue completes the refinement process by constructing a new value that is guaranteed to meet all of the previously-specified refinements.

If the original value being refined was known then the result is exactly that value, because otherwise the previous refinement calls would have panicked reporting the refinements as invalid for the value.

If the original value was unknown then the result is typically also unknown but may have additional refinements compared to the original. If the applied refinements have reduced the range to a single exact value then the result might be that known value.

func (*RefinementBuilder) NotNull added in v1.13.0

func (b *RefinementBuilder) NotNull() *RefinementBuilder

NotNull constrains the value as definitely not being null.

NotNull is valid when refining values of the following types:

  • number, boolean, and string values
  • list, set, or map types of any element type
  • values of object types
  • values of collection types
  • values of capsule types

When refining any other type this function will panic.

In particular note that it is not valid to constrain an untyped value -- a value whose type is `cty.DynamicPseudoType` -- as being non-null. An unknown value of an unknown type is always completely unconstrained.

func (*RefinementBuilder) Null added in v1.13.0

Null constrains the value as definitely null.

Null is valid for the same types as RefinementBuilder.NotNull. When refining any other type this function will panic.

Explicitly cnstraining a value to be null is strange because that suggests that the caller does actually know the value -- there is only one null value for each type constraint -- but this is here for symmetry with the fact that a ValueRange can also represent that a value is definitely null.

func (*RefinementBuilder) NumberRangeInclusive added in v1.13.0

func (b *RefinementBuilder) NumberRangeInclusive(min, max Value) *RefinementBuilder

NumericRange constrains the upper and/or lower bounds of a number value, or panics if this builder is not refining a number value.

The two given values are interpreted as inclusive bounds and either one may be an unknown number if only one of the two bounds is currently known. If either of the given values is not a non-null number value then this function will panic.

func (*RefinementBuilder) NumberRangeLowerBound added in v1.13.0

func (b *RefinementBuilder) NumberRangeLowerBound(min Value, inclusive bool) *RefinementBuilder

NumberRangeLowerBound constraints the lower bound of a number value, or panics if this builder is not refining a number value.

func (*RefinementBuilder) NumberRangeUpperBound added in v1.13.0

func (b *RefinementBuilder) NumberRangeUpperBound(max Value, inclusive bool) *RefinementBuilder

NumberRangeUpperBound constraints the upper bound of a number value, or panics if this builder is not refining a number value.

func (*RefinementBuilder) StringPrefix added in v1.13.0

func (b *RefinementBuilder) StringPrefix(prefix string) *RefinementBuilder

StringPrefix constrains the prefix of a string value, or panics if this builder is not refining a string value.

The given prefix will be Unicode normalized in the same way that a cty.StringVal would be.

Due to Unicode normalization and grapheme cluster rules, appending new characters to a string can change the meaning of earlier characters. StringPrefix may discard one or more characters from the end of the given prefix to avoid that problem.

Although cty cannot check this automatically, applications should avoid relying on the discarding of the suffix for correctness. For example, if the prefix ends with an emoji base character then StringPrefix will discard it in case subsequent characters include emoji modifiers, but it's still incorrect for the final string to use an entirely different base character.

Applications which fully control the final result and can guarantee the subsequent characters will not combine with the prefix may be able to use RefinementBuilder.StringPrefixFull instead, after carefully reviewing the constraints described in its documentation.

func (*RefinementBuilder) StringPrefixFull added in v1.13.0

func (b *RefinementBuilder) StringPrefixFull(prefix string) *RefinementBuilder

StringPrefixFull is a variant of StringPrefix that will never shorten the given prefix to take into account the possibility of the next character combining with the end of the prefix.

Applications which fully control the subsequent characters can use this as long as they guarantee that the characters added later cannot possibly combine with characters at the end of the prefix to form a single grapheme cluster. For example, it would be unsafe to use the full prefix "hello" if there is any chance that the final string will add a combining diacritic character after the "o", because that would then change the final character.

Use RefinementBuilder.StringPrefix instead if an application cannot fully control the final result to avoid violating this rule.

type Transformer added in v1.7.0

type Transformer interface {
	Enter(Path, Value) (Value, error)
	Exit(Path, Value) (Value, error)
}

Transformer is the interface used to optionally transform values in a possibly-complex structure. The Enter method is called before traversing through a given path, and the Exit method is called when traversal of a path is complete.

Use Enter when you want to transform a complex value before traversal (preorder), and Exit when you want to transform a value after traversal (postorder).

The path passed to the given function may not be used after that function returns, since its backing array is re-used for other calls.

type Type

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

Type represents value types within the type system.

This is a closed interface type, meaning that only the concrete implementations provided within this package are considered valid.

var Bool Type

Bool is the boolean type. The two values of this type are True and False.

var DynamicPseudoType Type

DynamicPseudoType represents the dynamic pseudo-type.

This type can represent situations where a type is not yet known. Its meaning is undefined in cty, but it could be used by a calling application to allow expression type checking with some types not yet known. For example, the application might optimistically permit any operation on values of this type in type checking, allowing a partial type-check result, and then repeat the check when more information is known to get the final, concrete type.

It is a pseudo-type because it is used only as a sigil to the calling application. "Unknown" is the only valid value of this pseudo-type, so operations on values of this type will always short-circuit as per the rules for that special value.

var EmptyObject Type

EmptyObject is a shorthand for Object(map[string]Type{}), to more easily talk about the empty object type.

var EmptyTuple Type

EmptyTuple is a shorthand for Tuple([]Type{}), to more easily talk about the empty tuple type.

var Number Type

Number is the numeric type. Number values are arbitrary-precision decimal numbers, which can then be converted into Go's various numeric types only if they are in the appropriate range.

var String Type

String is the string type. String values are sequences of unicode codepoints encoded internally as UTF-8.

func Capsule

func Capsule(name string, nativeType reflect.Type) Type

Capsule creates a new Capsule type.

A Capsule type is a special type that can be used to transport arbitrary Go native values of a given type through the cty type system. A language that uses cty as its type system might, for example, provide functions that return capsule-typed values and then other functions that operate on those values.

From cty's perspective, Capsule types have a few interesting characteristics, described in the following paragraphs.

Each capsule type has an associated Go native type that it is able to transport. Capsule types compare by identity, so each call to the Capsule function creates an entirely-distinct cty Type, even if two calls use the same native type.

Each capsule-typed value contains a pointer to a value of the given native type. A capsule-typed value by default supports no operations except equality, and equality is implemented by pointer identity of the encapsulated pointer. A capsule type can optionally have its own implementations of certain operations if it is created with CapsuleWithOps instead of Capsule.

The given name is used as the new type's "friendly name". This can be any string in principle, but will usually be a short, all-lowercase name aimed at users of the embedding language (i.e. not mention Go-specific details) and will ideally not create ambiguity with any predefined cty type.

Capsule types are never introduced by any standard cty operation, so a calling application opts in to including them within its own type system by creating them and introducing them via its own functions. At that point, the application is responsible for dealing with any capsule-typed values that might be returned.

func CapsuleWithOps added in v1.2.0

func CapsuleWithOps(name string, nativeType reflect.Type, ops *CapsuleOps) Type

CapsuleWithOps is like Capsule except the caller may provide an object representing some overloaded operation implementations to associate with the given capsule type.

All of the other caveats and restrictions for capsule types still apply, but overloaded operations can potentially help a capsule type participate better in cty operations.

func List

func List(elem Type) Type

List creates a map type with the given element Type.

List types are CollectionType implementations.

func Map

func Map(elem Type) Type

Map creates a map type with the given element Type.

Map types are CollectionType implementations.

func Object

func Object(attrTypes map[string]Type) Type

Object creates an object type with the given attribute types.

After a map is passed to this function the caller must no longer access it, since ownership is transferred to this library.

func ObjectWithOptionalAttrs added in v1.6.0

func ObjectWithOptionalAttrs(attrTypes map[string]Type, optional []string) Type

ObjectWithOptionalAttrs creates an object type where some of its attributes are optional.

This function is EXPERIMENTAL. The behavior of the function or of any other functions working either directly or indirectly with a type created by this function is not currently considered as a compatibility constraint, and is subject to change even in minor-version releases of this module. Other modules that work with cty types and values may or may not support object types with optional attributes; if they do not, their behavior when receiving one may be non-ideal.

Optional attributes are significant only when an object type is being used as a target type for conversion in the "convert" package. A value of an object type always has a value for each of the attributes in the attribute types table, with optional values replaced with null during conversion.

All keys in the optional slice must also exist in the attrTypes map. If not, this function will panic.

After a map or array is passed to this function the caller must no longer access it, since ownership is transferred to this library.

func Set

func Set(elem Type) Type

Set creates a set type with the given element Type.

Set types are CollectionType implementations.

func Tuple

func Tuple(elemTypes []Type) Type

Tuple creates a tuple type with the given element types.

After a slice is passed to this function the caller must no longer access the underlying array, since ownership is transferred to this library.

func (Type) AttributeOptional added in v1.6.0

func (t Type) AttributeOptional(name string) bool

AttributeOptional returns true if the attribute of the given name is optional.

Will panic if the receiver is not an object type (use IsObjectType to confirm) or if the object type has no such attribute (use HasAttribute to confirm).

func (Type) AttributeType

func (t Type) AttributeType(name string) Type

AttributeType returns the type of the attribute with the given name. Will panic if the receiver is not an object type (use IsObjectType to confirm) or if the object type has no such attribute (use HasAttribute to confirm).

func (Type) AttributeTypes

func (t Type) AttributeTypes() map[string]Type

AttributeTypes returns a map from attribute names to their associated types. Will panic if the receiver is not an object type (use IsObjectType to confirm).

The returned map is part of the internal state of the type, and is provided for read access only. It is forbidden for any caller to modify the returned map. For many purposes the attribute-related methods of Value are more appropriate and more convenient to use.

func (Type) CapsuleExtensionData added in v1.2.0

func (ty Type) CapsuleExtensionData(key interface{}) interface{}

CapsuleExtensionData is a convenience interface to the ExtensionData function that can be optionally implemented for a capsule type. It will check to see if the underlying type implements ExtensionData and call it if so. If not, it will return nil to indicate that the given key is not supported.

See the documentation for CapsuleOps.ExtensionData for more information on the purpose of and usage of this mechanism.

If CapsuleExtensionData is called on a non-capsule type then it will panic.

func (Type) CapsuleOps added in v1.2.0

func (ty Type) CapsuleOps() *CapsuleOps

CapsuleOps returns a pointer to the CapsuleOps value for a capsule type, or panics if the receiver is not a capsule type.

The caller must not modify the CapsuleOps.

func (Type) ElementType

func (t Type) ElementType() Type

ElementType returns the element type of the receiver if it is a collection type, or panics if it is not. Use IsCollectionType first to test whether this method will succeed.

func (Type) EncapsulatedType

func (t Type) EncapsulatedType() reflect.Type

EncapsulatedType returns the encapsulated native type of a capsule type, or panics if the receiver is not a Capsule type.

Is IsCapsuleType to determine if this method is safe to call.

func (Type) Equals

func (t Type) Equals(other Type) bool

Equals returns true if the other given Type exactly equals the receiver type.

func (Type) FriendlyName

func (t Type) FriendlyName() string

FriendlyName returns a human-friendly *English* name for the given type.

func (Type) FriendlyNameForConstraint

func (t Type) FriendlyNameForConstraint() string

FriendlyNameForConstraint is similar to FriendlyName except that the result is specialized for describing type _constraints_ rather than types themselves. This is more appropriate when reporting that a particular value does not conform to an expected type constraint.

In particular, this function uses the term "any type" to refer to cty.DynamicPseudoType, rather than "dynamic" as returned by FriendlyName.

func (Type) GoString

func (t Type) GoString() string

GoString returns a string approximating how the receiver type would be expressed in Go source code.

func (Type) HasAttribute

func (t Type) HasAttribute(name string) bool

HasAttribute returns true if the receiver has an attribute with the given name, regardless of its type. Will panic if the reciever isn't an object type; use IsObjectType to determine whether this operation will succeed.

func (Type) HasDynamicTypes

func (t Type) HasDynamicTypes() bool

HasDynamicTypes returns true either if the receiver is itself DynamicPseudoType or if it is a compound type whose descendent elements are DynamicPseudoType.

func (Type) IsCapsuleType

func (t Type) IsCapsuleType() bool

IsCapsuleType returns true if this type is a capsule type, as created by cty.Capsule .

func (Type) IsCollectionType

func (t Type) IsCollectionType() bool

IsCollectionType returns true if the given type supports the operations that are defined for all collection types.

func (Type) IsListType

func (t Type) IsListType() bool

IsListType returns true if the given type is a list type, regardless of its element type.

func (Type) IsMapType

func (t Type) IsMapType() bool

IsMapType returns true if the given type is a map type, regardless of its element type.

func (Type) IsObjectType

func (t Type) IsObjectType() bool

IsObjectType returns true if the given type is an object type, regardless of its element type.

func (Type) IsPrimitiveType

func (t Type) IsPrimitiveType() bool

IsPrimitiveType returns true if and only if the reciever is a primitive type, which means it's either number, string, or bool. Any two primitive types can be safely compared for equality using the standard == operator without panic, which is not a guarantee that holds for all types. Primitive types can therefore also be used in switch statements.

func (Type) IsSetType

func (t Type) IsSetType() bool

IsSetType returns true if the given type is a list type, regardless of its element type.

func (Type) IsTupleType

func (t Type) IsTupleType() bool

IsTupleType returns true if the given type is an object type, regardless of its element type.

func (Type) Length

func (t Type) Length() int

Length returns the number of elements of the receiving tuple type. Will panic if the reciever isn't a tuple type; use IsTupleType to determine whether this operation will succeed.

func (Type) ListElementType

func (t Type) ListElementType() *Type

ListElementType is a convenience method that checks if the given type is a list type, returning a pointer to its element type if so and nil otherwise. This is intended to allow convenient conditional branches, like so:

if et := t.ListElementType(); et != nil {
    // Do something with *et
}

func (Type) MapElementType

func (t Type) MapElementType() *Type

MapElementType is a convenience method that checks if the given type is a map type, returning a pointer to its element type if so and nil otherwise. This is intended to allow convenient conditional branches, like so:

if et := t.MapElementType(); et != nil {
    // Do something with *et
}

func (Type) MarshalJSON

func (t Type) MarshalJSON() ([]byte, error)

MarshalJSON is an implementation of json.Marshaler that allows Type instances to be serialized as JSON.

All standard types can be serialized, but capsule types cannot since there is no way to automatically recover the original pointer and capsule types compare by equality.

func (Type) OptionalAttributes added in v1.6.0

func (t Type) OptionalAttributes() map[string]struct{}

OptionalAttributes returns a map representing the set of attributes that are optional. Will panic if the receiver is not an object type (use IsObjectType to confirm).

The returned map is part of the internal state of the type, and is provided for read access only. It is forbidden for any caller to modify the returned map.

func (Type) SetElementType

func (t Type) SetElementType() *Type

SetElementType is a convenience method that checks if the given type is a set type, returning a pointer to its element type if so and nil otherwise. This is intended to allow convenient conditional branches, like so:

if et := t.SetElementType(); et != nil {
    // Do something with *et
}

func (Type) TestConformance

func (t Type) TestConformance(other Type) []error

TestConformance recursively walks the receiver and the given other type and returns nil if the receiver *conforms* to the given type.

Type conformance is similar to type equality but has one crucial difference: PseudoTypeDynamic can be used within the given type to represent that *any* type is allowed.

If any non-conformities are found, the returned slice will be non-nil and contain at least one error value. It will be nil if the type is entirely conformant.

Note that the special behavior of PseudoTypeDynamic is the *only* exception to normal type equality. Calling applications may wish to apply their own automatic conversion logic to the given data structure to create a more liberal notion of conformance to a type.

Returned errors are usually (but not always) PathError instances that indicate where in the structure the error was found. If a returned error is of that type then the error message is written for (English-speaking) end-users working within the cty type system, not mentioning any Go-oriented implementation details.

func (Type) TupleElementType

func (t Type) TupleElementType(idx int) Type

TupleElementType returns the type of the element with the given index. Will panic if the receiver is not a tuple type (use IsTupleType to confirm) or if the index is out of range (use Length to confirm).

func (Type) TupleElementTypes

func (t Type) TupleElementTypes() []Type

TupleElementTypes returns a slice of the recieving tuple type's element types. Will panic if the receiver is not a tuple type (use IsTupleType to confirm).

The returned slice is part of the internal state of the type, and is provided for read access only. It is forbidden for any caller to modify the underlying array. For many purposes the element-related methods of Value are more appropriate and more convenient to use.

func (*Type) UnmarshalJSON

func (t *Type) UnmarshalJSON(buf []byte) error

UnmarshalJSON is the opposite of MarshalJSON. See the documentation of MarshalJSON for information on the limitations of JSON serialization of types.

func (Type) WithoutOptionalAttributesDeep added in v1.8.1

func (t Type) WithoutOptionalAttributesDeep() Type

WithoutOptionalAttributesDeep returns a type equivalent to the receiver but with any objects with optional attributes converted into fully concrete object types. This operation is applied recursively.

type Value

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

Value represents a value of a particular type, and is the interface by which operations are executed on typed values.

Value has two different classes of method. Operation methods stay entirely within the type system (methods accept and return Value instances) and are intended for use in implementing a language in terms of cty, while integration methods either enter or leave the type system, working with native Go values. Operation methods are guaranteed to support all of the expected short-circuit behavior for unknown and dynamic values, while integration methods may not.

The philosophy for the operations API is that it's the caller's responsibility to ensure that the given types and values satisfy the specified invariants during a separate type check, so that the caller is able to return errors to its user from the application's own perspective.

Consequently the design of these methods assumes such checks have already been done and panics if any invariants turn out not to be satisfied. These panic errors are not intended to be handled, but rather indicate a bug in the calling application that should be fixed with more checks prior to executing operations.

A related consequence of this philosophy is that no automatic type conversions are done. If a method specifies that its argument must be number then it's the caller's responsibility to do that conversion before the call, thus allowing the application to have more constrained conversion rules than are offered by the built-in converter where necessary.

var DynamicVal Value

DynamicVal is the only valid value of the pseudo-type dynamic. This value can be used as a placeholder where a value or expression's type and value are both unknown, thus allowing partial evaluation. See the docs for DynamicPseudoType for more information.

var EmptyObjectVal Value

EmptyObjectVal is the only possible non-null, non-unknown value of type EmptyObject.

var EmptyTupleVal Value

EmptyTupleVal is the only possible non-null, non-unknown value of type EmptyTuple.

var False Value

False is the falsey value of type Bool

var NegativeInfinity Value

NegativeInfinity is a Number value representing negative infinity

var PositiveInfinity Value

PositiveInfinity is a Number value representing positive infinity

var True Value

True is the truthy value of type Bool

var Zero Value

Zero is a number value representing exactly zero.

func BoolVal

func BoolVal(v bool) Value

BoolVal returns a Value of type Number whose internal value is the given bool.

func CapsuleVal

func CapsuleVal(ty Type, wrapVal interface{}) Value

CapsuleVal creates a value of the given capsule type using the given wrapVal, which must be a pointer to a value of the capsule type's native type.

This function will panic if the given type is not a capsule type, if the given wrapVal is not compatible with the given capsule type, or if wrapVal is not a pointer.

func ListVal

func ListVal(vals []Value) Value

ListVal returns a Value of list type whose element type is defined by the types of the given values, which must be homogenous.

If the types are not all consistent (aside from elements that are of the dynamic pseudo-type) then this function will panic. It will panic also if the given list is empty, since then the element type cannot be inferred. (See also ListValEmpty.)

func ListValEmpty

func ListValEmpty(element Type) Value

ListValEmpty returns an empty list of the given element type.

func MapVal

func MapVal(vals map[string]Value) Value

MapVal returns a Value of a map type whose element type is defined by the types of the given values, which must be homogenous.

If the types are not all consistent (aside from elements that are of the dynamic pseudo-type) then this function will panic. It will panic also if the given map is empty, since then the element type cannot be inferred. (See also MapValEmpty.)

func MapValEmpty

func MapValEmpty(element Type) Value

MapValEmpty returns an empty map of the given element type.

func MustParseNumberVal

func MustParseNumberVal(s string) Value

MustParseNumberVal is like ParseNumberVal but it will panic in case of any error. It can be used during initialization or any other situation where the given string is a constant or otherwise known to be correct by the caller.

func NullVal

func NullVal(t Type) Value

NullVal returns a null value of the given type. A null can be created of any type, but operations on such values will always panic. Calling applications are encouraged to use nulls only sparingly, particularly when user-provided expressions are to be evaluated, since the precence of nulls creates a much higher chance of evaluation errors that can't be caught by a type checker.

func NumberFloatVal

func NumberFloatVal(v float64) Value

NumberFloatVal returns a Value of type Number whose internal value is equal to the given float.

func NumberIntVal

func NumberIntVal(v int64) Value

NumberIntVal returns a Value of type Number whose internal value is equal to the given integer.

func NumberUIntVal

func NumberUIntVal(v uint64) Value

NumberUIntVal returns a Value of type Number whose internal value is equal to the given unsigned integer.

func NumberVal

func NumberVal(v *big.Float) Value

NumberVal returns a Value of type Number whose internal value is the given big.Float. The returned value becomes the owner of the big.Float object, and so it's forbidden for the caller to mutate the object after it's wrapped in this way.

func ObjectVal

func ObjectVal(attrs map[string]Value) Value

ObjectVal returns a Value of an object type whose structure is defined by the key names and value types in the given map.

func ParseNumberVal

func ParseNumberVal(s string) (Value, error)

ParseNumberVal returns a Value of type number produced by parsing the given string as a decimal real number. To ensure that two identical strings will always produce an equal number, always use this function to derive a number from a string; it will ensure that the precision and rounding mode for the internal big decimal is configured in a consistent way.

If the given string cannot be parsed as a number, the returned error has the message "a number is required", making it suitable to return to an end-user to signal a type conversion error.

If the given string contains a number that becomes a recurring fraction when expressed in binary then it will be truncated to have a 512-bit mantissa. Note that this is a higher precision than that of a float64, so coverting the same decimal number first to float64 and then calling NumberFloatVal will not produce an equal result; the conversion first to float64 will round the mantissa to fewer than 512 bits.

func SetVal

func SetVal(vals []Value) Value

SetVal returns a Value of set type whose element type is defined by the types of the given values, which must be homogenous.

If the types are not all consistent (aside from elements that are of the dynamic pseudo-type) then this function will panic. It will panic also if the given list is empty, since then the element type cannot be inferred. (See also SetValEmpty.)

func SetValEmpty

func SetValEmpty(element Type) Value

SetValEmpty returns an empty set of the given element type.

func SetValFromValueSet

func SetValFromValueSet(s ValueSet) Value

SetValFromValueSet returns a Value of set type based on an already-constructed ValueSet.

The element type of the returned value is the element type of the given set.

func StringVal

func StringVal(v string) Value

StringVal returns a Value of type String whose internal value is the given string.

Strings must be UTF-8 encoded sequences of valid unicode codepoints, and they are NFC-normalized on entry into the world of cty values.

If the given string is not valid UTF-8 then behavior of string operations is undefined.

func Transform

func Transform(val Value, cb func(Path, Value) (Value, error)) (Value, error)

Transform visits all of the values in a possibly-complex structure, calling a given function for each value which has an opportunity to replace that value.

Unlike Walk, Transform visits child nodes first, so for a list of strings it would first visit the strings and then the _new_ list constructed from the transformed values of the list items.

This is useful for creating the effect of being able to make deep mutations to a value even though values are immutable. However, it's the responsibility of the given function to preserve expected invariants, such as homogenity of element types in collections; this function can panic if such invariants are violated, just as if new values were constructed directly using the value constructor functions. An easy way to preserve invariants is to ensure that the transform function never changes the value type.

The callback function may halt the walk altogether by returning a non-nil error. If the returned error is about the element currently being visited, it is recommended to use the provided path value to produce a PathError describing that context.

The path passed to the given function may not be used after that function returns, since its backing array is re-used for other calls.

func TransformWithTransformer added in v1.7.0

func TransformWithTransformer(val Value, t Transformer) (Value, error)

TransformWithTransformer allows the caller to more closely control the traversal used for transformation. See the documentation for Transformer for more details.

func TupleVal

func TupleVal(elems []Value) Value

TupleVal returns a Value of a tuple type whose element types are defined by the value types in the given slice.

func UnknownAsNull

func UnknownAsNull(val Value) Value

UnknownAsNull returns a value of the same type as the given value but with any unknown values (including nested values) replaced with null values of the same type.

This can be useful if a result is to be serialized in a format that can't represent unknowns, such as JSON, as long as the caller does not need to retain the unknown value information.

func UnknownVal

func UnknownVal(t Type) Value

UnknownVal returns an Value that represents an unknown value of the given type. Unknown values can be used to represent a value that is not yet known. Its meaning is undefined in cty, but it could be used by an calling application to allow partial evaluation.

Unknown values of any type can be created of any type. All operations on Unknown values themselves return Unknown.

func (Value) Absolute

func (val Value) Absolute() Value

Absolute returns the absolute (signless) value of the receiver, which must be a number or this method will panic.

func (Value) Add

func (val Value) Add(other Value) Value

Add returns the sum of the receiver and the given other value. Both values must be numbers; this method will panic if not.

func (Value) And

func (val Value) And(other Value) Value

And returns the result of logical AND with the receiver and the other given value, which must both be of type Bool or this method will panic.

func (Value) AsBigFloat

func (val Value) AsBigFloat() *big.Float

AsBigFloat returns a big.Float representation of a non-null, non-unknown cty.Number value, or panics if called on any other value.

For more convenient conversions to other native numeric types, use the "gocty" package.

func (Value) AsString

func (val Value) AsString() string

AsString returns the native string from a non-null, non-unknown cty.String value, or panics if called on any other value.

func (Value) AsValueMap

func (val Value) AsValueMap() map[string]Value

AsValueMap returns a map[string]cty.Value representation of a non-null, non-unknown value of any type that CanIterateElements, or panics if called on any other value.

For more convenient conversions to maps of more specific types, use the "gocty" package.

func (Value) AsValueSet

func (val Value) AsValueSet() ValueSet

AsValueSet returns a ValueSet representation of a non-null, non-unknown value of any collection type, or panics if called on any other value.

Unlike AsValueSlice and AsValueMap, this method requires specifically a collection type (list, set or map) and does not allow structural types (tuple or object), because the ValueSet type requires homogenous element types.

The returned ValueSet can store only values of the receiver's element type.

func (Value) AsValueSlice

func (val Value) AsValueSlice() []Value

AsValueSlice returns a []cty.Value representation of a non-null, non-unknown value of any type that CanIterateElements, or panics if called on any other value.

For more convenient conversions to slices of more specific types, use the "gocty" package.

func (Value) CanIterateElements

func (val Value) CanIterateElements() bool

CanIterateElements returns true if the receiver can support the ElementIterator method (and by extension, ForEachElement) without panic.

func (Value) ContainsMarked added in v1.2.0

func (val Value) ContainsMarked() bool

ContainsMarked returns true if the receiving value or any value within it is marked.

This operation is relatively expensive. If you only need a shallow result, use IsMarked instead.

func (Value) Divide

func (val Value) Divide(other Value) Value

Divide returns the quotient of the receiver and the given other value. Both values must be numbers; this method will panic if not.

If the "other" value is exactly zero, this operation will return either PositiveInfinity or NegativeInfinity, depending on the sign of the receiver value. For some use-cases the presence of infinities may be undesirable, in which case the caller should check whether the other value equals zero before calling and raise an error instead.

If both values are zero or infinity, this function will panic with an instance of big.ErrNaN.

func (Value) ElementIterator

func (val Value) ElementIterator() ElementIterator

ElementIterator returns an ElementIterator for iterating the elements of the receiver, which must be a collection type, a tuple type, or an object type. If called on a method of any other type, this method will panic.

The value must be Known and non-Null, or this method will panic.

If the receiver is of a list type, the returned keys will be of type Number and the values will be of the list's element type.

If the receiver is of a map type, the returned keys will be of type String and the value will be of the map's element type. Elements are passed in ascending lexicographical order by key.

If the receiver is of a set type, each element is returned as both the key and the value, since set members are their own identity.

If the receiver is of a tuple type, the returned keys will be of type Number and the value will be of the corresponding element's type.

If the receiver is of an object type, the returned keys will be of type String and the value will be of the corresponding attributes's type.

ElementIterator is an integration method, so it cannot handle Unknown values. This method will panic if the receiver is Unknown.

func (Value) EncapsulatedValue

func (val Value) EncapsulatedValue() interface{}

EncapsulatedValue returns the native value encapsulated in a non-null, non-unknown capsule-typed value, or panics if called on any other value.

The result is the same pointer that was passed to CapsuleVal to create the value. Since cty considers values to be immutable, it is strongly recommended to treat the encapsulated value itself as immutable too.

func (Value) Equals

func (val Value) Equals(other Value) Value

Equals returns True if the receiver and the given other value have the same type and are exactly equal in value.

As a special case, two null values are always equal regardless of type.

The usual short-circuit rules apply, so the result will be unknown if either of the given values are.

Use RawEquals to compare if two values are equal *ignoring* the short-circuit rules and the exception for null values.

func (Value) False

func (val Value) False() bool

False is the opposite of True.

func (Value) ForEachElement

func (val Value) ForEachElement(cb ElementCallback) bool

ForEachElement executes a given callback function for each element of the receiver, which must be a collection type or tuple type, or this method will panic.

ForEachElement uses ElementIterator internally, and so the values passed to the callback are as described for ElementIterator.

Returns true if the iteration exited early due to the callback function returning true, or false if the loop ran to completion.

ForEachElement is an integration method, so it cannot handle Unknown values. This method will panic if the receiver is Unknown.

func (Value) GetAttr

func (val Value) GetAttr(name string) Value

GetAttr returns the value of the given attribute of the receiver, which must be of an object type that has an attribute of the given name. This method will panic if the receiver type is not compatible.

The method will also panic if the given attribute name is not defined for the value's type. Use the attribute-related methods on Type to check for the validity of an attribute before trying to use it.

This method may be called on a value whose type is DynamicPseudoType, in which case the result will also be DynamicVal.

func (Value) GoString

func (val Value) GoString() string

GoString is an implementation of fmt.GoStringer that produces concise source-like representations of values suitable for use in debug messages.

func (Value) GreaterThan

func (val Value) GreaterThan(other Value) Value

GreaterThan returns True if the receiver is greater than the other given value, which must both be numbers or this method will panic.

func (Value) GreaterThanOrEqualTo

func (val Value) GreaterThanOrEqualTo(other Value) Value

GreaterThanOrEqualTo is equivalent to GreaterThan and Equal combined with Or.

func (Value) HasElement

func (val Value) HasElement(elem Value) Value

HasElement returns True if the receiver (which must be of a set type) has the given value as an element, or False if it does not.

The result will be UnknownVal(Bool) if either the set or the given value are unknown.

This method will panic if the receiver is not a set, or if it is a null set.

func (Value) HasIndex

func (val Value) HasIndex(key Value) Value

HasIndex returns True if the receiver (which must be supported for Index) has an element with the given index key, or False if it does not.

The result will be UnknownVal(Bool) if either the collection or the key value are unknown.

This method will panic if the receiver is not indexable, but does not impose any panic-causing type constraints on the key.

func (Value) HasMark added in v1.2.0

func (val Value) HasMark(mark interface{}) bool

HasMark returns true if and only if the receiving value has the given mark.

func (Value) HasSameMarks added in v1.2.0

func (val Value) HasSameMarks(other Value) bool

HasSameMarks returns true if an only if the receiver and the given other value have identical marks.

func (Value) HasWhollyKnownType added in v1.5.0

func (val Value) HasWhollyKnownType() bool

HasWhollyKnownType checks if the value is dynamic, or contains any nested DynamicVal. This implies that both the value is not known, and the final type may change.

func (Value) Hash

func (val Value) Hash() int

Hash returns a hash value for the receiver that can be used for equality checks where some inaccuracy is tolerable.

The hash function is value-type-specific, so it is not meaningful to compare hash results for values of different types.

This function is not safe to use for security-related applications, since the hash used is not strong enough.

func (Value) Index

func (val Value) Index(key Value) Value

Index returns the value of an element of the receiver, which must have either a list, map or tuple type. This method will panic if the receiver type is not compatible.

The key value must be the correct type for the receving collection: a number if the collection is a list or tuple, or a string if it is a map. In the case of a list or tuple, the given number must be convertable to int or this method will panic. The key may alternatively be of DynamicPseudoType, in which case the result itself is an unknown of the collection's element type.

The result is of the receiver collection's element type, or in the case of a tuple the type of the specific element index requested.

This method may be called on a value whose type is DynamicPseudoType, in which case the result will also be the DynamicValue.

func (Value) IsKnown

func (val Value) IsKnown() bool

IsKnown returns true if the value is known. That is, if it is not the result of the unknown value constructor Unknown(...), and is not the result of an operation on another unknown value.

Unknown values are only produced either directly or as a result of operating on other unknown values, and so an application that never introduces Unknown values can be guaranteed to never receive any either.

func (Value) IsMarked added in v1.2.0

func (val Value) IsMarked() bool

IsMarked returns true if and only if the receiving value carries at least one mark. A marked value cannot be used directly with integration methods without explicitly unmarking it (and retrieving the markings) first.

func (Value) IsNull

func (val Value) IsNull() bool

IsNull returns true if the value is null. Values of any type can be null, but any operations on a null value will panic. No operation ever produces null, so an application that never introduces Null values can be guaranteed to never receive any either.

func (Value) IsWhollyKnown

func (val Value) IsWhollyKnown() bool

IsWhollyKnown is an extension of IsKnown that also recursively checks inside collections and structures to see if there are any nested unknown values.

func (Value) Length

func (val Value) Length() Value

Length returns the length of the receiver, which must be a collection type or tuple type, as a number value. If the receiver is not a compatible type then this method will panic.

If the receiver is unknown then the result is also unknown.

If the receiver is null then this function will panic.

Note that Length is not supported for strings. To determine the length of a string, use the Length function in funcs/stdlib.

func (Value) LengthInt

func (val Value) LengthInt() int

LengthInt is like Length except it returns an int. It has the same behavior as Length except that it will panic if the receiver is unknown.

This is an integration method provided for the convenience of code bridging into Go's type system.

For backward compatibility with an earlier implementation error, LengthInt's result can disagree with Length's result for any set containing unknown values. Length can potentially indicate the set's length is unknown in that case, whereas LengthInt will return the maximum possible length as if the unknown values were each a placeholder for a value not equal to any other value in the set.

func (Value) LessThan

func (val Value) LessThan(other Value) Value

LessThan returns True if the receiver is less than the other given value, which must both be numbers or this method will panic.

func (Value) LessThanOrEqualTo

func (val Value) LessThanOrEqualTo(other Value) Value

LessThanOrEqualTo is equivalent to LessThan and Equal combined with Or.

func (Value) Mark added in v1.2.0

func (val Value) Mark(mark interface{}) Value

Mark returns a new value that as the same type and underlying value as the receiver but that also carries the given value as a "mark".

Marks are used to carry additional application-specific characteristics associated with values. A marked value can be used with operation methods, in which case the marks are propagated to the operation results. A marked value _cannot_ be used with integration methods, so callers of those must derive an unmarked value using Unmark (and thus explicitly handle the markings) before calling the integration methods.

The mark value can be any value that would be valid to use as a map key. The mark value should be of a named type in order to use the type itself as a namespace for markings. That type can be unexported if desired, in order to ensure that the mark can only be handled through the defining package's own functions.

An application that never calls this method does not need to worry about handling marked values.

func (Value) MarkWithPaths added in v1.7.0

func (val Value) MarkWithPaths(pvm []PathValueMarks) Value

MarkWithPaths accepts a slice of PathValueMarks to apply markers to particular paths and returns the marked Value.

func (Value) Marks added in v1.2.0

func (val Value) Marks() ValueMarks

Marks returns a map (representing a set) of all of the mark values associated with the receiving value, without changing the marks. Returns nil if the value is not marked at all.

func (Value) Modulo

func (val Value) Modulo(other Value) Value

Modulo returns the remainder of an integer division of the receiver and the given other value. Both values must be numbers; this method will panic if not.

If the "other" value is exactly zero, this operation will return either PositiveInfinity or NegativeInfinity, depending on the sign of the receiver value. For some use-cases the presence of infinities may be undesirable, in which case the caller should check whether the other value equals zero before calling and raise an error instead.

This operation is primarily here for use with nonzero natural numbers. Modulo with "other" as a non-natural number gets somewhat philosophical, and this function takes a position on what that should mean, but callers may wish to disallow such things outright or implement their own modulo if they disagree with the interpretation used here.

func (Value) Multiply

func (val Value) Multiply(other Value) Value

Multiply returns the product of the receiver and the given other value. Both values must be numbers; this method will panic if not.

func (Value) Negate

func (val Value) Negate() Value

Negate returns the numeric negative of the receiver, which must be a number. This method will panic when given a value of any other type.

func (Value) Not

func (val Value) Not() Value

Not returns the logical inverse of the receiver, which must be of type Bool or this method will panic.

func (Value) NotEqual

func (val Value) NotEqual(other Value) Value

NotEqual is a shorthand for Equals followed by Not.

func (Value) Or

func (val Value) Or(other Value) Value

Or returns the result of logical OR with the receiver and the other given value, which must both be of type Bool or this method will panic.

func (Value) Range added in v1.13.0

func (v Value) Range() ValueRange

Range returns an object that offers partial information about the range of the receiver.

This is most relevant for unknown values, because it gives access to any optional additional constraints on the final value (specified by the source of the value using "refinements") beyond what we can assume from the value's type.

Calling Range for a known value is a little strange, but it's supported by returning a ValueRange object that describes the exact value as closely as possible. Typically a caller should work directly with the exact value in that case, but some purposes might only need the level of detail offered by ranges and so can share code between both known and unknown values.

func (Value) RawEquals

func (val Value) RawEquals(other Value) bool

RawEquals returns true if and only if the two given values have the same type and equal value, ignoring the usual short-circuit rules about unknowns and dynamic types.

This method is more appropriate for testing than for real use, since it skips over usual semantics around unknowns but as a consequence allows testing the result of another operation that is expected to return unknown. It returns a primitive Go bool rather than a Value to remind us that it is not a first-class value operation.

func (Value) Refine added in v1.13.0

func (v Value) Refine() *RefinementBuilder

Refine creates a RefinementBuilder with which to annotate the reciever with zero or more additional refinements that constrain the range of the value.

Calling methods on a RefinementBuilder for a known value essentially just serves as assertions about the range of that value, leading to panics if those assertions don't hold in practice. This is mainly supported just to make programs that rely on refinements automatically self-check by using the refinement codepath unconditionally on both placeholders and final values for those placeholders. It's always a bug to refine the range of an unknown value and then later substitute an exact value outside of the refined range.

Calling methods on a RefinementBuilder for an unknown value is perhaps more useful because the newly-refined value will then be a placeholder for a smaller range of values and so it may be possible for other operations on the unknown value to return a known result despite the exact value not yet being known.

It is never valid to refine DynamicVal, because that value is a placeholder for a value about which we knkow absolutely nothing. A value must at least have a known root type before it can support further refinement.

func (Value) RefineNotNull added in v1.13.0

func (v Value) RefineNotNull() Value

RefineNotNull is a shorthand for Value.Refine().NotNull().NewValue(), because declaring that a unknown value isn't null is by far the most common use of refinements.

func (Value) RefineWith added in v1.13.0

func (v Value) RefineWith(refiners ...func(*RefinementBuilder) *RefinementBuilder) Value

RefineWith is a variant of Refine which uses callback functions instead of the builder pattern.

The result is equivalent to passing the return value of Value.Refine to the first callback, and then continue passing the builder through any other callbacks in turn, and then calling RefinementBuilder.NewValue on the final result.

The builder pattern approach of Value.Refine is more convenient for inline annotation of refinements when constructing a value, but this alternative approach may be more convenient when applying pre-defined collections of refinements, or when refinements are defined separately from the values they will apply to.

Each refiner callback should return the same pointer that it was given, typically after having mutated it using the RefinementBuilder methods. It's invalid to return a different builder.

func (Value) Subtract

func (val Value) Subtract(other Value) Value

Subtract returns receiver minus the given other value. Both values must be numbers; this method will panic if not.

func (Value) True

func (val Value) True() bool

True returns true if the receiver is True, false if False, and panics if the receiver is not of type Bool.

This is a helper function to help write application logic that works with values, rather than a first-class operation. It does not work with unknown or null values. For more robust handling with unknown value short-circuiting, use val.Equals(cty.True).

func (Value) Type

func (val Value) Type() Type

Type returns the type of the value.

func (Value) Unmark added in v1.2.0

func (val Value) Unmark() (Value, ValueMarks)

Unmark separates the marks of the receiving value from the value itself, removing a new unmarked value and a map (representing a set) of the marks.

If the receiver isn't marked, Unmark returns it verbatim along with a nil map of marks.

func (Value) UnmarkDeep added in v1.2.0

func (val Value) UnmarkDeep() (Value, ValueMarks)

UnmarkDeep is similar to Unmark, but it works with an entire nested structure rather than just the given value directly.

The result is guaranteed to contain no nested values that are marked, and the returned marks set includes the superset of all of the marks encountered during the operation.

func (Value) UnmarkDeepWithPaths added in v1.7.0

func (val Value) UnmarkDeepWithPaths() (Value, []PathValueMarks)

UnmarkDeepWithPaths is like UnmarkDeep, except it returns a slice of PathValueMarks rather than a superset of all marks. This allows a caller to know which marks are associated with which paths in the Value.

func (Value) WithMarks added in v1.2.0

func (val Value) WithMarks(marks ...ValueMarks) Value

WithMarks returns a new value that has the same type and underlying value as the receiver and also has the marks from the given maps (representing sets).

func (Value) WithSameMarks added in v1.2.0

func (val Value) WithSameMarks(srcs ...Value) Value

WithSameMarks returns a new value that has the same type and underlying value as the receiver and also has the marks from the given source values.

Use this if you are implementing your own higher-level operations against cty using the integration methods, to re-introduce the marks from the source values of the operation.

type ValueMarks added in v1.2.0

type ValueMarks map[interface{}]struct{}

ValueMarks is a map, representing a set, of "mark" values associated with a Value. See Value.Mark for more information on the usage of mark values.

func NewValueMarks added in v1.2.0

func NewValueMarks(marks ...interface{}) ValueMarks

NewValueMarks constructs a new ValueMarks set with the given mark values.

If any of the arguments are already ValueMarks values then they'll be merged into the result, rather than used directly as individual marks.

func (ValueMarks) Equal added in v1.2.0

func (m ValueMarks) Equal(o ValueMarks) bool

Equal returns true if the receiver and the given ValueMarks both contain the same marks.

func (ValueMarks) GoString added in v1.2.0

func (m ValueMarks) GoString() string

type ValueRange added in v1.13.0

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

ValueRange offers partial information about the range of a value.

This is primarily interesting for unknown values, because it provides access to any additional known constraints (specified using "refinements") on the range of the value beyond what is represented by the value's type.

func (ValueRange) CouldBeNull added in v1.13.0

func (r ValueRange) CouldBeNull() bool

CouldBeNull returns true unless the value being described is definitely known to represent a non-null value.

func (ValueRange) DefinitelyNotNull added in v1.13.0

func (r ValueRange) DefinitelyNotNull() bool

DefinitelyNotNull returns true if there are no null values in the range.

func (ValueRange) Includes added in v1.13.0

func (r ValueRange) Includes(v Value) Value

Includes determines whether the given value is in the receiving range.

It can return only three possible values:

  • cty.True if the range definitely includes the value
  • cty.False if the range definitely does not include the value
  • An unknown value of cty.Bool if there isn't enough information to decide.

This function is not fully comprehensive: it may return an unknown value in some cases where a definitive value could be computed in principle, and those same situations may begin returning known values in later releases as the rules are refined to be more complete. Currently the rules focus mainly on answering cty.False, because disproving membership tends to be more useful than proving membership.

func (ValueRange) LengthLowerBound added in v1.13.0

func (r ValueRange) LengthLowerBound() int

LengthLowerBound returns information about the lower bound of the length of a collection-typed value, or panics if the value is definitely not a collection.

If the value is nullable then the result represents the range of the length only if the value turns out not to be null.

func (ValueRange) LengthUpperBound added in v1.13.0

func (r ValueRange) LengthUpperBound() int

LengthUpperBound returns information about the upper bound of the length of a collection-typed value, or panics if the value is definitely not a collection.

If the value is nullable then the result represents the range of the length only if the value turns out not to be null.

The resulting value might itself be an unknown number if there is no known upper bound. In that case the "inclusive" flag is meaningless.

func (ValueRange) NumberLowerBound added in v1.13.0

func (r ValueRange) NumberLowerBound() (min Value, inclusive bool)

NumberLowerBound returns information about the lower bound of the range of a number value, or panics if the value is definitely not a number.

If the value is nullable then the result represents the range of the number only if it turns out not to be null.

The resulting value might itself be an unknown number if there is no known lower bound. In that case the "inclusive" flag is meaningless.

func (ValueRange) NumberUpperBound added in v1.13.0

func (r ValueRange) NumberUpperBound() (max Value, inclusive bool)

NumberUpperBound returns information about the upper bound of the range of a number value, or panics if the value is definitely not a number.

If the value is nullable then the result represents the range of the number only if it turns out not to be null.

The resulting value might itself be an unknown number if there is no known upper bound. In that case the "inclusive" flag is meaningless.

func (ValueRange) StringPrefix added in v1.13.0

func (r ValueRange) StringPrefix() string

StringPrefix returns a string that is guaranteed to be the prefix of the string value being described, or panics if the value is definitely not a string.

If the value is nullable then the result represents the prefix of the string only if it turns out to not be null.

If the resulting value is zero-length then the value could potentially be a string but it has no known prefix.

cty.String values always contain normalized UTF-8 sequences; the result is also guaranteed to be a normalized UTF-8 sequence so the result also represents the exact bytes of the string value's prefix.

func (ValueRange) TypeConstraint added in v1.13.0

func (r ValueRange) TypeConstraint() Type

TypeConstraint returns a type constraint describing the value's type as precisely as possible with the available information.

type ValueSet

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

ValueSet is to cty.Set what []cty.Value is to cty.List and map[string]cty.Value is to cty.Map. It's provided to allow callers a convenient interface for manipulating sets before wrapping them in cty.Set values using cty.SetValFromValueSet.

Unlike value slices and value maps, ValueSet instances have a single homogenous element type because that is a requirement of the underlying set implementation, which uses the element type to select a suitable hashing function.

Set mutations are not concurrency-safe.

func NewValueSet

func NewValueSet(ety Type) ValueSet

NewValueSet creates and returns a new ValueSet with the given element type.

func (ValueSet) Add

func (s ValueSet) Add(v Value)

Add inserts the given value into the receiving set.

func (ValueSet) Copy

func (s ValueSet) Copy() ValueSet

Copy performs a shallow copy of the receiving set, returning a new set with the same rules and elements.

func (ValueSet) ElementType

func (s ValueSet) ElementType() Type

ElementType returns the element type for the receiving ValueSet.

func (ValueSet) Has

func (s ValueSet) Has(v Value) bool

Has returns true if the given value is in the receiving set, or false if it is not.

func (ValueSet) Intersection

func (s ValueSet) Intersection(other ValueSet) ValueSet

Intersection returns a new set that contains the values that both the receiver and given sets have in common. Both sets must have the same element type, or else this function will panic.

func (ValueSet) Length

func (s ValueSet) Length() int

Length returns the number of values in the set.

func (ValueSet) Remove

func (s ValueSet) Remove(v Value)

Remove deletes the given value from the receiving set, if indeed it was there in the first place. If the value is not present, this is a no-op.

func (ValueSet) Subtract

func (s ValueSet) Subtract(other ValueSet) ValueSet

Subtract returns a new set that contains all of the values from the receiver that are not also in the given set. Both sets must have the same element type, or else this function will panic.

func (ValueSet) SymmetricDifference

func (s ValueSet) SymmetricDifference(other ValueSet) ValueSet

SymmetricDifference returns a new set that contains all of the values from both the receiver and given sets, except those that both sets have in common. Both sets must have the same element type, or else this function will panic.

func (ValueSet) Union

func (s ValueSet) Union(other ValueSet) ValueSet

Union returns a new set that contains all of the members of both the receiving set and the given set. Both sets must have the same element type, or else this function will panic.

func (ValueSet) Values

func (s ValueSet) Values() []Value

Values returns a slice of all of the values in the set in no particular order.

Directories

Path Synopsis
Package convert contains some routines for converting between cty types.
Package convert contains some routines for converting between cty types.
Package ctystrings is a collection of string manipulation utilities which intend to help application developers implement string-manipulation functionality in a way that respects the cty model of strings, even when they are working in the realm of Go strings.
Package ctystrings is a collection of string manipulation utilities which intend to help application developers implement string-manipulation functionality in a way that respects the cty model of strings, even when they are working in the realm of Go strings.
Package function builds on the functionality of cty by modeling functions that operate on cty Values.
Package function builds on the functionality of cty by modeling functions that operate on cty Values.
stdlib
Package stdlib is a collection of cty functions that are expected to be generally useful, and are thus factored out into this shared library in the hope that cty-using applications will have consistent behavior when using these functions.
Package stdlib is a collection of cty functions that are expected to be generally useful, and are thus factored out into this shared library in the hope that cty-using applications will have consistent behavior when using these functions.
Package gocty deals with converting between cty Values and native go values.
Package gocty deals with converting between cty Values and native go values.
Package json provides functions for serializing cty types and values in JSON format, and for decoding them again.
Package json provides functions for serializing cty types and values in JSON format, and for decoding them again.
Package msgpack provides functions for serializing cty values in the msgpack encoding, and decoding them again.
Package msgpack provides functions for serializing cty values in the msgpack encoding, and decoding them again.

Jump to

Keyboard shortcuts

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