Movatterモバイル変換


[0]ホーム

URL:


cty

package
v1.17.0Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License:MITImports:17Imported by:3,277

Details

Repository

github.com/zclconf/go-cty

Links

Documentation

Overview

Package cty (pronounced see-tie) provides some infrastructure for a typesystem that might be useful for applications that need to representconfiguration values provided by the user whose types are not knownat compile time, particularly if the calling application also allowssuch values to be used in expressions.

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

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

This package is oriented towards being a building block for configurationlanguages used to bootstrap an application. It is not optimized for usein 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 errorand has no useful type to return. It should not be used and any methodscalled 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 returningwith 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 byNullVal. NilVal is a nil within the *Go* type system, and is invalid inthe cty type system. Null values *do* exist in the cty type system.

Functions

funcCanListValadded inv1.8.1

func CanListVal(vals []Value)bool

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

funcCanMapValadded inv1.8.1

func CanMapVal(vals map[string]Value)bool

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

funcCanSetValadded inv1.8.1

func CanSetVal(vals []Value)bool

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

funcDeepValuesadded inv1.17.0

func DeepValues(valValue)iter.Seq2[Path,Value]

DeepValues returns an iterable sequence containing at least the givenvalue but also, if it is of a collection or structural type, the other valuesnested within it recursively.

ThePath values in different elements of the sequence may share a backingarray to reduce garbage generated during iteration, so if a caller wishes topreserve a path outside of a single loop iteration the caller must copy it toa separate Path value with its own separate backing array, such as by callingPath.Copy.

funcNormalizeString

func NormalizeString(sstring)string

NormalizeString applies the same normalization that cty applies whenconstructing string values.

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

funcValueMarksOfTypeadded inv1.17.0

func ValueMarksOfType[Tany](vValue)iter.Seq[T]

ValueMarksOfType returns an iterable sequence of any marks directlyassociated with the given value that can be type-asserted to the giventype.

funcValueMarksOfTypeDeepadded inv1.17.0

func ValueMarksOfTypeDeep[Tany](vValue)iter.Seq[T]

ValueMarksOfTypeDeep is likeValueMarksOfType but also visits any valuesnested inside the given value.

The same value may be produced multiple times if multiple nested values aremarked with it.

funcWalk

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

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

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

New callers may prefer to useDeepValues instead, because that returnsa result usable with a normal for loop.

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

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

Types

typeCapsuleOpsadded inv1.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(valany)string// TypeGoString provides the GoString implementation for the corresponding// capsule type itself.TypeGoString func(goTyreflect.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, bany)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, bany)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(vany)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(srcType) func(any,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(dstType) func(Value,Path) (any,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(keyany)any}

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 beset to an implementation of the corresponding operation. If an operationfunction is nil then it isn't supported for the given capsule type.

typeElementCallback

type ElementCallback func(keyValue, valValue) (stopbool)

ElementCallback is a callback type used for iterating over elements ofcollections 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 tocontinue iterating.

typeElementIterator

type ElementIterator interface {Next()boolElement() (keyValue, valueValue)}

ElementIterator is the interface type returned by Value.ElementIterator toallow 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()    // ...}

typeGetAttrStep

type GetAttrStep struct {Namestring// contains filtered or unexported fields}

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

func (GetAttrStep)Apply

func (sGetAttrStep) Apply(valValue) (Value,error)

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

func (GetAttrStep)GoString

func (sGetAttrStep) GoString()string

typeIndexStep

type IndexStep struct {KeyValue// contains filtered or unexported fields}

IndexStep is a Step implementation representing applying the index operationto 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 accesseditself, since in sets elements are their own identity.

func (IndexStep)Apply

func (sIndexStep) Apply(valValue) (Value,error)

Apply returns the value resulting from indexing the given value withour key value.

func (IndexStep)GoString

func (sIndexStep) GoString()string

typePath

type Path []PathStep

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

The empty Path represents the given item. Any PathSteps within representtaking 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 manuallyand convert to this type, which may be more appropriate in environmentswhere memory pressure is a concern.

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

funcGetAttrPath

func GetAttrPath(namestring)Path

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

funcIndexIntPathadded inv1.4.0

func IndexIntPath(vint)Path

IndexIntPath is a typed convenience method for IndexPath.

funcIndexPath

func IndexPath(vValue)Path

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

funcIndexStringPathadded inv1.4.0

func IndexStringPath(vstring)Path

IndexStringPath is a typed convenience method for IndexPath.

func (Path)Apply

func (pPath) Apply(valValue) (Value,error)

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

func (Path)Copy

func (pPath) Copy()Path

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

func (Path)Equalsadded inv1.1.0

func (pPath) Equals(otherPath)bool

Equals compares 2 Paths for exact equality.

func (Path)GetAttr

func (pPath) GetAttr(namestring)Path

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

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

func (Path)HasPrefixadded inv1.1.0

func (pPath) HasPrefix(prefixPath)bool

HasPrefix determines if the path p contains the provided prefix.

func (Path)Index

func (pPath) Index(vValue)Path

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

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

func (Path)IndexIntadded inv1.4.0

func (pPath) IndexInt(vint)Path

IndexInt is a typed convenience method for Index.

func (Path)IndexStringadded inv1.4.0

func (pPath) IndexString(vstring)Path

IndexString is a typed convenience method for Index.

func (Path)LastStep

func (pPath) LastStep(valValue) (Value,PathStep,error)

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

This is useful when dealing with assignment operations, since in thatcase 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 errorsfor 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 thegiven value.

func (Path)NewError

func (pPath) NewError(errerror)error

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

func (Path)NewErrorf

func (pPath) NewErrorf(fstring, args ...any)error

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

typePathError

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

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

typePathSet

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.

funcNewPathSet

func NewPathSet(paths ...Path)PathSet

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

func (PathSet)Add

func (sPathSet) Add(pathPath)

Add inserts a single given path into the set.

Paths are immutable after construction by convention. It is particularlyimportant 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 (sPathSet) AddAllSteps(pathPath)

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

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

func (PathSet)Empty

func (sPathSet) Empty()bool

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

func (PathSet)Equal

func (sPathSet) Equal(otherPathSet)bool

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

func (PathSet)Has

func (sPathSet) Has(pathPath)bool

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

func (PathSet)Intersection

func (sPathSet) Intersection(otherPathSet)PathSet

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

func (PathSet)List

func (sPathSet) 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 (sPathSet) Remove(pathPath)

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 (sPathSet) Subtract(otherPathSet)PathSet

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

func (PathSet)SymmetricDifference

func (sPathSet) SymmetricDifference(otherPathSet)PathSet

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

func (PathSet)Union

func (sPathSet) Union(otherPathSet)PathSet

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

typePathStep

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

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

typePathValueMarksadded inv1.7.0

type PathValueMarks struct {PathPathMarksValueMarks}

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

func (PathValueMarks)Equaladded inv1.7.0

typeRefinementBuilderadded inv1.13.0

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

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

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

func (*RefinementBuilder)CollectionLengthadded inv1.13.0

func (b *RefinementBuilder) CollectionLength(lengthint) *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 collapseto 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 methodif the caller knows that there will be the given number of _unique_ valuesin the set. If any values might potentially coalesce together once known,use [CollectionLengthUpperBound] instead.

func (*RefinementBuilder)CollectionLengthLowerBoundadded inv1.13.0

func (b *RefinementBuilder) CollectionLengthLowerBound(minint) *RefinementBuilder

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

func (*RefinementBuilder)CollectionLengthUpperBoundadded inv1.13.0

func (b *RefinementBuilder) CollectionLengthUpperBound(maxint) *RefinementBuilder

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

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

func (*RefinementBuilder)NewValueadded inv1.13.0

func (b *RefinementBuilder) NewValue() (retValue)

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

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

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

func (*RefinementBuilder)NotNulladded inv1.13.0

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)Nulladded inv1.13.0

Null constrains the value as definitely null.

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

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

func (*RefinementBuilder)NumberRangeInclusiveadded inv1.13.0

func (b *RefinementBuilder) NumberRangeInclusive(min, maxValue) *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 onemay 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 thisfunction will panic.

func (*RefinementBuilder)NumberRangeLowerBoundadded inv1.13.0

func (b *RefinementBuilder) NumberRangeLowerBound(minValue, inclusivebool) *RefinementBuilder

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

func (*RefinementBuilder)NumberRangeUpperBoundadded inv1.13.0

func (b *RefinementBuilder) NumberRangeUpperBound(maxValue, inclusivebool) *RefinementBuilder

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

func (*RefinementBuilder)StringPrefixadded inv1.13.0

func (b *RefinementBuilder) StringPrefix(prefixstring) *RefinementBuilder

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

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

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

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

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

func (*RefinementBuilder)StringPrefixFulladded inv1.13.0

func (b *RefinementBuilder) StringPrefixFull(prefixstring) *RefinementBuilder

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

Applications which fully control the subsequent characters can use thisas long as they guarantee that the characters added later cannot possiblycombine with characters at the end of the prefix to form a single graphemecluster. For example, it would be unsafe to use the full prefix "hello" ifthere is any chance that the final string will add a combining diacriticcharacter after the "o", because that would then change the final character.

UseRefinementBuilder.StringPrefix instead if an application cannot fullycontrol the final result to avoid violating this rule.

typeTransformeradded inv1.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 apossibly-complex structure. The Enter method is called before traversingthrough a given path, and the Exit method is called when traversal of apath 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 functionreturns, since its backing array is re-used for other calls.

typeType

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 concreteimplementations provided within this package are considered valid.

var BoolType

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

var DynamicPseudoTypeType

DynamicPseudoType represents the dynamic pseudo-type.

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

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

var EmptyObjectType

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

var EmptyTupleType

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

var NumberType

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

var StringType

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

funcCapsule

func Capsule(namestring, nativeTypereflect.Type)Type

Capsule creates a new Capsule type.

A Capsule type is a special type that can be used to transport arbitraryGo native values of a given type through the cty type system. A languagethat uses cty as its type system might, for example, provide functionsthat return capsule-typed values and then other functions that operateon 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 totransport. Capsule types compare by identity, so each call to theCapsule function creates an entirely-distinct cty Type, even if two callsuse the same native type.

Each capsule-typed value contains a pointer to a value of the given nativetype. A capsule-typed value by default supports no operations exceptequality, and equality is implemented by pointer identity of theencapsulated pointer. A capsule type can optionally have its ownimplementations of certain operations if it is created with CapsuleWithOpsinstead of Capsule.

The given name is used as the new type's "friendly name". This can be anystring in principle, but will usually be a short, all-lowercase name aimedat 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 acalling application opts in to including them within its own type systemby creating them and introducing them via its own functions. At that point,the application is responsible for dealing with any capsule-typed valuesthat might be returned.

funcCapsuleWithOpsadded inv1.2.0

func CapsuleWithOps(namestring, nativeTypereflect.Type, ops *CapsuleOps)Type

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

All of the other caveats and restrictions for capsule types still apply, butoverloaded operations can potentially help a capsule type participate betterin cty operations.

funcList

func List(elemType)Type

List creates a map type with the given element Type.

List types are CollectionType implementations.

funcMap

func Map(elemType)Type

Map creates a map type with the given element Type.

Map types are CollectionType implementations.

funcObject

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.

funcObjectWithOptionalAttrsadded inv1.6.0

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

ObjectWithOptionalAttrs creates an object type where some of its attributesare optional.

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

Optional attributes are significant only when an object type is being usedas a target type for conversion in the "convert" package. A value of anobject type always has a value for each of the attributes in the attributetypes 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 longeraccess it, since ownership is transferred to this library.

funcSet

func Set(elemType)Type

Set creates a set type with the given element Type.

Set types are CollectionType implementations.

funcTuple

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 accessthe underlying array, since ownership is transferred to this library.

func (Type)AttributeOptionaladded inv1.6.0

func (tType) AttributeOptional(namestring)bool

AttributeOptional returns true if the attribute of the given name isoptional.

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

func (Type)AttributeType

func (tType) AttributeType(namestring)Type

AttributeType returns the type of the attribute with the given name. Willpanic 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 (tType) AttributeTypes() map[string]Type

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

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

func (Type)CapsuleExtensionDataadded inv1.2.0

func (tyType) CapsuleExtensionData(keyany)any

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

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

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

func (Type)CapsuleOpsadded inv1.2.0

func (tyType) 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 (tType) ElementType()Type

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

func (Type)EncapsulatedType

func (tType) 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 (tType) Equals(otherType)bool

Equals returns true if the other given Type exactly equals the receivertype.

func (Type)FriendlyName

func (tType) FriendlyName()string

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

func (Type)FriendlyNameForConstraint

func (tType) FriendlyNameForConstraint()string

FriendlyNameForConstraint is similar to FriendlyName except that theresult is specialized for describing type _constraints_ rather than typesthemselves. This is more appropriate when reporting that a particular valuedoes not conform to an expected type constraint.

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

func (Type)GoString

func (tType) GoString()string

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

func (Type)HasAttribute

func (tType) HasAttribute(namestring)bool

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

func (Type)HasDynamicTypes

func (tType) HasDynamicTypes()bool

HasDynamicTypes returns true either if the receiver is itselfDynamicPseudoType or if it is a compound type whose descendent elementsare DynamicPseudoType.

func (Type)IsCapsuleType

func (tType) IsCapsuleType()bool

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

func (Type)IsCollectionType

func (tType) IsCollectionType()bool

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

func (Type)IsListType

func (tType) IsListType()bool

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

func (Type)IsMapType

func (tType) IsMapType()bool

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

func (Type)IsObjectType

func (tType) IsObjectType()bool

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

func (Type)IsPrimitiveType

func (tType) IsPrimitiveType()bool

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

func (Type)IsSetType

func (tType) IsSetType()bool

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

func (Type)IsTupleType

func (tType) IsTupleType()bool

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

func (Type)Length

func (tType) 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 determinewhether this operation will succeed.

func (Type)ListElementType

func (tType) ListElementType() *Type

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

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

func (Type)MapElementType

func (tType) MapElementType() *Type

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

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

func (Type)MarshalJSON

func (tType) MarshalJSON() ([]byte,error)

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

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

func (Type)OptionalAttributesadded inv1.6.0

func (tType) OptionalAttributes() map[string]struct{}

OptionalAttributes returns a map representing the set of attributesthat 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 providedfor read access only. It is forbidden for any caller to modify the returnedmap.

func (Type)SetElementType

func (tType) SetElementType() *Type

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

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

func (Type)TestConformance

func (tType) TestConformance(otherType) []error

TestConformance recursively walks the receiver and the given other type andreturns 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 andcontain at least one error value. It will be nil if the type is entirelyconformant.

Note that the special behavior of PseudoTypeDynamic is the *only* exceptionto normal type equality. Calling applications may wish to apply their ownautomatic conversion logic to the given data structure to create a moreliberal notion of conformance to a type.

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

func (Type)TupleElementType

func (tType) TupleElementType(idxint)Type

TupleElementType returns the type of the element with the given index. Willpanic 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 (tType) TupleElementTypes() []Type

TupleElementTypes returns a slice of the recieving tuple type's elementtypes. Will panic if the receiver is not a tuple type (use IsTupleTypeto confirm).

The returned slice is part of the internal state of the type, and is providedfor read access only. It is forbidden for any caller to modify theunderlying array. For many purposes the element-related methods of Valueare 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 ofMarshalJSON for information on the limitations of JSON serialization oftypes.

func (Type)WithoutOptionalAttributesDeepadded inv1.8.1

func (tType) WithoutOptionalAttributesDeep()Type

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

typeValue

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

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

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

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

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

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

var DynamicValValue

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

var EmptyObjectValValue

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

var EmptyTupleValValue

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

var FalseValue

False is the falsey value of type Bool

var NegativeInfinityValue

NegativeInfinity is a Number value representing negative infinity

var PositiveInfinityValue

PositiveInfinity is a Number value representing positive infinity

var TrueValue

True is the truthy value of type Bool

var ZeroValue

Zero is a number value representing exactly zero.

funcBoolVal

func BoolVal(vbool)Value

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

funcCapsuleVal

func CapsuleVal(tyType, wrapValany)Value

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

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

funcListVal

func ListVal(vals []Value)Value

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

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

funcListValEmpty

func ListValEmpty(elementType)Value

ListValEmpty returns an empty list of the given element type.

funcMapVal

func MapVal(vals map[string]Value)Value

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

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

funcMapValEmpty

func MapValEmpty(elementType)Value

MapValEmpty returns an empty map of the given element type.

funcMustParseNumberVal

func MustParseNumberVal(sstring)Value

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

funcNullVal

func NullVal(tType)Value

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

funcNumberFloatVal

func NumberFloatVal(vfloat64)Value

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

funcNumberIntVal

func NumberIntVal(vint64)Value

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

funcNumberUIntVal

func NumberUIntVal(vuint64)Value

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

funcNumberVal

func NumberVal(v *big.Float)Value

NumberVal returns a Value of type Number whose internal value is the givenbig.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'swrapped in this way.

funcObjectVal

func ObjectVal(attrs map[string]Value)Value

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

funcParseNumberVal

func ParseNumberVal(sstring) (Value,error)

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

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

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

funcSetVal

func SetVal(vals []Value)Value

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

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

funcSetValEmpty

func SetValEmpty(elementType)Value

SetValEmpty returns an empty set of the given element type.

funcSetValFromValueSet

func SetValFromValueSet(sValueSet)Value

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

The element type of the returned value is the element type of the givenset.

funcStringVal

func StringVal(vstring)Value

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

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

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

funcTransform

func Transform(valValue, 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 toreplace that value.

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

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

The callback function may halt the walk altogether byreturning a non-nil error. If the returned error is about the elementcurrently being visited, it is recommended to use the provided pathvalue to produce a PathError describing that context.

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

funcTransformWithTransformeradded inv1.7.0

func TransformWithTransformer(valValue, tTransformer) (Value,error)

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

funcTupleVal

func TupleVal(elems []Value)Value

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

funcUnknownAsNull

func UnknownAsNull(valValue)Value

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

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

funcUnknownVal

func UnknownVal(tType)Value

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

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

func (Value)Absolute

func (valValue) Absolute()Value

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

func (Value)Add

func (valValue) Add(otherValue)Value

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

func (Value)And

func (valValue) And(otherValue)Value

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

func (Value)AsBigFloat

func (valValue) AsBigFloat() *big.Float

AsBigFloat returns a big.Float representation of a non-null, non-unknowncty.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 (valValue) AsString()string

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

func (Value)AsValueMap

func (valValue) 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 calledon any other value.

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

func (Value)AsValueSet

func (valValue) AsValueSet()ValueSet

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

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

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

func (Value)AsValueSlice

func (valValue) AsValueSlice() []Value

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

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

func (Value)CanIterateElements

func (valValue) CanIterateElements()bool

CanIterateElements returns true if the receiver can support theElements, ElementIterator, and ForEachElement methods without panic.

func (Value)ContainsMarkedadded inv1.2.0

func (valValue) ContainsMarked()bool

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

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

func (Value)Divide

func (valValue) Divide(otherValue)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 eitherPositiveInfinity or NegativeInfinity, depending on the sign of thereceiver value. For some use-cases the presence of infinities may beundesirable, in which case the caller should check whether theother value equals zero before calling and raise an error instead.

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

func (Value)ElementIterator

func (valValue) ElementIterator()ElementIterator

ElementIterator returns an ElementIterator for iterating the elementsof the receiver, which must be a collection type, a tuple type, or an objecttype. 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.

The element iterator produces keys and values matching what's describedforValue.Elements. New code should prefer to useValue.Elements.

func (Value)Elementsadded inv1.17.0

func (valValue) Elements()iter.Seq2[Value,Value]

Elements returns an iterable sequence over the elements of the reciever,which must be a collection type, a tuple type, or an object type.If called on a value of any other type, this method will panic.The value must also be known, non-null, and unmarked, or this method willpanic.

UseValue.CanIterateElements to check dynamically if a particular valuecan support this method without panicking.

The two values in each iteration represent a key and a value respectively.

If the receiver is of list type then the key is guaranteed to be of typeNumber and the values are of the list's element type.

The the reciever is of a map type then the key is guaranteed to be of typeString and the values are of the map's element type. Elements areproduced in ascending lexicographical order by key.

If the receiver is of a set type then each element is returned as both thekey and the value, because set member values are their own identity.

If the reciever is of a tuple type then the key is guaranteed to be of typeNumber and the and the value types match the corresponding element types.

If the reciever is of an object type then the key is guaranteed to be oftypeString and the value types match the corresponding attribute types.

func (Value)EncapsulatedValue

func (valValue) EncapsulatedValue()any

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 createthe value. Since cty considers values to be immutable, it is stronglyrecommended to treat the encapsulated value itself as immutable too.

func (Value)Equals

func (valValue) Equals(otherValue)Value

Equals returns True if the receiver and the given other value have thesame 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 ifeither of the given values are.

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

func (Value)False

func (valValue) False()bool

False is the opposite of True.

func (Value)ForEachElement

func (valValue) ForEachElement(cbElementCallback)bool

ForEachElement executes a given callback function for each element ofthe receiver, which must be a collection type or tuple type, or this methodwill panic.

ForEachElement uses ElementIterator internally, and so the values passedto the callback are as described forValue.Elements. New code shouldprefer to useValue.Elements in a normal for loop instead of using thismethod.

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

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

func (Value)GetAttr

func (valValue) GetAttr(namestring)Value

GetAttr returns the value of the given attribute of the receiver, whichmust 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 definedfor the value's type. Use the attribute-related methods on Type tocheck 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 (valValue) GoString()string

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

func (Value)GreaterThan

func (valValue) GreaterThan(otherValue)Value

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

func (Value)GreaterThanOrEqualTo

func (valValue) GreaterThanOrEqualTo(otherValue)Value

GreaterThanOrEqualTo is equivalent to GreaterThan and Equal combined with Or.

func (Value)HasElement

func (valValue) HasElement(elemValue)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 thegiven 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 (valValue) HasIndex(keyValue)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 thekey value are unknown.

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

func (Value)HasMarkadded inv1.2.0

func (valValue) HasMark(markany)bool

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

func (Value)HasMarkDeepadded inv1.17.0

func (valValue) HasMarkDeep(markany)bool

HasMarkDeep is like [HasMark] but also searches any values nested insidethe given value.

func (Value)HasSameMarksadded inv1.2.0

func (valValue) HasSameMarks(otherValue)bool

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

func (Value)HasWhollyKnownTypeadded inv1.5.0

func (valValue) HasWhollyKnownType()bool

HasWhollyKnownType checks if the value is dynamic, or contains any nestedDynamicVal. This implies that both the value is not known, and the finaltype may change.

func (Value)Hash

func (valValue) Hash()int

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

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

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

func (Value)Index

func (valValue) Index(keyValue)Value

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

The key value must be the correct type for the receving collection: anumber 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 intor this method will panic. The key may alternatively be ofDynamicPseudoType, in which case the result itself is an unknown of thecollection's element type.

The result is of the receiver collection's element type, or in the caseof 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 (valValue) IsKnown()bool

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

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

func (Value)IsMarkedadded inv1.2.0

func (valValue) IsMarked()bool

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

func (Value)IsNull

func (valValue) IsNull()bool

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

func (Value)IsWhollyKnown

func (valValue) IsWhollyKnown()bool

IsWhollyKnown is an extension of IsKnown that also recursively checksinside collections and structures to see if there are any nested unknownvalues.

func (Value)Length

func (valValue) Length()Value

Length returns the length of the receiver, which must be a collection typeor tuple type, as a number value. If the receiver is not a compatible typethen 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 lengthof a string, use the Length function in funcs/stdlib.

func (Value)LengthInt

func (valValue) LengthInt()int

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

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

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

func (Value)LessThan

func (valValue) LessThan(otherValue)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 (valValue) LessThanOrEqualTo(otherValue)Value

LessThanOrEqualTo is equivalent to LessThan and Equal combined with Or.

func (Value)Markadded inv1.2.0

func (valValue) Mark(markany)Value

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

Marks are used to carry additional application-specific characteristicsassociated with values. A marked value can be used with operation methods,in which case the marks are propagated to the operation results. A markedvalue _cannot_ be used with integration methods, so callers of thosemust derive an unmarked value using Unmark (and thus explicitly handlethe 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 itselfas a namespace for markings. That type can be unexported if desired, inorder to ensure that the mark can only be handled through the definingpackage's own functions.

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

func (Value)MarkWithPathsadded inv1.7.0

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

MarkWithPaths accepts a slice of PathValueMarks to applymarkers to particular paths and returns the markedValue.

func (Value)Marksadded inv1.2.0

func (valValue) Marks()ValueMarks

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

func (Value)Modulo

func (valValue) Modulo(otherValue)Value

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

If the "other" value is exactly zero, this operation will return eitherPositiveInfinity or NegativeInfinity, depending on the sign of thereceiver value. For some use-cases the presence of infinities may beundesirable, in which case the caller should check whether theother 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 callersmay wish to disallow such things outright or implement their own moduloif they disagree with the interpretation used here.

func (Value)Multiply

func (valValue) Multiply(otherValue)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 (valValue) 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 (valValue) Not()Value

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

func (Value)NotEqual

func (valValue) NotEqual(otherValue)Value

NotEqual is a shorthand for Equals followed by Not.

func (Value)Or

func (valValue) Or(otherValue)Value

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

func (Value)Rangeadded inv1.13.0

func (vValue) Range()ValueRange

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

This is most relevant for unknown values, because it gives access to anyoptional additional constraints on the final value (specified by the sourceof the value using "refinements") beyond what we can assume from the value'stype.

Calling Range for a known value is a little strange, but it's supported byreturning aValueRange object that describes the exact value as closelyas possible. Typically a caller should work directly with the exact valuein that case, but some purposes might only need the level of detailoffered by ranges and so can share code between both known and unknownvalues.

func (Value)RawEquals

func (valValue) RawEquals(otherValue)bool

RawEquals returns true if and only if the two given values have the sametype and equal value, ignoring the usual short-circuit rules aboutunknowns and dynamic types.

This method is more appropriate for testing than for real use, since itskips over usual semantics around unknowns but as a consequence allowstesting 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 itis not a first-class value operation.

func (Value)Refineadded inv1.13.0

func (vValue) Refine() *RefinementBuilder

Refine creates aRefinementBuilder with which to annotate the recieverwith zero or more additional refinements that constrain the range ofthe value.

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

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

It is never valid to refineDynamicVal, because that value is aplaceholder for a value about which we knkow absolutely nothing. A valuemust at least have a known root type before it can support furtherrefinement.

func (Value)RefineNotNulladded inv1.13.0

func (vValue) RefineNotNull()Value

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

func (Value)RefineWithadded inv1.13.0

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

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

The result is equivalent to passing the return value ofValue.Refine to thefirst callback, and then continue passing the builder through any othercallbacks in turn, and then callingRefinementBuilder.NewValue on thefinal result.

The builder pattern approach ofValue.Refine is more convenient for inlineannotation of refinements when constructing a value, but this alternativeapproach may be more convenient when applying pre-defined collections ofrefinements, or when refinements are defined separately from the valuesthey will apply to.

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

func (Value)Subtract

func (valValue) Subtract(otherValue)Value

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

func (Value)True

func (valValue) True()bool

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

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

func (Value)Type

func (valValue) Type()Type

Type returns the type of the value.

func (Value)Unmarkadded inv1.2.0

func (valValue) 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 nilmap of marks.

func (Value)UnmarkDeepadded inv1.2.0

func (valValue) UnmarkDeep() (Value,ValueMarks)

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

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

func (Value)UnmarkDeepWithPathsadded inv1.7.0

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

UnmarkDeepWithPaths is like UnmarkDeep, except it returns a sliceof PathValueMarks rather than a superset of all marks. This allowsa caller to know which marks are associated with which pathsin the Value.

func (Value)WithMarksadded inv1.2.0

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

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

func (Value)WithSameMarksadded inv1.2.0

func (valValue) WithSameMarks(srcs ...Value)Value

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

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

func (Value)WrangleMarksDeepadded inv1.17.0

func (vValue) WrangleMarksDeep(wranglers ...WrangleFunc) (Value,error)

WrangleMarksDeep is a specialized variant ofTransform that is focusedon interrogating and modifying any marks present throughout a data structure,without modifying anything else about the value.

Refer to theWrangleFunc documentation for more information. Each ofthe provided functions is called in turn for each mark at each distinct path,and the first function that returns a non-nilctymarks.WrangleAction "wins"and prevents any later ones from running for a particular mark/path pair.

The implementation makes a best effort to avoid constructing new valuesunless marks have actually changed, to keep this operation relatively cheapin the presumed-common case where no marks are present at all.

typeValueMarksadded inv1.2.0

type ValueMarks map[any]struct{}

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

funcNewValueMarksadded inv1.2.0

func NewValueMarks(marks ...any)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 mergedinto the result, rather than used directly as individual marks.

func (ValueMarks)Equaladded inv1.2.0

func (mValueMarks) Equal(oValueMarks)bool

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

func (ValueMarks)GoStringadded inv1.2.0

func (mValueMarks) GoString()string

typeValueRangeadded inv1.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 accessto any additional known constraints (specified using "refinements") on therange of the value beyond what is represented by the value's type.

func (ValueRange)CouldBeNulladded inv1.13.0

func (rValueRange) CouldBeNull()bool

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

func (ValueRange)DefinitelyNotNulladded inv1.13.0

func (rValueRange) DefinitelyNotNull()bool

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

func (ValueRange)Includesadded inv1.13.0

func (rValueRange) Includes(vValue)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 ofcty.Bool if there isn't enough information to decide.

This function is not fully comprehensive: it may return an unknown valuein some cases where a definitive value could be computed in principle, andthose same situations may begin returning known values in later releases asthe rules are refined to be more complete. Currently the rules focus mainlyon answeringcty.False, because disproving membership tends to be moreuseful than proving membership.

func (ValueRange)LengthLowerBoundadded inv1.13.0

func (rValueRange) LengthLowerBound()int

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

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

func (ValueRange)LengthUpperBoundadded inv1.13.0

func (rValueRange) LengthUpperBound()int

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

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

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

func (ValueRange)NumberLowerBoundadded inv1.13.0

func (rValueRange) NumberLowerBound() (minValue, inclusivebool)

NumberLowerBound returns information about the lower bound of the range ofa 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 numberonly if it turns out not to be null.

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

func (ValueRange)NumberUpperBoundadded inv1.13.0

func (rValueRange) NumberUpperBound() (maxValue, inclusivebool)

NumberUpperBound returns information about the upper bound of the range ofa 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 numberonly if it turns out not to be null.

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

func (ValueRange)StringPrefixadded inv1.13.0

func (rValueRange) StringPrefix()string

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

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

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

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

func (ValueRange)TypeConstraintadded inv1.13.0

func (rValueRange) TypeConstraint()Type

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

typeValueSet

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

ValueSet is to cty.Set what []cty.Value is to cty.List andmap[string]cty.Value is to cty.Map. It's provided to allow callers aconvenient interface for manipulating sets before wrapping them in cty.Setvalues using cty.SetValFromValueSet.

Unlike value slices and value maps, ValueSet instances have a singlehomogenous element type because that is a requirement of the underlyingset implementation, which uses the element type to select a suitablehashing function.

Set mutations are not concurrency-safe.

funcNewValueSet

func NewValueSet(etyType)ValueSet

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

func (ValueSet)Add

func (sValueSet) Add(vValue)

Add inserts the given value into the receiving set.

func (ValueSet)Copy

func (sValueSet) Copy()ValueSet

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

func (ValueSet)ElementType

func (sValueSet) ElementType()Type

ElementType returns the element type for the receiving ValueSet.

func (ValueSet)Has

func (sValueSet) Has(vValue)bool

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

func (ValueSet)Intersection

func (sValueSet) Intersection(otherValueSet)ValueSet

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

func (ValueSet)Length

func (sValueSet) Length()int

Length returns the number of values in the set.

func (ValueSet)Remove

func (sValueSet) Remove(vValue)

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

func (ValueSet)Subtract

func (sValueSet) Subtract(otherValueSet)ValueSet

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

func (ValueSet)SymmetricDifference

func (sValueSet) SymmetricDifference(otherValueSet)ValueSet

SymmetricDifference returns a new set that contains all of the values fromboth the receiver and given sets, except those that both sets have incommon. Both sets must have the same element type, or else this functionwill panic.

func (ValueSet)Union

func (sValueSet) Union(otherValueSet)ValueSet

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

func (ValueSet)Values

func (sValueSet) Values() []Value

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

typeWrangleFuncadded inv1.17.0

type WrangleFunc func(markany, pathPath) (ctymarks.WrangleAction,error)

WrangleFunc is the signature of a callback function used to visit aparticular mark associated with a particular path within a value.

Path values passed to successive calls to aWrangleFunc may share abacking array, and so if the function wishes to retain a particular pathafter it returns it must usePath.Copy to produce a copy in an unaliasedbacking array.

A function of this type must decide what change to make, if any, to thepresence of this mark at this location. Returning nil means to take noaction at all and to potentially allow other later functions of thistype to decide what to do instead.

If the function returns an error thenValue.WrangleMarksDeep collects itand any other errors returned during traversal, automatically wraps in acty.PathError if not at the root, and returns an [`errors.Join`] of allof the errors if there are more than one. The indicated action is still takenand continued "wrangling" occurs as normal to visit other marks and otherpaths.

cty.Value.WrangleMarksDeep, and this callback signature used with it,are together designed with some assumptions that don't always hold buthave been common enough to make it seem worth supporting with a first-classfeature:

  • All of the different marks on any specific value are orthogonal to oneanother, and so it's possible to decide an action for each one inisolation.
  • Marks within a data structure are orthogonal to the specific values theyare associated with, and so it's possible to decide an action withoutknowning the value it's associated with. (Though it's possible inprinciple to use the given path to retrieve more information when needed,at the expense of some additional traversal overhead.)
  • Most values have no marks at all and when marks are present there arerelatively few of them, and so it's worth making some extra effort tohandle the no-marks case cheaply even if it makes the marks-present casea little more expensive.

If any of these assumptions don't apply to your situation then this may notbe an appropriate solution.cty.Transform orcty.TransformWithTransformermight serve as a more general alternative if you need more control.

Source Files

View all Source files

Directories

PathSynopsis
Package convert contains some routines for converting between cty types.
Package convert contains some routines for converting between cty types.
Package ctymarks contains some ancillary types, values, and constants for use with mark-related parts of the main cty package.
Package ctymarks contains some ancillary types, values, and constants for use with mark-related parts of the main cty package.
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 orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp