cty

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2019 License: MIT Imports: 13 Imported by: 2,763

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 InternalTypesToRegister []interface{}

InternalTypesToRegister is a slice of values that covers all of the internal types used in the representation of cty.Type and cty.Value across all cty Types.

This is intended to be used to register these types with encoding packages that require registration of types used in interfaces, such as encoding/gob, thus allowing cty types and values to be included in streams created from those packages. However, registering with gob is not necessary since that is done automatically as a side-effect of importing this package.

Callers should not do anything with the values here except pass them on verbatim to a registration function.

If the calling application uses Capsule types that wrap local structs either directly or indirectly, these structs may also need to be registered in order to support encoding and decoding of values of these types. That is the responsibility of the calling application.

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 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 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 IndexPath

func IndexPath(v Value) Path

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

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) 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) 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) 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 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 supports no operations except equality, and equality is implemented by pointer identity of the encapsulated pointer.

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

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

GobDecode is an implementatino of the gob.GobDecoder interface, which reverses the encoding performed by GobEncode to allow types to be recovered from gob buffers.

func (Type) GobEncode

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

GobEncode is an implementation of the gob.GobEncoder interface, which allows Types to be included in structures encoded with encoding/gob.

Currently it is not possible to represent capsule types in gob.

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 list 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) 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.

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

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

func (val *Value) GobDecode(buf []byte) error

GobDecode is an implementation of the gob.GobDecoder interface, which inverts the operation performed by GobEncode. See the documentation of GobEncode for considerations when using cty.Value instances with gob.

func (Value) GobEncode

func (val Value) GobEncode() ([]byte, error)

GobEncode is an implementation of the gob.GobEncoder interface, which allows Values to be included in structures encoded with encoding/gob.

Currently it is not possible to represent values of capsule types in gob, because the types themselves cannot be represented.

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) 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) 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, call AsString and take the length of the native Go string that is returned.

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.

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

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