Modify parsing functions and config structs to accept hcl changes

Signed-off-by: Patrick Van Stee <patrick@vanstee.me>
This commit is contained in:
Patrick Van Stee
2020-04-15 21:00:18 -04:00
parent 87c4bf1df9
commit 4121ae50b5
131 changed files with 45185 additions and 110 deletions

View File

@ -0,0 +1,78 @@
package stdlib
import (
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var NotFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "val",
Type: cty.Bool,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
return args[0].Not(), nil
},
})
var AndFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Bool,
AllowDynamicType: true,
AllowMarked: true,
},
{
Name: "b",
Type: cty.Bool,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
return args[0].And(args[1]), nil
},
})
var OrFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Bool,
AllowDynamicType: true,
AllowMarked: true,
},
{
Name: "b",
Type: cty.Bool,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
return args[0].Or(args[1]), nil
},
})
// Not returns the logical complement of the given boolean value.
func Not(num cty.Value) (cty.Value, error) {
return NotFunc.Call([]cty.Value{num})
}
// And returns true if and only if both of the given boolean values are true.
func And(a, b cty.Value) (cty.Value, error) {
return AndFunc.Call([]cty.Value{a, b})
}
// Or returns true if either of the given boolean values are true.
func Or(a, b cty.Value) (cty.Value, error) {
return OrFunc.Call([]cty.Value{a, b})
}

View File

@ -0,0 +1,112 @@
package stdlib
import (
"fmt"
"reflect"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/gocty"
)
// Bytes is a capsule type that can be used with the binary functions to
// support applications that need to support raw buffers in addition to
// UTF-8 strings.
var Bytes = cty.Capsule("bytes", reflect.TypeOf([]byte(nil)))
// BytesVal creates a new Bytes value from the given buffer, which must be
// non-nil or this function will panic.
//
// Once a byte slice has been wrapped in a Bytes capsule, its underlying array
// must be considered immutable.
func BytesVal(buf []byte) cty.Value {
if buf == nil {
panic("can't make Bytes value from nil slice")
}
return cty.CapsuleVal(Bytes, &buf)
}
// BytesLen is a Function that returns the length of the buffer encapsulated
// in a Bytes value.
var BytesLenFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "buf",
Type: Bytes,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
bufPtr := args[0].EncapsulatedValue().(*[]byte)
return cty.NumberIntVal(int64(len(*bufPtr))), nil
},
})
// BytesSlice is a Function that returns a slice of the given Bytes value.
var BytesSliceFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "buf",
Type: Bytes,
AllowDynamicType: true,
},
{
Name: "offset",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "length",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(Bytes),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
bufPtr := args[0].EncapsulatedValue().(*[]byte)
var offset, length int
var err error
err = gocty.FromCtyValue(args[1], &offset)
if err != nil {
return cty.NilVal, err
}
err = gocty.FromCtyValue(args[2], &length)
if err != nil {
return cty.NilVal, err
}
if offset < 0 || length < 0 {
return cty.NilVal, fmt.Errorf("offset and length must be non-negative")
}
if offset > len(*bufPtr) {
return cty.NilVal, fmt.Errorf(
"offset %d is greater than total buffer length %d",
offset, len(*bufPtr),
)
}
end := offset + length
if end > len(*bufPtr) {
return cty.NilVal, fmt.Errorf(
"offset %d + length %d is greater than total buffer length %d",
offset, length, len(*bufPtr),
)
}
return BytesVal((*bufPtr)[offset:end]), nil
},
})
func BytesLen(buf cty.Value) (cty.Value, error) {
return BytesLenFunc.Call([]cty.Value{buf})
}
func BytesSlice(buf cty.Value, offset cty.Value, length cty.Value) (cty.Value, error) {
return BytesSliceFunc.Call([]cty.Value{buf, offset, length})
}

View File

@ -0,0 +1,140 @@
package stdlib
import (
"fmt"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/gocty"
)
var HasIndexFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "collection",
Type: cty.DynamicPseudoType,
AllowDynamicType: true,
},
{
Name: "key",
Type: cty.DynamicPseudoType,
AllowDynamicType: true,
},
},
Type: func(args []cty.Value) (ret cty.Type, err error) {
collTy := args[0].Type()
if !(collTy.IsTupleType() || collTy.IsListType() || collTy.IsMapType() || collTy == cty.DynamicPseudoType) {
return cty.NilType, fmt.Errorf("collection must be a list, a map or a tuple")
}
return cty.Bool, nil
},
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].HasIndex(args[1]), nil
},
})
var IndexFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "collection",
Type: cty.DynamicPseudoType,
},
{
Name: "key",
Type: cty.DynamicPseudoType,
AllowDynamicType: true,
},
},
Type: func(args []cty.Value) (ret cty.Type, err error) {
collTy := args[0].Type()
key := args[1]
keyTy := key.Type()
switch {
case collTy.IsTupleType():
if keyTy != cty.Number && keyTy != cty.DynamicPseudoType {
return cty.NilType, fmt.Errorf("key for tuple must be number")
}
if !key.IsKnown() {
return cty.DynamicPseudoType, nil
}
var idx int
err := gocty.FromCtyValue(key, &idx)
if err != nil {
return cty.NilType, fmt.Errorf("invalid key for tuple: %s", err)
}
etys := collTy.TupleElementTypes()
if idx >= len(etys) || idx < 0 {
return cty.NilType, fmt.Errorf("key must be between 0 and %d inclusive", len(etys))
}
return etys[idx], nil
case collTy.IsListType():
if keyTy != cty.Number && keyTy != cty.DynamicPseudoType {
return cty.NilType, fmt.Errorf("key for list must be number")
}
return collTy.ElementType(), nil
case collTy.IsMapType():
if keyTy != cty.String && keyTy != cty.DynamicPseudoType {
return cty.NilType, fmt.Errorf("key for map must be string")
}
return collTy.ElementType(), nil
default:
return cty.NilType, fmt.Errorf("collection must be a list, a map or a tuple")
}
},
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
has, err := HasIndex(args[0], args[1])
if err != nil {
return cty.NilVal, err
}
if has.False() { // safe because collection and key are guaranteed known here
return cty.NilVal, fmt.Errorf("invalid index")
}
return args[0].Index(args[1]), nil
},
})
var LengthFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "collection",
Type: cty.DynamicPseudoType,
AllowDynamicType: true,
},
},
Type: func(args []cty.Value) (ret cty.Type, err error) {
collTy := args[0].Type()
if !(collTy.IsTupleType() || collTy.IsListType() || collTy.IsMapType() || collTy.IsSetType() || collTy == cty.DynamicPseudoType) {
return cty.NilType, fmt.Errorf("collection must be a list, a map or a tuple")
}
return cty.Number, nil
},
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].Length(), nil
},
})
// HasIndex determines whether the given collection can be indexed with the
// given key.
func HasIndex(collection cty.Value, key cty.Value) (cty.Value, error) {
return HasIndexFunc.Call([]cty.Value{collection, key})
}
// Index returns an element from the given collection using the given key,
// or returns an error if there is no element for the given key.
func Index(collection cty.Value, key cty.Value) (cty.Value, error) {
return IndexFunc.Call([]cty.Value{collection, key})
}
// Length returns the number of elements in the given collection.
func Length(collection cty.Value) (cty.Value, error) {
return LengthFunc.Call([]cty.Value{collection})
}

View File

@ -0,0 +1,93 @@
package stdlib
import (
"encoding/csv"
"fmt"
"io"
"strings"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var CSVDecodeFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
str := args[0]
if !str.IsKnown() {
return cty.DynamicPseudoType, nil
}
r := strings.NewReader(str.AsString())
cr := csv.NewReader(r)
headers, err := cr.Read()
if err == io.EOF {
return cty.DynamicPseudoType, fmt.Errorf("missing header line")
}
if err != nil {
return cty.DynamicPseudoType, err
}
atys := make(map[string]cty.Type, len(headers))
for _, name := range headers {
if _, exists := atys[name]; exists {
return cty.DynamicPseudoType, fmt.Errorf("duplicate column name %q", name)
}
atys[name] = cty.String
}
return cty.List(cty.Object(atys)), nil
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
ety := retType.ElementType()
atys := ety.AttributeTypes()
str := args[0]
r := strings.NewReader(str.AsString())
cr := csv.NewReader(r)
cr.FieldsPerRecord = len(atys)
// Read the header row first, since that'll tell us which indices
// map to which attribute names.
headers, err := cr.Read()
if err != nil {
return cty.DynamicVal, err
}
var rows []cty.Value
for {
cols, err := cr.Read()
if err == io.EOF {
break
}
if err != nil {
return cty.DynamicVal, err
}
vals := make(map[string]cty.Value, len(cols))
for i, str := range cols {
name := headers[i]
vals[name] = cty.StringVal(str)
}
rows = append(rows, cty.ObjectVal(vals))
}
if len(rows) == 0 {
return cty.ListValEmpty(ety), nil
}
return cty.ListVal(rows), nil
},
})
// CSVDecode parses the given CSV (RFC 4180) string and, if it is valid,
// returns a list of objects representing the rows.
//
// The result is always a list of some object type. The first row of the
// input is used to determine the object attributes, and subsequent rows
// determine the values of those attributes.
func CSVDecode(str cty.Value) (cty.Value, error) {
return CSVDecodeFunc.Call([]cty.Value{str})
}

View File

@ -0,0 +1,385 @@
package stdlib
import (
"bufio"
"bytes"
"fmt"
"strings"
"time"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var FormatDateFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "format",
Type: cty.String,
},
{
Name: "time",
Type: cty.String,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
formatStr := args[0].AsString()
timeStr := args[1].AsString()
t, err := parseTimestamp(timeStr)
if err != nil {
return cty.DynamicVal, function.NewArgError(1, err)
}
var buf bytes.Buffer
sc := bufio.NewScanner(strings.NewReader(formatStr))
sc.Split(splitDateFormat)
const esc = '\''
for sc.Scan() {
tok := sc.Bytes()
// The leading byte signals the token type
switch {
case tok[0] == esc:
if tok[len(tok)-1] != esc || len(tok) == 1 {
return cty.DynamicVal, function.NewArgErrorf(0, "unterminated literal '")
}
if len(tok) == 2 {
// Must be a single escaped quote, ''
buf.WriteByte(esc)
} else {
// The content (until a closing esc) is printed out verbatim
// except that we must un-double any double-esc escapes in
// the middle of the string.
raw := tok[1 : len(tok)-1]
for i := 0; i < len(raw); i++ {
buf.WriteByte(raw[i])
if raw[i] == esc {
i++ // skip the escaped quote
}
}
}
case startsDateFormatVerb(tok[0]):
switch tok[0] {
case 'Y':
y := t.Year()
switch len(tok) {
case 2:
fmt.Fprintf(&buf, "%02d", y%100)
case 4:
fmt.Fprintf(&buf, "%04d", y)
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: year must either be \"YY\" or \"YYYY\"", tok)
}
case 'M':
m := t.Month()
switch len(tok) {
case 1:
fmt.Fprintf(&buf, "%d", m)
case 2:
fmt.Fprintf(&buf, "%02d", m)
case 3:
buf.WriteString(m.String()[:3])
case 4:
buf.WriteString(m.String())
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: month must be \"M\", \"MM\", \"MMM\", or \"MMMM\"", tok)
}
case 'D':
d := t.Day()
switch len(tok) {
case 1:
fmt.Fprintf(&buf, "%d", d)
case 2:
fmt.Fprintf(&buf, "%02d", d)
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: day of month must either be \"D\" or \"DD\"", tok)
}
case 'E':
d := t.Weekday()
switch len(tok) {
case 3:
buf.WriteString(d.String()[:3])
case 4:
buf.WriteString(d.String())
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: day of week must either be \"EEE\" or \"EEEE\"", tok)
}
case 'h':
h := t.Hour()
switch len(tok) {
case 1:
fmt.Fprintf(&buf, "%d", h)
case 2:
fmt.Fprintf(&buf, "%02d", h)
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: 24-hour must either be \"h\" or \"hh\"", tok)
}
case 'H':
h := t.Hour() % 12
if h == 0 {
h = 12
}
switch len(tok) {
case 1:
fmt.Fprintf(&buf, "%d", h)
case 2:
fmt.Fprintf(&buf, "%02d", h)
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: 12-hour must either be \"H\" or \"HH\"", tok)
}
case 'A', 'a':
if len(tok) != 2 {
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: must be \"%s%s\"", tok, tok[0:1], tok[0:1])
}
upper := tok[0] == 'A'
switch t.Hour() / 12 {
case 0:
if upper {
buf.WriteString("AM")
} else {
buf.WriteString("am")
}
case 1:
if upper {
buf.WriteString("PM")
} else {
buf.WriteString("pm")
}
}
case 'm':
m := t.Minute()
switch len(tok) {
case 1:
fmt.Fprintf(&buf, "%d", m)
case 2:
fmt.Fprintf(&buf, "%02d", m)
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: minute must either be \"m\" or \"mm\"", tok)
}
case 's':
s := t.Second()
switch len(tok) {
case 1:
fmt.Fprintf(&buf, "%d", s)
case 2:
fmt.Fprintf(&buf, "%02d", s)
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: second must either be \"s\" or \"ss\"", tok)
}
case 'Z':
// We'll just lean on Go's own formatter for this one, since
// the necessary information is unexported.
switch len(tok) {
case 1:
buf.WriteString(t.Format("Z07:00"))
case 3:
str := t.Format("-0700")
switch str {
case "+0000":
buf.WriteString("UTC")
default:
buf.WriteString(str)
}
case 4:
buf.WriteString(t.Format("-0700"))
case 5:
buf.WriteString(t.Format("-07:00"))
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q: timezone must be Z, ZZZZ, or ZZZZZ", tok)
}
default:
return cty.DynamicVal, function.NewArgErrorf(0, "invalid date format verb %q", tok)
}
default:
// Any other starting character indicates a literal sequence
buf.Write(tok)
}
}
return cty.StringVal(buf.String()), nil
},
})
// FormatDate reformats a timestamp given in RFC3339 syntax into another time
// syntax defined by a given format string.
//
// The format string uses letter mnemonics to represent portions of the
// timestamp, with repetition signifying length variants of each portion.
// Single quote characters ' can be used to quote sequences of literal letters
// that should not be interpreted as formatting mnemonics.
//
// The full set of supported mnemonic sequences is listed below:
//
// YY Year modulo 100 zero-padded to two digits, like "06".
// YYYY Four (or more) digit year, like "2006".
// M Month number, like "1" for January.
// MM Month number zero-padded to two digits, like "01".
// MMM English month name abbreviated to three letters, like "Jan".
// MMMM English month name unabbreviated, like "January".
// D Day of month number, like "2".
// DD Day of month number zero-padded to two digits, like "02".
// EEE English day of week name abbreviated to three letters, like "Mon".
// EEEE English day of week name unabbreviated, like "Monday".
// h 24-hour number, like "2".
// hh 24-hour number zero-padded to two digits, like "02".
// H 12-hour number, like "2".
// HH 12-hour number zero-padded to two digits, like "02".
// AA Hour AM/PM marker in uppercase, like "AM".
// aa Hour AM/PM marker in lowercase, like "am".
// m Minute within hour, like "5".
// mm Minute within hour zero-padded to two digits, like "05".
// s Second within minute, like "9".
// ss Second within minute zero-padded to two digits, like "09".
// ZZZZ Timezone offset with just sign and digit, like "-0800".
// ZZZZZ Timezone offset with colon separating hours and minutes, like "-08:00".
// Z Like ZZZZZ but with a special case "Z" for UTC.
// ZZZ Like ZZZZ but with a special case "UTC" for UTC.
//
// The format syntax is optimized mainly for generating machine-oriented
// timestamps rather than human-oriented timestamps; the English language
// portions of the output reflect the use of English names in a number of
// machine-readable date formatting standards. For presentation to humans,
// a locale-aware time formatter (not included in this package) is a better
// choice.
//
// The format syntax is not compatible with that of any other language, but
// is optimized so that patterns for common standard date formats can be
// recognized quickly even by a reader unfamiliar with the format syntax.
func FormatDate(format cty.Value, timestamp cty.Value) (cty.Value, error) {
return FormatDateFunc.Call([]cty.Value{format, timestamp})
}
func parseTimestamp(ts string) (time.Time, error) {
t, err := time.Parse(time.RFC3339, ts)
if err != nil {
switch err := err.(type) {
case *time.ParseError:
// If err is s time.ParseError then its string representation is not
// appropriate since it relies on details of Go's strange date format
// representation, which a caller of our functions is not expected
// to be familiar with.
//
// Therefore we do some light transformation to get a more suitable
// error that should make more sense to our callers. These are
// still not awesome error messages, but at least they refer to
// the timestamp portions by name rather than by Go's example
// values.
if err.LayoutElem == "" && err.ValueElem == "" && err.Message != "" {
// For some reason err.Message is populated with a ": " prefix
// by the time package.
return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp%s", err.Message)
}
var what string
switch err.LayoutElem {
case "2006":
what = "year"
case "01":
what = "month"
case "02":
what = "day of month"
case "15":
what = "hour"
case "04":
what = "minute"
case "05":
what = "second"
case "Z07:00":
what = "UTC offset"
case "T":
return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: missing required time introducer 'T'")
case ":", "-":
if err.ValueElem == "" {
return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: end of string where %q is expected", err.LayoutElem)
} else {
return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: found %q where %q is expected", err.ValueElem, err.LayoutElem)
}
default:
// Should never get here, because time.RFC3339 includes only the
// above portions, but since that might change in future we'll
// be robust here.
what = "timestamp segment"
}
if err.ValueElem == "" {
return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: end of string before %s", what)
} else {
return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: cannot use %q as %s", err.ValueElem, what)
}
}
return time.Time{}, err
}
return t, nil
}
// splitDataFormat is a bufio.SplitFunc used to tokenize a date format.
func splitDateFormat(data []byte, atEOF bool) (advance int, token []byte, err error) {
if len(data) == 0 {
return 0, nil, nil
}
const esc = '\''
switch {
case data[0] == esc:
// If we have another quote immediately after then this is a single
// escaped escape.
if len(data) > 1 && data[1] == esc {
return 2, data[:2], nil
}
// Beginning of quoted sequence, so we will seek forward until we find
// the closing quote, ignoring escaped quotes along the way.
for i := 1; i < len(data); i++ {
if data[i] == esc {
if (i + 1) == len(data) {
// We need at least one more byte to decide if this is an
// escape or a terminator.
return 0, nil, nil
}
if data[i+1] == esc {
i++ // doubled-up quotes are an escape sequence
continue
}
// We've found the closing quote
return i + 1, data[:i+1], nil
}
}
// If we fall out here then we need more bytes to find the end,
// unless we're already at the end with an unclosed quote.
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
case startsDateFormatVerb(data[0]):
rep := data[0]
for i := 1; i < len(data); i++ {
if data[i] != rep {
return i, data[:i], nil
}
}
if atEOF {
return len(data), data, nil
}
// We need more data to decide if we've found the end
return 0, nil, nil
default:
for i := 1; i < len(data); i++ {
if data[i] == esc || startsDateFormatVerb(data[i]) {
return i, data[:i], nil
}
}
// We might not actually be at the end of a literal sequence,
// but that doesn't matter since we'll concat them back together
// anyway.
return len(data), data, nil
}
}
func startsDateFormatVerb(b byte) bool {
return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
}

View File

@ -0,0 +1,13 @@
// 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.
//
// See the parent package "function" for more information on the purpose
// and usage of cty functions.
//
// This package contains both Go functions, which provide convenient access
// to call the functions from Go code, and the Function objects themselves.
// The latter follow the naming scheme of appending "Func" to the end of
// the function name.
package stdlib

View File

@ -0,0 +1,517 @@
package stdlib
import (
"bytes"
"fmt"
"math/big"
"strings"
"github.com/apparentlymart/go-textseg/textseg"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/json"
)
//go:generate ragel -Z format_fsm.rl
//go:generate gofmt -w format_fsm.go
var FormatFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "format",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "args",
Type: cty.DynamicPseudoType,
AllowNull: true,
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
for _, arg := range args[1:] {
if !arg.IsWhollyKnown() {
// We require all nested values to be known because the only
// thing we can do for a collection/structural type is print
// it as JSON and that requires it to be wholly known.
return cty.UnknownVal(cty.String), nil
}
}
str, err := formatFSM(args[0].AsString(), args[1:])
return cty.StringVal(str), err
},
})
var FormatListFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "format",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "args",
Type: cty.DynamicPseudoType,
AllowNull: true,
AllowUnknown: true,
},
Type: function.StaticReturnType(cty.List(cty.String)),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
fmtVal := args[0]
args = args[1:]
if len(args) == 0 {
// With no arguments, this function is equivalent to Format, but
// returning a single-element list result.
result, err := Format(fmtVal, args...)
return cty.ListVal([]cty.Value{result}), err
}
fmtStr := fmtVal.AsString()
// Each of our arguments will be dealt with either as an iterator
// or as a single value. Iterators are used for sequence-type values
// (lists, sets, tuples) while everything else is treated as a
// single value. The sequences we iterate over are required to be
// all the same length.
iterLen := -1
lenChooser := -1
iterators := make([]cty.ElementIterator, len(args))
singleVals := make([]cty.Value, len(args))
unknowns := make([]bool, len(args))
for i, arg := range args {
argTy := arg.Type()
switch {
case (argTy.IsListType() || argTy.IsSetType() || argTy.IsTupleType()) && !arg.IsNull():
if !argTy.IsTupleType() && !arg.IsKnown() {
// We can't iterate this one at all yet then, so we can't
// yet produce a result.
unknowns[i] = true
continue
}
thisLen := arg.LengthInt()
if iterLen == -1 {
iterLen = thisLen
lenChooser = i
} else {
if thisLen != iterLen {
return cty.NullVal(cty.List(cty.String)), function.NewArgErrorf(
i+1,
"argument %d has length %d, which is inconsistent with argument %d of length %d",
i+1, thisLen,
lenChooser+1, iterLen,
)
}
}
if !arg.IsKnown() {
// We allowed an unknown tuple value to fall through in
// our initial check above so that we'd be able to run
// the above error checks against it, but we still can't
// iterate it if the checks pass.
unknowns[i] = true
continue
}
iterators[i] = arg.ElementIterator()
default:
singleVals[i] = arg
}
}
for _, isUnk := range unknowns {
if isUnk {
return cty.UnknownVal(retType), nil
}
}
if iterLen == 0 {
// If our sequences are all empty then our result must be empty.
return cty.ListValEmpty(cty.String), nil
}
if iterLen == -1 {
// If we didn't encounter any iterables at all then we're going
// to just do one iteration with items from singleVals.
iterLen = 1
}
ret := make([]cty.Value, 0, iterLen)
fmtArgs := make([]cty.Value, len(iterators))
Results:
for iterIdx := 0; iterIdx < iterLen; iterIdx++ {
// Construct our arguments for a single format call
for i := range fmtArgs {
switch {
case iterators[i] != nil:
iterator := iterators[i]
iterator.Next()
_, val := iterator.Element()
fmtArgs[i] = val
default:
fmtArgs[i] = singleVals[i]
}
// If any of the arguments to this call would be unknown then
// this particular result is unknown, but we'll keep going
// to see if any other iterations can produce known values.
if !fmtArgs[i].IsWhollyKnown() {
// We require all nested values to be known because the only
// thing we can do for a collection/structural type is print
// it as JSON and that requires it to be wholly known.
ret = append(ret, cty.UnknownVal(cty.String))
continue Results
}
}
str, err := formatFSM(fmtStr, fmtArgs)
if err != nil {
return cty.NullVal(cty.List(cty.String)), fmt.Errorf(
"error on format iteration %d: %s", iterIdx, err,
)
}
ret = append(ret, cty.StringVal(str))
}
return cty.ListVal(ret), nil
},
})
// Format produces a string representation of zero or more values using a
// format string similar to the "printf" function in C.
//
// It supports the following "verbs":
//
// %% Literal percent sign, consuming no value
// %v A default formatting of the value based on type, as described below.
// %#v JSON serialization of the value
// %t Converts to boolean and then produces "true" or "false"
// %b Converts to number, requires integer, produces binary representation
// %d Converts to number, requires integer, produces decimal representation
// %o Converts to number, requires integer, produces octal representation
// %x Converts to number, requires integer, produces hexadecimal representation
// with lowercase letters
// %X Like %x but with uppercase letters
// %e Converts to number, produces scientific notation like -1.234456e+78
// %E Like %e but with an uppercase "E" representing the exponent
// %f Converts to number, produces decimal representation with fractional
// part but no exponent, like 123.456
// %g %e for large exponents or %f otherwise
// %G %E for large exponents or %f otherwise
// %s Converts to string and produces the string's characters
// %q Converts to string and produces JSON-quoted string representation,
// like %v.
//
// The default format selections made by %v are:
//
// string %s
// number %g
// bool %t
// other %#v
//
// Null values produce the literal keyword "null" for %v and %#v, and produce
// an error otherwise.
//
// Width is specified by an optional decimal number immediately preceding the
// verb letter. If absent, the width is whatever is necessary to represent the
// value. Precision is specified after the (optional) width by a period
// followed by a decimal number. If no period is present, a default precision
// is used. A period with no following number is invalid.
// For examples:
//
// %f default width, default precision
// %9f width 9, default precision
// %.2f default width, precision 2
// %9.2f width 9, precision 2
//
// Width and precision are measured in unicode characters (grapheme clusters).
//
// For most values, width is the minimum number of characters to output,
// padding the formatted form with spaces if necessary.
//
// For strings, precision limits the length of the input to be formatted (not
// the size of the output), truncating if necessary.
//
// For numbers, width sets the minimum width of the field and precision sets
// the number of places after the decimal, if appropriate, except that for
// %g/%G precision sets the total number of significant digits.
//
// The following additional symbols can be used immediately after the percent
// introducer as flags:
//
// (a space) leave a space where the sign would be if number is positive
// + Include a sign for a number even if it is positive (numeric only)
// - Pad with spaces on the left rather than the right
// 0 Pad with zeros rather than spaces.
//
// Flag characters are ignored for verbs that do not support them.
//
// By default, % sequences consume successive arguments starting with the first.
// Introducing a [n] sequence immediately before the verb letter, where n is a
// decimal integer, explicitly chooses a particular value argument by its
// one-based index. Subsequent calls without an explicit index will then
// proceed with n+1, n+2, etc.
//
// An error is produced if the format string calls for an impossible conversion
// or accesses more values than are given. An error is produced also for
// an unsupported format verb.
func Format(format cty.Value, vals ...cty.Value) (cty.Value, error) {
args := make([]cty.Value, 0, len(vals)+1)
args = append(args, format)
args = append(args, vals...)
return FormatFunc.Call(args)
}
// FormatList applies the same formatting behavior as Format, but accepts
// a mixture of list and non-list values as arguments. Any list arguments
// passed must have the same length, which dictates the length of the
// resulting list.
//
// Any non-list arguments are used repeatedly for each iteration over the
// list arguments. The list arguments are iterated in order by key, so
// corresponding items are formatted together.
func FormatList(format cty.Value, vals ...cty.Value) (cty.Value, error) {
args := make([]cty.Value, 0, len(vals)+1)
args = append(args, format)
args = append(args, vals...)
return FormatListFunc.Call(args)
}
type formatVerb struct {
Raw string
Offset int
ArgNum int
Mode rune
Zero bool
Sharp bool
Plus bool
Minus bool
Space bool
HasPrec bool
Prec int
HasWidth bool
Width int
}
// formatAppend is called by formatFSM (generated by format_fsm.rl) for each
// formatting sequence that is encountered.
func formatAppend(verb *formatVerb, buf *bytes.Buffer, args []cty.Value) error {
argIdx := verb.ArgNum - 1
if argIdx >= len(args) {
return fmt.Errorf(
"not enough arguments for %q at %d: need index %d but have %d total",
verb.Raw, verb.Offset,
verb.ArgNum, len(args),
)
}
arg := args[argIdx]
if verb.Mode != 'v' && arg.IsNull() {
return fmt.Errorf("unsupported value for %q at %d: null value cannot be formatted", verb.Raw, verb.Offset)
}
// Normalize to make some things easier for downstream formatters
if !verb.HasWidth {
verb.Width = -1
}
if !verb.HasPrec {
verb.Prec = -1
}
// For our first pass we'll ensure the verb is supported and then fan
// out to other functions based on what conversion is needed.
switch verb.Mode {
case 'v':
return formatAppendAsIs(verb, buf, arg)
case 't':
return formatAppendBool(verb, buf, arg)
case 'b', 'd', 'o', 'x', 'X', 'e', 'E', 'f', 'g', 'G':
return formatAppendNumber(verb, buf, arg)
case 's', 'q':
return formatAppendString(verb, buf, arg)
default:
return fmt.Errorf("unsupported format verb %q in %q at offset %d", verb.Mode, verb.Raw, verb.Offset)
}
}
func formatAppendAsIs(verb *formatVerb, buf *bytes.Buffer, arg cty.Value) error {
if !verb.Sharp && !arg.IsNull() {
// Unless the caller overrode it with the sharp flag, we'll try some
// specialized formats before we fall back on JSON.
switch arg.Type() {
case cty.String:
fmted := arg.AsString()
fmted = formatPadWidth(verb, fmted)
buf.WriteString(fmted)
return nil
case cty.Number:
bf := arg.AsBigFloat()
fmted := bf.Text('g', -1)
fmted = formatPadWidth(verb, fmted)
buf.WriteString(fmted)
return nil
}
}
jb, err := json.Marshal(arg, arg.Type())
if err != nil {
return fmt.Errorf("unsupported value for %q at %d: %s", verb.Raw, verb.Offset, err)
}
fmted := formatPadWidth(verb, string(jb))
buf.WriteString(fmted)
return nil
}
func formatAppendBool(verb *formatVerb, buf *bytes.Buffer, arg cty.Value) error {
var err error
arg, err = convert.Convert(arg, cty.Bool)
if err != nil {
return fmt.Errorf("unsupported value for %q at %d: %s", verb.Raw, verb.Offset, err)
}
if arg.True() {
buf.WriteString("true")
} else {
buf.WriteString("false")
}
return nil
}
func formatAppendNumber(verb *formatVerb, buf *bytes.Buffer, arg cty.Value) error {
var err error
arg, err = convert.Convert(arg, cty.Number)
if err != nil {
return fmt.Errorf("unsupported value for %q at %d: %s", verb.Raw, verb.Offset, err)
}
switch verb.Mode {
case 'b', 'd', 'o', 'x', 'X':
return formatAppendInteger(verb, buf, arg)
default:
bf := arg.AsBigFloat()
// For floats our format syntax is a subset of Go's, so it's
// safe for us to just lean on the existing Go implementation.
fmtstr := formatStripIndexSegment(verb.Raw)
fmted := fmt.Sprintf(fmtstr, bf)
buf.WriteString(fmted)
return nil
}
}
func formatAppendInteger(verb *formatVerb, buf *bytes.Buffer, arg cty.Value) error {
bf := arg.AsBigFloat()
bi, acc := bf.Int(nil)
if acc != big.Exact {
return fmt.Errorf("unsupported value for %q at %d: an integer is required", verb.Raw, verb.Offset)
}
// For integers our format syntax is a subset of Go's, so it's
// safe for us to just lean on the existing Go implementation.
fmtstr := formatStripIndexSegment(verb.Raw)
fmted := fmt.Sprintf(fmtstr, bi)
buf.WriteString(fmted)
return nil
}
func formatAppendString(verb *formatVerb, buf *bytes.Buffer, arg cty.Value) error {
var err error
arg, err = convert.Convert(arg, cty.String)
if err != nil {
return fmt.Errorf("unsupported value for %q at %d: %s", verb.Raw, verb.Offset, err)
}
// We _cannot_ directly use the Go fmt.Sprintf implementation for strings
// because it measures widths and precisions in runes rather than grapheme
// clusters.
str := arg.AsString()
if verb.Prec > 0 {
strB := []byte(str)
pos := 0
wanted := verb.Prec
for i := 0; i < wanted; i++ {
next := strB[pos:]
if len(next) == 0 {
// ran out of characters before we hit our max width
break
}
d, _, _ := textseg.ScanGraphemeClusters(strB[pos:], true)
pos += d
}
str = str[:pos]
}
switch verb.Mode {
case 's':
fmted := formatPadWidth(verb, str)
buf.WriteString(fmted)
case 'q':
jb, err := json.Marshal(cty.StringVal(str), cty.String)
if err != nil {
// Should never happen, since we know this is a known, non-null string
panic(fmt.Errorf("failed to marshal %#v as JSON: %s", arg, err))
}
fmted := formatPadWidth(verb, string(jb))
buf.WriteString(fmted)
default:
// Should never happen because formatAppend should've already validated
panic(fmt.Errorf("invalid string formatting mode %q", verb.Mode))
}
return nil
}
func formatPadWidth(verb *formatVerb, fmted string) string {
if verb.Width < 0 {
return fmted
}
// Safe to ignore errors because ScanGraphemeClusters cannot produce errors
givenLen, _ := textseg.TokenCount([]byte(fmted), textseg.ScanGraphemeClusters)
wantLen := verb.Width
if givenLen >= wantLen {
return fmted
}
padLen := wantLen - givenLen
padChar := " "
if verb.Zero {
padChar = "0"
}
pads := strings.Repeat(padChar, padLen)
if verb.Minus {
return fmted + pads
}
return pads + fmted
}
// formatStripIndexSegment strips out any [nnn] segment present in a verb
// string so that we can pass it through to Go's fmt.Sprintf with a single
// argument. This is used in cases where we're just leaning on Go's formatter
// because it's a superset of ours.
func formatStripIndexSegment(rawVerb string) string {
// We assume the string has already been validated here, since we should
// only be using this function with strings that were accepted by our
// scanner in formatFSM.
start := strings.Index(rawVerb, "[")
end := strings.Index(rawVerb, "]")
if start == -1 || end == -1 {
return rawVerb
}
return rawVerb[:start] + rawVerb[end+1:]
}

View File

@ -0,0 +1,374 @@
// line 1 "format_fsm.rl"
// This file is generated from format_fsm.rl. DO NOT EDIT.
// line 5 "format_fsm.rl"
package stdlib
import (
"bytes"
"fmt"
"unicode/utf8"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
// line 21 "format_fsm.go"
var _formatfsm_actions []byte = []byte{
0, 1, 0, 1, 1, 1, 2, 1, 4,
1, 5, 1, 6, 1, 7, 1, 8,
1, 9, 1, 10, 1, 11, 1, 14,
1, 16, 1, 17, 1, 18, 2, 3,
4, 2, 12, 10, 2, 12, 16, 2,
12, 18, 2, 13, 14, 2, 15, 10,
2, 15, 18,
}
var _formatfsm_key_offsets []byte = []byte{
0, 0, 14, 27, 34, 36, 39, 43,
51,
}
var _formatfsm_trans_keys []byte = []byte{
32, 35, 37, 43, 45, 46, 48, 91,
49, 57, 65, 90, 97, 122, 32, 35,
43, 45, 46, 48, 91, 49, 57, 65,
90, 97, 122, 91, 48, 57, 65, 90,
97, 122, 49, 57, 93, 48, 57, 65,
90, 97, 122, 46, 91, 48, 57, 65,
90, 97, 122, 37,
}
var _formatfsm_single_lengths []byte = []byte{
0, 8, 7, 1, 0, 1, 0, 2,
1,
}
var _formatfsm_range_lengths []byte = []byte{
0, 3, 3, 3, 1, 1, 2, 3,
0,
}
var _formatfsm_index_offsets []byte = []byte{
0, 0, 12, 23, 28, 30, 33, 36,
42,
}
var _formatfsm_indicies []byte = []byte{
1, 2, 3, 4, 5, 6, 7, 10,
8, 9, 9, 0, 1, 2, 4, 5,
6, 7, 10, 8, 9, 9, 0, 13,
11, 12, 12, 0, 14, 0, 15, 14,
0, 9, 9, 0, 16, 19, 17, 18,
18, 0, 20, 3,
}
var _formatfsm_trans_targs []byte = []byte{
0, 2, 2, 8, 2, 2, 3, 2,
7, 8, 4, 3, 8, 4, 5, 6,
3, 7, 8, 4, 1,
}
var _formatfsm_trans_actions []byte = []byte{
7, 17, 9, 3, 15, 13, 25, 11,
43, 29, 19, 27, 49, 46, 21, 0,
37, 23, 40, 34, 1,
}
var _formatfsm_eof_actions []byte = []byte{
0, 31, 31, 31, 31, 31, 31, 31,
5,
}
const formatfsm_start int = 8
const formatfsm_first_final int = 8
const formatfsm_error int = 0
const formatfsm_en_main int = 8
// line 20 "format_fsm.rl"
func formatFSM(format string, a []cty.Value) (string, error) {
var buf bytes.Buffer
data := format
nextArg := 1 // arg numbers are 1-based
var verb formatVerb
highestArgIdx := 0 // zero means "none", since arg numbers are 1-based
// line 159 "format_fsm.rl"
// Ragel state
p := 0 // "Pointer" into data
pe := len(data) // End-of-data "pointer"
cs := 0 // current state (will be initialized by ragel-generated code)
ts := 0
te := 0
eof := pe
// Keep Go compiler happy even if generated code doesn't use these
_ = ts
_ = te
_ = eof
// line 123 "format_fsm.go"
{
cs = formatfsm_start
}
// line 128 "format_fsm.go"
{
var _klen int
var _trans int
var _acts int
var _nacts uint
var _keys int
if p == pe {
goto _test_eof
}
if cs == 0 {
goto _out
}
_resume:
_keys = int(_formatfsm_key_offsets[cs])
_trans = int(_formatfsm_index_offsets[cs])
_klen = int(_formatfsm_single_lengths[cs])
if _klen > 0 {
_lower := int(_keys)
var _mid int
_upper := int(_keys + _klen - 1)
for {
if _upper < _lower {
break
}
_mid = _lower + ((_upper - _lower) >> 1)
switch {
case data[p] < _formatfsm_trans_keys[_mid]:
_upper = _mid - 1
case data[p] > _formatfsm_trans_keys[_mid]:
_lower = _mid + 1
default:
_trans += int(_mid - int(_keys))
goto _match
}
}
_keys += _klen
_trans += _klen
}
_klen = int(_formatfsm_range_lengths[cs])
if _klen > 0 {
_lower := int(_keys)
var _mid int
_upper := int(_keys + (_klen << 1) - 2)
for {
if _upper < _lower {
break
}
_mid = _lower + (((_upper - _lower) >> 1) & ^1)
switch {
case data[p] < _formatfsm_trans_keys[_mid]:
_upper = _mid - 2
case data[p] > _formatfsm_trans_keys[_mid+1]:
_lower = _mid + 2
default:
_trans += int((_mid - int(_keys)) >> 1)
goto _match
}
}
_trans += _klen
}
_match:
_trans = int(_formatfsm_indicies[_trans])
cs = int(_formatfsm_trans_targs[_trans])
if _formatfsm_trans_actions[_trans] == 0 {
goto _again
}
_acts = int(_formatfsm_trans_actions[_trans])
_nacts = uint(_formatfsm_actions[_acts])
_acts++
for ; _nacts > 0; _nacts-- {
_acts++
switch _formatfsm_actions[_acts-1] {
case 0:
// line 31 "format_fsm.rl"
verb = formatVerb{
ArgNum: nextArg,
Prec: -1,
Width: -1,
}
ts = p
case 1:
// line 40 "format_fsm.rl"
buf.WriteByte(data[p])
case 4:
// line 51 "format_fsm.rl"
// We'll try to slurp a whole UTF-8 sequence here, to give the user
// better feedback.
r, _ := utf8.DecodeRuneInString(data[p:])
return buf.String(), fmt.Errorf("unrecognized format character %q at offset %d", r, p)
case 5:
// line 58 "format_fsm.rl"
verb.Sharp = true
case 6:
// line 61 "format_fsm.rl"
verb.Zero = true
case 7:
// line 64 "format_fsm.rl"
verb.Minus = true
case 8:
// line 67 "format_fsm.rl"
verb.Plus = true
case 9:
// line 70 "format_fsm.rl"
verb.Space = true
case 10:
// line 74 "format_fsm.rl"
verb.ArgNum = 0
case 11:
// line 77 "format_fsm.rl"
verb.ArgNum = (10 * verb.ArgNum) + (int(data[p]) - '0')
case 12:
// line 81 "format_fsm.rl"
verb.HasWidth = true
case 13:
// line 84 "format_fsm.rl"
verb.Width = 0
case 14:
// line 87 "format_fsm.rl"
verb.Width = (10 * verb.Width) + (int(data[p]) - '0')
case 15:
// line 91 "format_fsm.rl"
verb.HasPrec = true
case 16:
// line 94 "format_fsm.rl"
verb.Prec = 0
case 17:
// line 97 "format_fsm.rl"
verb.Prec = (10 * verb.Prec) + (int(data[p]) - '0')
case 18:
// line 101 "format_fsm.rl"
verb.Mode = rune(data[p])
te = p + 1
verb.Raw = data[ts:te]
verb.Offset = ts
if verb.ArgNum > highestArgIdx {
highestArgIdx = verb.ArgNum
}
err := formatAppend(&verb, &buf, a)
if err != nil {
return buf.String(), err
}
nextArg = verb.ArgNum + 1
// line 330 "format_fsm.go"
}
}
_again:
if cs == 0 {
goto _out
}
p++
if p != pe {
goto _resume
}
_test_eof:
{
}
if p == eof {
__acts := _formatfsm_eof_actions[cs]
__nacts := uint(_formatfsm_actions[__acts])
__acts++
for ; __nacts > 0; __nacts-- {
__acts++
switch _formatfsm_actions[__acts-1] {
case 2:
// line 44 "format_fsm.rl"
case 3:
// line 47 "format_fsm.rl"
return buf.String(), fmt.Errorf("invalid format string starting at offset %d", p)
case 4:
// line 51 "format_fsm.rl"
// We'll try to slurp a whole UTF-8 sequence here, to give the user
// better feedback.
r, _ := utf8.DecodeRuneInString(data[p:])
return buf.String(), fmt.Errorf("unrecognized format character %q at offset %d", r, p)
// line 369 "format_fsm.go"
}
}
}
_out:
{
}
}
// line 177 "format_fsm.rl"
// If we fall out here without being in a final state then we've
// encountered something that the scanner can't match, which should
// be impossible (the scanner matches all bytes _somehow_) but we'll
// flag it anyway rather than just losing data from the end.
if cs < formatfsm_first_final {
return buf.String(), fmt.Errorf("extraneous characters beginning at offset %d", p)
}
if highestArgIdx < len(a) {
// Extraneous args are an error, to more easily detect mistakes
firstBad := highestArgIdx + 1
if highestArgIdx == 0 {
// Custom error message for this case
return buf.String(), function.NewArgErrorf(firstBad, "too many arguments; no verbs in format string")
}
return buf.String(), function.NewArgErrorf(firstBad, "too many arguments; only %d used by format string", highestArgIdx)
}
return buf.String(), nil
}

View File

@ -0,0 +1,198 @@
// This file is generated from format_fsm.rl. DO NOT EDIT.
%%{
# (except you are actually in scan_tokens.rl here, so edit away!)
machine formatfsm;
}%%
package stdlib
import (
"bytes"
"fmt"
"unicode/utf8"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
%%{
write data;
}%%
func formatFSM(format string, a []cty.Value) (string, error) {
var buf bytes.Buffer
data := format
nextArg := 1 // arg numbers are 1-based
var verb formatVerb
highestArgIdx := 0 // zero means "none", since arg numbers are 1-based
%%{
action begin {
verb = formatVerb{
ArgNum: nextArg,
Prec: -1,
Width: -1,
}
ts = p
}
action emit {
buf.WriteByte(fc);
}
action finish_ok {
}
action finish_err {
return buf.String(), fmt.Errorf("invalid format string starting at offset %d", p)
}
action err_char {
// We'll try to slurp a whole UTF-8 sequence here, to give the user
// better feedback.
r, _ := utf8.DecodeRuneInString(data[p:])
return buf.String(), fmt.Errorf("unrecognized format character %q at offset %d", r, p)
}
action flag_sharp {
verb.Sharp = true
}
action flag_zero {
verb.Zero = true
}
action flag_minus {
verb.Minus = true
}
action flag_plus {
verb.Plus = true
}
action flag_space {
verb.Space = true
}
action argidx_reset {
verb.ArgNum = 0
}
action argidx_num {
verb.ArgNum = (10 * verb.ArgNum) + (int(fc) - '0')
}
action has_width {
verb.HasWidth = true
}
action width_reset {
verb.Width = 0
}
action width_num {
verb.Width = (10 * verb.Width) + (int(fc) - '0')
}
action has_prec {
verb.HasPrec = true
}
action prec_reset {
verb.Prec = 0
}
action prec_num {
verb.Prec = (10 * verb.Prec) + (int(fc) - '0')
}
action mode {
verb.Mode = rune(fc)
te = p+1
verb.Raw = data[ts:te]
verb.Offset = ts
if verb.ArgNum > highestArgIdx {
highestArgIdx = verb.ArgNum
}
err := formatAppend(&verb, &buf, a)
if err != nil {
return buf.String(), err
}
nextArg = verb.ArgNum + 1
}
# a number that isn't zero and doesn't have a leading zero
num = [1-9] [0-9]*;
flags = (
'0' @flag_zero |
'#' @flag_sharp |
'-' @flag_minus |
'+' @flag_plus |
' ' @flag_space
)*;
argidx = ((
'[' (num $argidx_num) ']'
) >argidx_reset)?;
width = (
( num $width_num ) >width_reset %has_width
)?;
precision = (
('.' ( digit* $prec_num )) >prec_reset %has_prec
)?;
# We accept any letter here, but will be more picky in formatAppend
mode = ('a'..'z' | 'A'..'Z') @mode;
fmt_verb = (
'%' @begin
flags
width
precision
argidx
mode
);
main := (
[^%] @emit |
'%%' @emit |
fmt_verb
)* @/finish_err %/finish_ok $!err_char;
}%%
// Ragel state
p := 0 // "Pointer" into data
pe := len(data) // End-of-data "pointer"
cs := 0 // current state (will be initialized by ragel-generated code)
ts := 0
te := 0
eof := pe
// Keep Go compiler happy even if generated code doesn't use these
_ = ts
_ = te
_ = eof
%%{
write init;
write exec;
}%%
// If we fall out here without being in a final state then we've
// encountered something that the scanner can't match, which should
// be impossible (the scanner matches all bytes _somehow_) but we'll
// flag it anyway rather than just losing data from the end.
if cs < formatfsm_first_final {
return buf.String(), fmt.Errorf("extraneous characters beginning at offset %d", p)
}
if highestArgIdx < len(a) {
// Extraneous args are an error, to more easily detect mistakes
firstBad := highestArgIdx+1
if highestArgIdx == 0 {
// Custom error message for this case
return buf.String(), function.NewArgErrorf(firstBad, "too many arguments; no verbs in format string")
}
return buf.String(), function.NewArgErrorf(firstBad, "too many arguments; only %d used by format string", highestArgIdx)
}
return buf.String(), nil
}

View File

@ -0,0 +1,107 @@
package stdlib
import (
"fmt"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
)
var EqualFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.DynamicPseudoType,
AllowUnknown: true,
AllowDynamicType: true,
AllowNull: true,
},
{
Name: "b",
Type: cty.DynamicPseudoType,
AllowUnknown: true,
AllowDynamicType: true,
AllowNull: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].Equals(args[1]), nil
},
})
var NotEqualFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.DynamicPseudoType,
AllowUnknown: true,
AllowDynamicType: true,
AllowNull: true,
},
{
Name: "b",
Type: cty.DynamicPseudoType,
AllowUnknown: true,
AllowDynamicType: true,
AllowNull: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].Equals(args[1]).Not(), nil
},
})
var CoalesceFunc = function.New(&function.Spec{
Params: []function.Parameter{},
VarParam: &function.Parameter{
Name: "vals",
Type: cty.DynamicPseudoType,
AllowUnknown: true,
AllowDynamicType: true,
AllowNull: true,
},
Type: func(args []cty.Value) (ret cty.Type, err error) {
argTypes := make([]cty.Type, len(args))
for i, val := range args {
argTypes[i] = val.Type()
}
retType, _ := convert.UnifyUnsafe(argTypes)
if retType == cty.NilType {
return cty.NilType, fmt.Errorf("all arguments must have the same type")
}
return retType, nil
},
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
for _, argVal := range args {
if !argVal.IsKnown() {
return cty.UnknownVal(retType), nil
}
if argVal.IsNull() {
continue
}
return convert.Convert(argVal, retType)
}
return cty.NilVal, fmt.Errorf("no non-null arguments")
},
})
// Equal determines whether the two given values are equal, returning a
// bool value.
func Equal(a cty.Value, b cty.Value) (cty.Value, error) {
return EqualFunc.Call([]cty.Value{a, b})
}
// NotEqual is the opposite of Equal.
func NotEqual(a cty.Value, b cty.Value) (cty.Value, error) {
return NotEqualFunc.Call([]cty.Value{a, b})
}
// Coalesce returns the first of the given arguments that is not null. If
// all arguments are null, an error is produced.
func Coalesce(vals ...cty.Value) (cty.Value, error) {
return CoalesceFunc.Call(vals)
}

View File

@ -0,0 +1,72 @@
package stdlib
import (
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/json"
)
var JSONEncodeFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "val",
Type: cty.DynamicPseudoType,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
val := args[0]
if !val.IsWhollyKnown() {
// We can't serialize unknowns, so if the value is unknown or
// contains any _nested_ unknowns then our result must be
// unknown.
return cty.UnknownVal(retType), nil
}
buf, err := json.Marshal(val, val.Type())
if err != nil {
return cty.NilVal, err
}
return cty.StringVal(string(buf)), nil
},
})
var JSONDecodeFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
str := args[0]
if !str.IsKnown() {
return cty.DynamicPseudoType, nil
}
buf := []byte(str.AsString())
return json.ImpliedType(buf)
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
buf := []byte(args[0].AsString())
return json.Unmarshal(buf, retType)
},
})
// JSONEncode returns a JSON serialization of the given value.
func JSONEncode(val cty.Value) (cty.Value, error) {
return JSONEncodeFunc.Call([]cty.Value{val})
}
// JSONDecode parses the given JSON string and, if it is valid, returns the
// value it represents.
//
// Note that applying JSONDecode to the result of JSONEncode may not produce
// an identically-typed result, since JSON encoding is lossy for cty Types.
// The resulting value will consist only of primitive types, object types, and
// tuple types.
func JSONDecode(str cty.Value) (cty.Value, error) {
return JSONDecodeFunc.Call([]cty.Value{str})
}

View File

@ -0,0 +1,438 @@
package stdlib
import (
"fmt"
"math/big"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var AbsoluteFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "num",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
return args[0].Absolute(), nil
},
})
var AddFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
// big.Float.Add can panic if the input values are opposing infinities,
// so we must catch that here in order to remain within
// the cty Function abstraction.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(big.ErrNaN); ok {
ret = cty.NilVal
err = fmt.Errorf("can't compute sum of opposing infinities")
} else {
// not a panic we recognize
panic(r)
}
}
}()
return args[0].Add(args[1]), nil
},
})
var SubtractFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
// big.Float.Sub can panic if the input values are infinities,
// so we must catch that here in order to remain within
// the cty Function abstraction.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(big.ErrNaN); ok {
ret = cty.NilVal
err = fmt.Errorf("can't subtract infinity from itself")
} else {
// not a panic we recognize
panic(r)
}
}
}()
return args[0].Subtract(args[1]), nil
},
})
var MultiplyFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
// big.Float.Mul can panic if the input values are both zero or both
// infinity, so we must catch that here in order to remain within
// the cty Function abstraction.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(big.ErrNaN); ok {
ret = cty.NilVal
err = fmt.Errorf("can't multiply zero by infinity")
} else {
// not a panic we recognize
panic(r)
}
}
}()
return args[0].Multiply(args[1]), nil
},
})
var DivideFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
// big.Float.Quo can panic if the input values are both zero or both
// infinity, so we must catch that here in order to remain within
// the cty Function abstraction.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(big.ErrNaN); ok {
ret = cty.NilVal
err = fmt.Errorf("can't divide zero by zero or infinity by infinity")
} else {
// not a panic we recognize
panic(r)
}
}
}()
return args[0].Divide(args[1]), nil
},
})
var ModuloFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
// big.Float.Mul can panic if the input values are both zero or both
// infinity, so we must catch that here in order to remain within
// the cty Function abstraction.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(big.ErrNaN); ok {
ret = cty.NilVal
err = fmt.Errorf("can't use modulo with zero and infinity")
} else {
// not a panic we recognize
panic(r)
}
}
}()
return args[0].Modulo(args[1]), nil
},
})
var GreaterThanFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].GreaterThan(args[1]), nil
},
})
var GreaterThanOrEqualToFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].GreaterThanOrEqualTo(args[1]), nil
},
})
var LessThanFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].LessThan(args[1]), nil
},
})
var LessThanOrEqualToFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
{
Name: "b",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].LessThanOrEqualTo(args[1]), nil
},
})
var NegateFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "num",
Type: cty.Number,
AllowDynamicType: true,
AllowMarked: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
return args[0].Negate(), nil
},
})
var MinFunc = function.New(&function.Spec{
Params: []function.Parameter{},
VarParam: &function.Parameter{
Name: "numbers",
Type: cty.Number,
AllowDynamicType: true,
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
if len(args) == 0 {
return cty.NilVal, fmt.Errorf("must pass at least one number")
}
min := cty.PositiveInfinity
for _, num := range args {
if num.LessThan(min).True() {
min = num
}
}
return min, nil
},
})
var MaxFunc = function.New(&function.Spec{
Params: []function.Parameter{},
VarParam: &function.Parameter{
Name: "numbers",
Type: cty.Number,
AllowDynamicType: true,
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
if len(args) == 0 {
return cty.NilVal, fmt.Errorf("must pass at least one number")
}
max := cty.NegativeInfinity
for _, num := range args {
if num.GreaterThan(max).True() {
max = num
}
}
return max, nil
},
})
var IntFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "num",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
bf := args[0].AsBigFloat()
if bf.IsInt() {
return args[0], nil
}
bi, _ := bf.Int(nil)
bf = (&big.Float{}).SetInt(bi)
return cty.NumberVal(bf), nil
},
})
// Absolute returns the magnitude of the given number, without its sign.
// That is, it turns negative values into positive values.
func Absolute(num cty.Value) (cty.Value, error) {
return AbsoluteFunc.Call([]cty.Value{num})
}
// Add returns the sum of the two given numbers.
func Add(a cty.Value, b cty.Value) (cty.Value, error) {
return AddFunc.Call([]cty.Value{a, b})
}
// Subtract returns the difference between the two given numbers.
func Subtract(a cty.Value, b cty.Value) (cty.Value, error) {
return SubtractFunc.Call([]cty.Value{a, b})
}
// Multiply returns the product of the two given numbers.
func Multiply(a cty.Value, b cty.Value) (cty.Value, error) {
return MultiplyFunc.Call([]cty.Value{a, b})
}
// Divide returns a divided by b, where both a and b are numbers.
func Divide(a cty.Value, b cty.Value) (cty.Value, error) {
return DivideFunc.Call([]cty.Value{a, b})
}
// Negate returns the given number multipled by -1.
func Negate(num cty.Value) (cty.Value, error) {
return NegateFunc.Call([]cty.Value{num})
}
// LessThan returns true if a is less than b.
func LessThan(a cty.Value, b cty.Value) (cty.Value, error) {
return LessThanFunc.Call([]cty.Value{a, b})
}
// LessThanOrEqualTo returns true if a is less than b.
func LessThanOrEqualTo(a cty.Value, b cty.Value) (cty.Value, error) {
return LessThanOrEqualToFunc.Call([]cty.Value{a, b})
}
// GreaterThan returns true if a is less than b.
func GreaterThan(a cty.Value, b cty.Value) (cty.Value, error) {
return GreaterThanFunc.Call([]cty.Value{a, b})
}
// GreaterThanOrEqualTo returns true if a is less than b.
func GreaterThanOrEqualTo(a cty.Value, b cty.Value) (cty.Value, error) {
return GreaterThanOrEqualToFunc.Call([]cty.Value{a, b})
}
// Modulo returns the remainder of a divided by b under integer division,
// where both a and b are numbers.
func Modulo(a cty.Value, b cty.Value) (cty.Value, error) {
return ModuloFunc.Call([]cty.Value{a, b})
}
// Min returns the minimum number from the given numbers.
func Min(numbers ...cty.Value) (cty.Value, error) {
return MinFunc.Call(numbers)
}
// Max returns the maximum number from the given numbers.
func Max(numbers ...cty.Value) (cty.Value, error) {
return MaxFunc.Call(numbers)
}
// Int removes the fractional component of the given number returning an
// integer representing the whole number component, rounding towards zero.
// For example, -1.5 becomes -1.
//
// If an infinity is passed to Int, an error is returned.
func Int(num cty.Value) (cty.Value, error) {
if num == cty.PositiveInfinity || num == cty.NegativeInfinity {
return cty.NilVal, fmt.Errorf("can't truncate infinity to an integer")
}
return IntFunc.Call([]cty.Value{num})
}

View File

@ -0,0 +1,233 @@
package stdlib
import (
"fmt"
"regexp"
resyntax "regexp/syntax"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var RegexFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "pattern",
Type: cty.String,
},
{
Name: "string",
Type: cty.String,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
if !args[0].IsKnown() {
// We can't predict our type without seeing our pattern
return cty.DynamicPseudoType, nil
}
retTy, err := regexPatternResultType(args[0].AsString())
if err != nil {
err = function.NewArgError(0, err)
}
return retTy, err
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
if retType == cty.DynamicPseudoType {
return cty.DynamicVal, nil
}
re, err := regexp.Compile(args[0].AsString())
if err != nil {
// Should never happen, since we checked this in the Type function above.
return cty.NilVal, function.NewArgErrorf(0, "error parsing pattern: %s", err)
}
str := args[1].AsString()
captureIdxs := re.FindStringSubmatchIndex(str)
if captureIdxs == nil {
return cty.NilVal, fmt.Errorf("pattern did not match any part of the given string")
}
return regexPatternResult(re, str, captureIdxs, retType), nil
},
})
var RegexAllFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "pattern",
Type: cty.String,
},
{
Name: "string",
Type: cty.String,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
if !args[0].IsKnown() {
// We can't predict our type without seeing our pattern,
// but we do know it'll always be a list of something.
return cty.List(cty.DynamicPseudoType), nil
}
retTy, err := regexPatternResultType(args[0].AsString())
if err != nil {
err = function.NewArgError(0, err)
}
return cty.List(retTy), err
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
ety := retType.ElementType()
if ety == cty.DynamicPseudoType {
return cty.DynamicVal, nil
}
re, err := regexp.Compile(args[0].AsString())
if err != nil {
// Should never happen, since we checked this in the Type function above.
return cty.NilVal, function.NewArgErrorf(0, "error parsing pattern: %s", err)
}
str := args[1].AsString()
captureIdxsEach := re.FindAllStringSubmatchIndex(str, -1)
if len(captureIdxsEach) == 0 {
return cty.ListValEmpty(ety), nil
}
elems := make([]cty.Value, len(captureIdxsEach))
for i, captureIdxs := range captureIdxsEach {
elems[i] = regexPatternResult(re, str, captureIdxs, ety)
}
return cty.ListVal(elems), nil
},
})
// Regex is a function that extracts one or more substrings from a given
// string by applying a regular expression pattern, describing the first
// match.
//
// The return type depends on the composition of the capture groups (if any)
// in the pattern:
//
// - If there are no capture groups at all, the result is a single string
// representing the entire matched pattern.
// - If all of the capture groups are named, the result is an object whose
// keys are the named groups and whose values are their sub-matches, or
// null if a particular sub-group was inside another group that didn't
// match.
// - If none of the capture groups are named, the result is a tuple whose
// elements are the sub-groups in order and whose values are their
// sub-matches, or null if a particular sub-group was inside another group
// that didn't match.
// - It is invalid to use both named and un-named capture groups together in
// the same pattern.
//
// If the pattern doesn't match, this function returns an error. To test for
// a match, call RegexAll and check if the length of the result is greater
// than zero.
func Regex(pattern, str cty.Value) (cty.Value, error) {
return RegexFunc.Call([]cty.Value{pattern, str})
}
// RegexAll is similar to Regex but it finds all of the non-overlapping matches
// in the given string and returns a list of them.
//
// The result type is always a list, whose element type is deduced from the
// pattern in the same way as the return type for Regex is decided.
//
// If the pattern doesn't match at all, this function returns an empty list.
func RegexAll(pattern, str cty.Value) (cty.Value, error) {
return RegexAllFunc.Call([]cty.Value{pattern, str})
}
// regexPatternResultType parses the given regular expression pattern and
// returns the structural type that would be returned to represent its
// capture groups.
//
// Returns an error if parsing fails or if the pattern uses a mixture of
// named and unnamed capture groups, which is not permitted.
func regexPatternResultType(pattern string) (cty.Type, error) {
re, rawErr := regexp.Compile(pattern)
switch err := rawErr.(type) {
case *resyntax.Error:
return cty.NilType, fmt.Errorf("invalid regexp pattern: %s in %s", err.Code, err.Expr)
case error:
// Should never happen, since all regexp compile errors should
// be resyntax.Error, but just in case...
return cty.NilType, fmt.Errorf("error parsing pattern: %s", err)
}
allNames := re.SubexpNames()[1:]
var names []string
unnamed := 0
for _, name := range allNames {
if name == "" {
unnamed++
} else {
if names == nil {
names = make([]string, 0, len(allNames))
}
names = append(names, name)
}
}
switch {
case unnamed == 0 && len(names) == 0:
// If there are no capture groups at all then we'll return just a
// single string for the whole match.
return cty.String, nil
case unnamed > 0 && len(names) > 0:
return cty.NilType, fmt.Errorf("invalid regexp pattern: cannot mix both named and unnamed capture groups")
case unnamed > 0:
// For unnamed captures, we return a tuple of them all in order.
etys := make([]cty.Type, unnamed)
for i := range etys {
etys[i] = cty.String
}
return cty.Tuple(etys), nil
default:
// For named captures, we return an object using the capture names
// as keys.
atys := make(map[string]cty.Type, len(names))
for _, name := range names {
atys[name] = cty.String
}
return cty.Object(atys), nil
}
}
func regexPatternResult(re *regexp.Regexp, str string, captureIdxs []int, retType cty.Type) cty.Value {
switch {
case retType == cty.String:
start, end := captureIdxs[0], captureIdxs[1]
return cty.StringVal(str[start:end])
case retType.IsTupleType():
captureIdxs = captureIdxs[2:] // index 0 is the whole pattern span, which we ignore by skipping one pair
vals := make([]cty.Value, len(captureIdxs)/2)
for i := range vals {
start, end := captureIdxs[i*2], captureIdxs[i*2+1]
if start < 0 || end < 0 {
vals[i] = cty.NullVal(cty.String) // Did not match anything because containing group didn't match
continue
}
vals[i] = cty.StringVal(str[start:end])
}
return cty.TupleVal(vals)
case retType.IsObjectType():
captureIdxs = captureIdxs[2:] // index 0 is the whole pattern span, which we ignore by skipping one pair
vals := make(map[string]cty.Value, len(captureIdxs)/2)
names := re.SubexpNames()[1:]
for i, name := range names {
start, end := captureIdxs[i*2], captureIdxs[i*2+1]
if start < 0 || end < 0 {
vals[name] = cty.NullVal(cty.String) // Did not match anything because containing group didn't match
continue
}
vals[name] = cty.StringVal(str[start:end])
}
return cty.ObjectVal(vals)
default:
// Should never happen
panic(fmt.Sprintf("invalid return type %#v", retType))
}
}

View File

@ -0,0 +1,218 @@
package stdlib
import (
"fmt"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
)
var ConcatFunc = function.New(&function.Spec{
Params: []function.Parameter{},
VarParam: &function.Parameter{
Name: "seqs",
Type: cty.DynamicPseudoType,
},
Type: func(args []cty.Value) (ret cty.Type, err error) {
if len(args) == 0 {
return cty.NilType, fmt.Errorf("at least one argument is required")
}
if args[0].Type().IsListType() {
// Possibly we're going to return a list, if all of our other
// args are also lists and we can find a common element type.
tys := make([]cty.Type, len(args))
for i, val := range args {
ty := val.Type()
if !ty.IsListType() {
tys = nil
break
}
tys[i] = ty
}
if tys != nil {
commonType, _ := convert.UnifyUnsafe(tys)
if commonType != cty.NilType {
return commonType, nil
}
}
}
etys := make([]cty.Type, 0, len(args))
for i, val := range args {
ety := val.Type()
switch {
case ety.IsTupleType():
etys = append(etys, ety.TupleElementTypes()...)
case ety.IsListType():
if !val.IsKnown() {
// We need to know the list to count its elements to
// build our tuple type, so any concat of an unknown
// list can't be typed yet.
return cty.DynamicPseudoType, nil
}
l := val.LengthInt()
subEty := ety.ElementType()
for j := 0; j < l; j++ {
etys = append(etys, subEty)
}
default:
return cty.NilType, function.NewArgErrorf(
i, "all arguments must be lists or tuples; got %s",
ety.FriendlyName(),
)
}
}
return cty.Tuple(etys), nil
},
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
switch {
case retType.IsListType():
// If retType is a list type then we know that all of the
// given values will be lists and that they will either be of
// retType or of something we can convert to retType.
vals := make([]cty.Value, 0, len(args))
for i, list := range args {
list, err = convert.Convert(list, retType)
if err != nil {
// Conversion might fail because we used UnifyUnsafe
// to choose our return type.
return cty.NilVal, function.NewArgError(i, err)
}
it := list.ElementIterator()
for it.Next() {
_, v := it.Element()
vals = append(vals, v)
}
}
if len(vals) == 0 {
return cty.ListValEmpty(retType.ElementType()), nil
}
return cty.ListVal(vals), nil
case retType.IsTupleType():
// If retType is a tuple type then we could have a mixture of
// lists and tuples but we know they all have known values
// (because our params don't AllowUnknown) and we know that
// concatenating them all together will produce a tuple of
// retType because of the work we did in the Type function above.
vals := make([]cty.Value, 0, len(args))
for _, seq := range args {
// Both lists and tuples support ElementIterator, so this is easy.
it := seq.ElementIterator()
for it.Next() {
_, v := it.Element()
vals = append(vals, v)
}
}
return cty.TupleVal(vals), nil
default:
// should never happen if Type is working correctly above
panic("unsupported return type")
}
},
})
var RangeFunc = function.New(&function.Spec{
VarParam: &function.Parameter{
Name: "params",
Type: cty.Number,
},
Type: function.StaticReturnType(cty.List(cty.Number)),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
var start, end, step cty.Value
switch len(args) {
case 1:
if args[0].LessThan(cty.Zero).True() {
start, end, step = cty.Zero, args[0], cty.NumberIntVal(-1)
} else {
start, end, step = cty.Zero, args[0], cty.NumberIntVal(1)
}
case 2:
if args[1].LessThan(args[0]).True() {
start, end, step = args[0], args[1], cty.NumberIntVal(-1)
} else {
start, end, step = args[0], args[1], cty.NumberIntVal(1)
}
case 3:
start, end, step = args[0], args[1], args[2]
default:
return cty.NilVal, fmt.Errorf("must have one, two, or three arguments")
}
var vals []cty.Value
if step == cty.Zero {
return cty.NilVal, function.NewArgErrorf(2, "step must not be zero")
}
down := step.LessThan(cty.Zero).True()
if down {
if end.GreaterThan(start).True() {
return cty.NilVal, function.NewArgErrorf(1, "end must be less than start when step is negative")
}
} else {
if end.LessThan(start).True() {
return cty.NilVal, function.NewArgErrorf(1, "end must be greater than start when step is positive")
}
}
num := start
for {
if down {
if num.LessThanOrEqualTo(end).True() {
break
}
} else {
if num.GreaterThanOrEqualTo(end).True() {
break
}
}
if len(vals) >= 1024 {
// Artificial limit to prevent bad arguments from consuming huge amounts of memory
return cty.NilVal, fmt.Errorf("more than 1024 values were generated; either decrease the difference between start and end or use a smaller step")
}
vals = append(vals, num)
num = num.Add(step)
}
if len(vals) == 0 {
return cty.ListValEmpty(cty.Number), nil
}
return cty.ListVal(vals), nil
},
})
// Concat takes one or more sequences (lists or tuples) and returns the single
// sequence that results from concatenating them together in order.
//
// If all of the given sequences are lists of the same element type then the
// result is a list of that type. Otherwise, the result is a of a tuple type
// constructed from the given sequence types.
func Concat(seqs ...cty.Value) (cty.Value, error) {
return ConcatFunc.Call(seqs)
}
// Range creates a list of numbers by starting from the given starting value,
// then adding the given step value until the result is greater than or
// equal to the given stopping value. Each intermediate result becomes an
// element in the resulting list.
//
// When all three parameters are set, the order is (start, end, step). If
// only two parameters are set, they are the start and end respectively and
// step defaults to 1. If only one argument is set, it gives the end value
// with start defaulting to 0 and step defaulting to 1.
//
// Because the resulting list must be fully buffered in memory, there is an
// artificial cap of 1024 elements, after which this function will return
// an error to avoid consuming unbounded amounts of memory. The Range function
// is primarily intended for creating small lists of indices to iterate over,
// so there should be no reason to generate huge lists with it.
func Range(params ...cty.Value) (cty.Value, error) {
return RangeFunc.Call(params)
}

View File

@ -0,0 +1,195 @@
package stdlib
import (
"fmt"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var SetHasElementFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "set",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
{
Name: "elem",
Type: cty.DynamicPseudoType,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Bool),
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
return args[0].HasElement(args[1]), nil
},
})
var SetUnionFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "first_set",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
},
VarParam: &function.Parameter{
Name: "other_sets",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
Type: setOperationReturnType,
Impl: setOperationImpl(func(s1, s2 cty.ValueSet) cty.ValueSet {
return s1.Union(s2)
}),
})
var SetIntersectionFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "first_set",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
},
VarParam: &function.Parameter{
Name: "other_sets",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
Type: setOperationReturnType,
Impl: setOperationImpl(func(s1, s2 cty.ValueSet) cty.ValueSet {
return s1.Intersection(s2)
}),
})
var SetSubtractFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "a",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
{
Name: "b",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
},
Type: setOperationReturnType,
Impl: setOperationImpl(func(s1, s2 cty.ValueSet) cty.ValueSet {
return s1.Subtract(s2)
}),
})
var SetSymmetricDifferenceFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "first_set",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
},
VarParam: &function.Parameter{
Name: "other_sets",
Type: cty.Set(cty.DynamicPseudoType),
AllowDynamicType: true,
},
Type: setOperationReturnType,
Impl: setOperationImpl(func(s1, s2 cty.ValueSet) cty.ValueSet {
return s1.Subtract(s2)
}),
})
// SetHasElement determines whether the given set contains the given value as an
// element.
func SetHasElement(set cty.Value, elem cty.Value) (cty.Value, error) {
return SetHasElementFunc.Call([]cty.Value{set, elem})
}
// SetUnion returns a new set containing all of the elements from the given
// sets, which must have element types that can all be converted to some
// common type using the standard type unification rules. If conversion
// is not possible, an error is returned.
//
// The union operation is performed after type conversion, which may result
// in some previously-distinct values being conflated.
//
// At least one set must be provided.
func SetUnion(sets ...cty.Value) (cty.Value, error) {
return SetUnionFunc.Call(sets)
}
// Intersection returns a new set containing the elements that exist
// in all of the given sets, which must have element types that can all be
// converted to some common type using the standard type unification rules.
// If conversion is not possible, an error is returned.
//
// The intersection operation is performed after type conversion, which may
// result in some previously-distinct values being conflated.
//
// At least one set must be provided.
func SetIntersection(sets ...cty.Value) (cty.Value, error) {
return SetIntersectionFunc.Call(sets)
}
// SetSubtract returns a new set containing the elements from the
// first set that are not present in the second set. The sets must have
// element types that can both be converted to some common type using the
// standard type unification rules. If conversion is not possible, an error
// is returned.
//
// The subtract operation is performed after type conversion, which may
// result in some previously-distinct values being conflated.
func SetSubtract(a, b cty.Value) (cty.Value, error) {
return SetSubtractFunc.Call([]cty.Value{a, b})
}
// SetSymmetricDifference returns a new set containing elements that appear
// in any of the given sets but not multiple. The sets must have
// element types that can all be converted to some common type using the
// standard type unification rules. If conversion is not possible, an error
// is returned.
//
// The difference operation is performed after type conversion, which may
// result in some previously-distinct values being conflated.
func SetSymmetricDifference(sets ...cty.Value) (cty.Value, error) {
return SetSymmetricDifferenceFunc.Call(sets)
}
func setOperationReturnType(args []cty.Value) (ret cty.Type, err error) {
var etys []cty.Type
for _, arg := range args {
etys = append(etys, arg.Type().ElementType())
}
newEty, _ := convert.UnifyUnsafe(etys)
if newEty == cty.NilType {
return cty.NilType, fmt.Errorf("given sets must all have compatible element types")
}
return cty.Set(newEty), nil
}
func setOperationImpl(f func(s1, s2 cty.ValueSet) cty.ValueSet) function.ImplFunc {
return func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
first := args[0]
first, err = convert.Convert(first, retType)
if err != nil {
return cty.NilVal, function.NewArgError(0, err)
}
set := first.AsValueSet()
for i, arg := range args[1:] {
arg, err := convert.Convert(arg, retType)
if err != nil {
return cty.NilVal, function.NewArgError(i+1, err)
}
argSet := arg.AsValueSet()
set = f(set, argSet)
}
return cty.SetValFromValueSet(set), nil
}
}

View File

@ -0,0 +1,234 @@
package stdlib
import (
"strings"
"github.com/apparentlymart/go-textseg/textseg"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/gocty"
)
var UpperFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
in := args[0].AsString()
out := strings.ToUpper(in)
return cty.StringVal(out), nil
},
})
var LowerFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
in := args[0].AsString()
out := strings.ToLower(in)
return cty.StringVal(out), nil
},
})
var ReverseFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
in := []byte(args[0].AsString())
out := make([]byte, len(in))
pos := len(out)
inB := []byte(in)
for i := 0; i < len(in); {
d, _, _ := textseg.ScanGraphemeClusters(inB[i:], true)
cluster := in[i : i+d]
pos -= len(cluster)
copy(out[pos:], cluster)
i += d
}
return cty.StringVal(string(out)), nil
},
})
var StrlenFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.Number),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
in := args[0].AsString()
l := 0
inB := []byte(in)
for i := 0; i < len(in); {
d, _, _ := textseg.ScanGraphemeClusters(inB[i:], true)
l++
i += d
}
return cty.NumberIntVal(int64(l)), nil
},
})
var SubstrFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "str",
Type: cty.String,
AllowDynamicType: true,
},
{
Name: "offset",
Type: cty.Number,
AllowDynamicType: true,
},
{
Name: "length",
Type: cty.Number,
AllowDynamicType: true,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
in := []byte(args[0].AsString())
var offset, length int
var err error
err = gocty.FromCtyValue(args[1], &offset)
if err != nil {
return cty.NilVal, err
}
err = gocty.FromCtyValue(args[2], &length)
if err != nil {
return cty.NilVal, err
}
if offset < 0 {
totalLenNum, err := Strlen(args[0])
if err != nil {
// should never happen
panic("Stdlen returned an error")
}
var totalLen int
err = gocty.FromCtyValue(totalLenNum, &totalLen)
if err != nil {
// should never happen
panic("Stdlen returned a non-int number")
}
offset += totalLen
}
sub := in
pos := 0
var i int
// First we'll seek forward to our offset
if offset > 0 {
for i = 0; i < len(sub); {
d, _, _ := textseg.ScanGraphemeClusters(sub[i:], true)
i += d
pos++
if pos == offset {
break
}
if i >= len(in) {
return cty.StringVal(""), nil
}
}
sub = sub[i:]
}
if length < 0 {
// Taking the remainder of the string is a fast path since
// we can just return the rest of the buffer verbatim.
return cty.StringVal(string(sub)), nil
}
// Otherwise we need to start seeking forward again until we
// reach the length we want.
pos = 0
for i = 0; i < len(sub); {
d, _, _ := textseg.ScanGraphemeClusters(sub[i:], true)
i += d
pos++
if pos == length {
break
}
}
sub = sub[:i]
return cty.StringVal(string(sub)), nil
},
})
// Upper is a Function that converts a given string to uppercase.
func Upper(str cty.Value) (cty.Value, error) {
return UpperFunc.Call([]cty.Value{str})
}
// Lower is a Function that converts a given string to lowercase.
func Lower(str cty.Value) (cty.Value, error) {
return LowerFunc.Call([]cty.Value{str})
}
// Reverse is a Function that reverses the order of the characters in the
// given string.
//
// As usual, "character" for the sake of this function is a grapheme cluster,
// so combining diacritics (for example) will be considered together as a
// single character.
func Reverse(str cty.Value) (cty.Value, error) {
return ReverseFunc.Call([]cty.Value{str})
}
// Strlen is a Function that returns the length of the given string in
// characters.
//
// As usual, "character" for the sake of this function is a grapheme cluster,
// so combining diacritics (for example) will be considered together as a
// single character.
func Strlen(str cty.Value) (cty.Value, error) {
return StrlenFunc.Call([]cty.Value{str})
}
// Substr is a Function that extracts a sequence of characters from another
// string and creates a new string.
//
// As usual, "character" for the sake of this function is a grapheme cluster,
// so combining diacritics (for example) will be considered together as a
// single character.
//
// The "offset" index may be negative, in which case it is relative to the
// end of the given string.
//
// The "length" may be -1, in which case the remainder of the string after
// the given offset will be returned.
func Substr(str cty.Value, offset cty.Value, length cty.Value) (cty.Value, error) {
return SubstrFunc.Call([]cty.Value{str, offset, length})
}

7
vendor/github.com/zclconf/go-cty/cty/gocty/doc.go generated vendored Normal file
View File

@ -0,0 +1,7 @@
// Package gocty deals with converting between cty Values and native go
// values.
//
// It operates under a similar principle to the encoding/json and
// encoding/xml packages in the standard library, using reflection to
// populate native Go data structures from cty values and vice-versa.
package gocty

43
vendor/github.com/zclconf/go-cty/cty/gocty/helpers.go generated vendored Normal file
View File

@ -0,0 +1,43 @@
package gocty
import (
"math/big"
"reflect"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/set"
)
var valueType = reflect.TypeOf(cty.Value{})
var typeType = reflect.TypeOf(cty.Type{})
var setType = reflect.TypeOf(set.Set{})
var bigFloatType = reflect.TypeOf(big.Float{})
var bigIntType = reflect.TypeOf(big.Int{})
var emptyInterfaceType = reflect.TypeOf(interface{}(nil))
var stringType = reflect.TypeOf("")
// structTagIndices interrogates the fields of the given type (which must
// be a struct type, or we'll panic) and returns a map from the cty
// attribute names declared via struct tags to the indices of the
// fields holding those tags.
//
// This function will panic if two fields within the struct are tagged with
// the same cty attribute name.
func structTagIndices(st reflect.Type) map[string]int {
ct := st.NumField()
ret := make(map[string]int, ct)
for i := 0; i < ct; i++ {
field := st.Field(i)
attrName := field.Tag.Get("cty")
if attrName != "" {
ret[attrName] = i
}
}
return ret
}

548
vendor/github.com/zclconf/go-cty/cty/gocty/in.go generated vendored Normal file
View File

@ -0,0 +1,548 @@
package gocty
import (
"math/big"
"reflect"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/set"
)
// ToCtyValue produces a cty.Value from a Go value. The result will conform
// to the given type, or an error will be returned if this is not possible.
//
// The target type serves as a hint to resolve ambiguities in the mapping.
// For example, the Go type set.Set tells us that the value is a set but
// does not describe the set's element type. This also allows for convenient
// conversions, such as populating a set from a slice rather than having to
// first explicitly instantiate a set.Set.
//
// The audience of this function is assumed to be the developers of Go code
// that is integrating with cty, and thus the error messages it returns are
// presented from Go's perspective. These messages are thus not appropriate
// for display to end-users. An error returned from ToCtyValue represents a
// bug in the calling program, not user error.
func ToCtyValue(val interface{}, ty cty.Type) (cty.Value, error) {
// 'path' starts off as empty but will grow for each level of recursive
// call we make, so by the time toCtyValue returns it is likely to have
// unused capacity on the end of it, depending on how deeply-recursive
// the given Type is.
path := make(cty.Path, 0)
return toCtyValue(reflect.ValueOf(val), ty, path)
}
func toCtyValue(val reflect.Value, ty cty.Type, path cty.Path) (cty.Value, error) {
if val != (reflect.Value{}) && val.Type().AssignableTo(valueType) {
// If the source value is a cty.Value then we'll try to just pass
// through to the target type directly.
return toCtyPassthrough(val, ty, path)
}
switch ty {
case cty.Bool:
return toCtyBool(val, path)
case cty.Number:
return toCtyNumber(val, path)
case cty.String:
return toCtyString(val, path)
case cty.DynamicPseudoType:
return toCtyDynamic(val, path)
}
switch {
case ty.IsListType():
return toCtyList(val, ty.ElementType(), path)
case ty.IsMapType():
return toCtyMap(val, ty.ElementType(), path)
case ty.IsSetType():
return toCtySet(val, ty.ElementType(), path)
case ty.IsObjectType():
return toCtyObject(val, ty.AttributeTypes(), path)
case ty.IsTupleType():
return toCtyTuple(val, ty.TupleElementTypes(), path)
case ty.IsCapsuleType():
return toCtyCapsule(val, ty, path)
}
// We should never fall out here
return cty.NilVal, path.NewErrorf("unsupported target type %#v", ty)
}
func toCtyBool(val reflect.Value, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.Bool), nil
}
switch val.Kind() {
case reflect.Bool:
return cty.BoolVal(val.Bool()), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to bool", val.Kind())
}
}
func toCtyNumber(val reflect.Value, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.Number), nil
}
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return cty.NumberIntVal(val.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return cty.NumberUIntVal(val.Uint()), nil
case reflect.Float32, reflect.Float64:
return cty.NumberFloatVal(val.Float()), nil
case reflect.Struct:
if val.Type().AssignableTo(bigIntType) {
bigInt := val.Interface().(big.Int)
bigFloat := (&big.Float{}).SetInt(&bigInt)
val = reflect.ValueOf(*bigFloat)
}
if val.Type().AssignableTo(bigFloatType) {
bigFloat := val.Interface().(big.Float)
return cty.NumberVal(&bigFloat), nil
}
fallthrough
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to number", val.Kind())
}
}
func toCtyString(val reflect.Value, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.String), nil
}
switch val.Kind() {
case reflect.String:
return cty.StringVal(val.String()), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to string", val.Kind())
}
}
func toCtyList(val reflect.Value, ety cty.Type, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.List(ety)), nil
}
switch val.Kind() {
case reflect.Slice:
if val.IsNil() {
return cty.NullVal(cty.List(ety)), nil
}
fallthrough
case reflect.Array:
if val.Len() == 0 {
return cty.ListValEmpty(ety), nil
}
// While we work on our elements we'll temporarily grow
// path to give us a place to put our index step.
path = append(path, cty.PathStep(nil))
vals := make([]cty.Value, val.Len())
for i := range vals {
var err error
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(i)),
}
vals[i], err = toCtyValue(val.Index(i), ety, path)
if err != nil {
return cty.NilVal, err
}
}
// Discard our extra path segment, retaining it as extra capacity
// for future appending to the path.
path = path[:len(path)-1]
return cty.ListVal(vals), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.List(ety))
}
}
func toCtyMap(val reflect.Value, ety cty.Type, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.Map(ety)), nil
}
switch val.Kind() {
case reflect.Map:
if val.IsNil() {
return cty.NullVal(cty.Map(ety)), nil
}
if val.Len() == 0 {
return cty.MapValEmpty(ety), nil
}
keyType := val.Type().Key()
if keyType.Kind() != reflect.String {
return cty.NilVal, path.NewErrorf("can't convert Go map with key type %s; key type must be string", keyType)
}
// While we work on our elements we'll temporarily grow
// path to give us a place to put our index step.
path = append(path, cty.PathStep(nil))
vals := make(map[string]cty.Value, val.Len())
for _, kv := range val.MapKeys() {
k := kv.String()
var err error
path[len(path)-1] = cty.IndexStep{
Key: cty.StringVal(k),
}
vals[k], err = toCtyValue(val.MapIndex(reflect.ValueOf(k)), ety, path)
if err != nil {
return cty.NilVal, err
}
}
// Discard our extra path segment, retaining it as extra capacity
// for future appending to the path.
path = path[:len(path)-1]
return cty.MapVal(vals), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Map(ety))
}
}
func toCtySet(val reflect.Value, ety cty.Type, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.Set(ety)), nil
}
var vals []cty.Value
switch val.Kind() {
case reflect.Slice:
if val.IsNil() {
return cty.NullVal(cty.Set(ety)), nil
}
fallthrough
case reflect.Array:
if val.Len() == 0 {
return cty.SetValEmpty(ety), nil
}
vals = make([]cty.Value, val.Len())
for i := range vals {
var err error
vals[i], err = toCtyValue(val.Index(i), ety, path)
if err != nil {
return cty.NilVal, err
}
}
case reflect.Struct:
if !val.Type().AssignableTo(setType) {
return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Type(), cty.Set(ety))
}
rawSet := val.Interface().(set.Set)
inVals := rawSet.Values()
if len(inVals) == 0 {
return cty.SetValEmpty(ety), nil
}
vals = make([]cty.Value, len(inVals))
for i := range inVals {
var err error
vals[i], err = toCtyValue(reflect.ValueOf(inVals[i]), ety, path)
if err != nil {
return cty.NilVal, err
}
}
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Set(ety))
}
return cty.SetVal(vals), nil
}
func toCtyObject(val reflect.Value, attrTypes map[string]cty.Type, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.Object(attrTypes)), nil
}
switch val.Kind() {
case reflect.Map:
if val.IsNil() {
return cty.NullVal(cty.Object(attrTypes)), nil
}
keyType := val.Type().Key()
if keyType.Kind() != reflect.String {
return cty.NilVal, path.NewErrorf("can't convert Go map with key type %s; key type must be string", keyType)
}
if len(attrTypes) == 0 {
return cty.EmptyObjectVal, nil
}
// While we work on our elements we'll temporarily grow
// path to give us a place to put our GetAttr step.
path = append(path, cty.PathStep(nil))
haveKeys := make(map[string]struct{}, val.Len())
for _, kv := range val.MapKeys() {
haveKeys[kv.String()] = struct{}{}
}
vals := make(map[string]cty.Value, len(attrTypes))
for k, at := range attrTypes {
var err error
path[len(path)-1] = cty.GetAttrStep{
Name: k,
}
if _, have := haveKeys[k]; !have {
vals[k] = cty.NullVal(at)
continue
}
vals[k], err = toCtyValue(val.MapIndex(reflect.ValueOf(k)), at, path)
if err != nil {
return cty.NilVal, err
}
}
// Discard our extra path segment, retaining it as extra capacity
// for future appending to the path.
path = path[:len(path)-1]
return cty.ObjectVal(vals), nil
case reflect.Struct:
if len(attrTypes) == 0 {
return cty.EmptyObjectVal, nil
}
// While we work on our elements we'll temporarily grow
// path to give us a place to put our GetAttr step.
path = append(path, cty.PathStep(nil))
attrFields := structTagIndices(val.Type())
vals := make(map[string]cty.Value, len(attrTypes))
for k, at := range attrTypes {
path[len(path)-1] = cty.GetAttrStep{
Name: k,
}
if fieldIdx, have := attrFields[k]; have {
var err error
vals[k], err = toCtyValue(val.Field(fieldIdx), at, path)
if err != nil {
return cty.NilVal, err
}
} else {
vals[k] = cty.NullVal(at)
}
}
// Discard our extra path segment, retaining it as extra capacity
// for future appending to the path.
path = path[:len(path)-1]
return cty.ObjectVal(vals), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Object(attrTypes))
}
}
func toCtyTuple(val reflect.Value, elemTypes []cty.Type, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.Tuple(elemTypes)), nil
}
switch val.Kind() {
case reflect.Slice:
if val.IsNil() {
return cty.NullVal(cty.Tuple(elemTypes)), nil
}
if val.Len() != len(elemTypes) {
return cty.NilVal, path.NewErrorf("wrong number of elements %d; need %d", val.Len(), len(elemTypes))
}
if len(elemTypes) == 0 {
return cty.EmptyTupleVal, nil
}
// While we work on our elements we'll temporarily grow
// path to give us a place to put our Index step.
path = append(path, cty.PathStep(nil))
vals := make([]cty.Value, len(elemTypes))
for i, ety := range elemTypes {
var err error
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(i)),
}
vals[i], err = toCtyValue(val.Index(i), ety, path)
if err != nil {
return cty.NilVal, err
}
}
// Discard our extra path segment, retaining it as extra capacity
// for future appending to the path.
path = path[:len(path)-1]
return cty.TupleVal(vals), nil
case reflect.Struct:
fieldCount := val.Type().NumField()
if fieldCount != len(elemTypes) {
return cty.NilVal, path.NewErrorf("wrong number of struct fields %d; need %d", fieldCount, len(elemTypes))
}
if len(elemTypes) == 0 {
return cty.EmptyTupleVal, nil
}
// While we work on our elements we'll temporarily grow
// path to give us a place to put our Index step.
path = append(path, cty.PathStep(nil))
vals := make([]cty.Value, len(elemTypes))
for i, ety := range elemTypes {
var err error
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(i)),
}
vals[i], err = toCtyValue(val.Field(i), ety, path)
if err != nil {
return cty.NilVal, err
}
}
// Discard our extra path segment, retaining it as extra capacity
// for future appending to the path.
path = path[:len(path)-1]
return cty.TupleVal(vals), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Tuple(elemTypes))
}
}
func toCtyCapsule(val reflect.Value, capsuleType cty.Type, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(capsuleType), nil
}
if val.Kind() != reflect.Ptr {
if !val.CanAddr() {
return cty.NilVal, path.NewErrorf("source value for capsule %#v must be addressable", capsuleType)
}
val = val.Addr()
}
if !val.Type().Elem().AssignableTo(capsuleType.EncapsulatedType()) {
return cty.NilVal, path.NewErrorf("value of type %T not compatible with capsule %#v", val.Interface(), capsuleType)
}
return cty.CapsuleVal(capsuleType, val.Interface()), nil
}
func toCtyDynamic(val reflect.Value, path cty.Path) (cty.Value, error) {
if val = toCtyUnwrapPointer(val); !val.IsValid() {
return cty.NullVal(cty.DynamicPseudoType), nil
}
switch val.Kind() {
case reflect.Struct:
if !val.Type().AssignableTo(valueType) {
return cty.NilVal, path.NewErrorf("can't convert Go %s dynamically; only cty.Value allowed", val.Type())
}
return val.Interface().(cty.Value), nil
default:
return cty.NilVal, path.NewErrorf("can't convert Go %s dynamically; only cty.Value allowed", val.Kind())
}
}
func toCtyPassthrough(wrappedVal reflect.Value, wantTy cty.Type, path cty.Path) (cty.Value, error) {
if wrappedVal = toCtyUnwrapPointer(wrappedVal); !wrappedVal.IsValid() {
return cty.NullVal(wantTy), nil
}
givenVal := wrappedVal.Interface().(cty.Value)
val, err := convert.Convert(givenVal, wantTy)
if err != nil {
return cty.NilVal, path.NewErrorf("unsuitable value: %s", err)
}
return val, nil
}
// toCtyUnwrapPointer is a helper for dealing with Go pointers. It has three
// possible outcomes:
//
// - Given value isn't a pointer, so it's just returned as-is.
// - Given value is a non-nil pointer, in which case it is dereferenced
// and the result returned.
// - Given value is a nil pointer, in which case an invalid value is returned.
//
// For nested pointer types, like **int, they are all dereferenced in turn
// until a non-pointer value is found, or until a nil pointer is encountered.
func toCtyUnwrapPointer(val reflect.Value) reflect.Value {
for val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
if val.IsNil() {
return reflect.Value{}
}
val = val.Elem()
}
return val
}

686
vendor/github.com/zclconf/go-cty/cty/gocty/out.go generated vendored Normal file
View File

@ -0,0 +1,686 @@
package gocty
import (
"math"
"math/big"
"reflect"
"github.com/zclconf/go-cty/cty"
)
// FromCtyValue assigns a cty.Value to a reflect.Value, which must be a pointer,
// using a fixed set of conversion rules.
//
// This function considers its audience to be the creator of the cty Value
// given, and thus the error messages it generates are (unlike with ToCtyValue)
// presented in cty terminology that is generally appropriate to return to
// end-users in applications where cty data structures are built from
// user-provided configuration. In particular this means that if incorrect
// target types are provided by the calling application the resulting error
// messages are likely to be confusing, since we assume that the given target
// type is correct and the cty.Value is where the error lies.
//
// If an error is returned, the target data structure may have been partially
// populated, but the degree to which this is true is an implementation
// detail that the calling application should not rely on.
//
// The function will panic if given a non-pointer as the Go value target,
// since that is considered to be a bug in the calling program.
func FromCtyValue(val cty.Value, target interface{}) error {
tVal := reflect.ValueOf(target)
if tVal.Kind() != reflect.Ptr {
panic("target value is not a pointer")
}
if tVal.IsNil() {
panic("target value is nil pointer")
}
// 'path' starts off as empty but will grow for each level of recursive
// call we make, so by the time fromCtyValue returns it is likely to have
// unused capacity on the end of it, depending on how deeply-recursive
// the given cty.Value is.
path := make(cty.Path, 0)
return fromCtyValue(val, tVal, path)
}
func fromCtyValue(val cty.Value, target reflect.Value, path cty.Path) error {
ty := val.Type()
deepTarget := fromCtyPopulatePtr(target, false)
// If we're decoding into a cty.Value then we just pass through the
// value as-is, to enable partial decoding. This is the only situation
// where unknown values are permitted.
if deepTarget.Kind() == reflect.Struct && deepTarget.Type().AssignableTo(valueType) {
deepTarget.Set(reflect.ValueOf(val))
return nil
}
// Lists and maps can be nil without indirection, but everything else
// requires a pointer and we set it immediately to nil.
// We also make an exception for capsule types because we want to handle
// pointers specially for these.
// (fromCtyList and fromCtyMap must therefore deal with val.IsNull, while
// other types can assume no nulls after this point.)
if val.IsNull() && !val.Type().IsListType() && !val.Type().IsMapType() && !val.Type().IsCapsuleType() {
target = fromCtyPopulatePtr(target, true)
if target.Kind() != reflect.Ptr {
return path.NewErrorf("null value is not allowed")
}
target.Set(reflect.Zero(target.Type()))
return nil
}
target = deepTarget
if !val.IsKnown() {
return path.NewErrorf("value must be known")
}
switch ty {
case cty.Bool:
return fromCtyBool(val, target, path)
case cty.Number:
return fromCtyNumber(val, target, path)
case cty.String:
return fromCtyString(val, target, path)
}
switch {
case ty.IsListType():
return fromCtyList(val, target, path)
case ty.IsMapType():
return fromCtyMap(val, target, path)
case ty.IsSetType():
return fromCtySet(val, target, path)
case ty.IsObjectType():
return fromCtyObject(val, target, path)
case ty.IsTupleType():
return fromCtyTuple(val, target, path)
case ty.IsCapsuleType():
return fromCtyCapsule(val, target, path)
}
// We should never fall out here; reaching here indicates a bug in this
// function.
return path.NewErrorf("unsupported source type %#v", ty)
}
func fromCtyBool(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Bool:
target.SetBool(val.True())
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyNumber(val cty.Value, target reflect.Value, path cty.Path) error {
bf := val.AsBigFloat()
switch target.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return fromCtyNumberInt(bf, target, path)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fromCtyNumberUInt(bf, target, path)
case reflect.Float32, reflect.Float64:
return fromCtyNumberFloat(bf, target, path)
case reflect.Struct:
return fromCtyNumberBig(bf, target, path)
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyNumberInt(bf *big.Float, target reflect.Value, path cty.Path) error {
// Doing this with switch rather than << arithmetic because << with
// result >32-bits is not portable to 32-bit systems.
var min int64
var max int64
switch target.Type().Bits() {
case 8:
min = math.MinInt8
max = math.MaxInt8
case 16:
min = math.MinInt16
max = math.MaxInt16
case 32:
min = math.MinInt32
max = math.MaxInt32
case 64:
min = math.MinInt64
max = math.MaxInt64
default:
panic("weird number of bits in target int")
}
iv, accuracy := bf.Int64()
if accuracy != big.Exact || iv < min || iv > max {
return path.NewErrorf("value must be a whole number, between %d and %d", min, max)
}
target.SetInt(iv)
return nil
}
func fromCtyNumberUInt(bf *big.Float, target reflect.Value, path cty.Path) error {
// Doing this with switch rather than << arithmetic because << with
// result >32-bits is not portable to 32-bit systems.
var max uint64
switch target.Type().Bits() {
case 8:
max = math.MaxUint8
case 16:
max = math.MaxUint16
case 32:
max = math.MaxUint32
case 64:
max = math.MaxUint64
default:
panic("weird number of bits in target uint")
}
iv, accuracy := bf.Uint64()
if accuracy != big.Exact || iv > max {
return path.NewErrorf("value must be a whole number, between 0 and %d inclusive", max)
}
target.SetUint(iv)
return nil
}
func fromCtyNumberFloat(bf *big.Float, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Float32, reflect.Float64:
fv, accuracy := bf.Float64()
if accuracy != big.Exact {
// We allow the precision to be truncated as part of our conversion,
// but we don't want to silently introduce infinities.
if math.IsInf(fv, 0) {
return path.NewErrorf("value must be between %f and %f inclusive", -math.MaxFloat64, math.MaxFloat64)
}
}
target.SetFloat(fv)
return nil
default:
panic("unsupported kind of float")
}
}
func fromCtyNumberBig(bf *big.Float, target reflect.Value, path cty.Path) error {
switch {
case bigFloatType.ConvertibleTo(target.Type()):
// Easy!
target.Set(reflect.ValueOf(bf).Elem().Convert(target.Type()))
return nil
case bigIntType.ConvertibleTo(target.Type()):
bi, accuracy := bf.Int(nil)
if accuracy != big.Exact {
return path.NewErrorf("value must be a whole number")
}
target.Set(reflect.ValueOf(bi).Elem().Convert(target.Type()))
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyString(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.String:
target.SetString(val.AsString())
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyList(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Slice:
if val.IsNull() {
target.Set(reflect.Zero(target.Type()))
return nil
}
length := val.LengthInt()
tv := reflect.MakeSlice(target.Type(), length, length)
path = append(path, nil)
i := 0
var err error
val.ForEachElement(func(key cty.Value, val cty.Value) bool {
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(i)),
}
targetElem := tv.Index(i)
err = fromCtyValue(val, targetElem, path)
if err != nil {
return true
}
i++
return false
})
if err != nil {
return err
}
path = path[:len(path)-1]
target.Set(tv)
return nil
case reflect.Array:
if val.IsNull() {
return path.NewErrorf("null value is not allowed")
}
length := val.LengthInt()
if length != target.Len() {
return path.NewErrorf("must be a list of length %d", target.Len())
}
path = append(path, nil)
i := 0
var err error
val.ForEachElement(func(key cty.Value, val cty.Value) bool {
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(i)),
}
targetElem := target.Index(i)
err = fromCtyValue(val, targetElem, path)
if err != nil {
return true
}
i++
return false
})
if err != nil {
return err
}
path = path[:len(path)-1]
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyMap(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Map:
if val.IsNull() {
target.Set(reflect.Zero(target.Type()))
return nil
}
tv := reflect.MakeMap(target.Type())
et := target.Type().Elem()
path = append(path, nil)
var err error
val.ForEachElement(func(key cty.Value, val cty.Value) bool {
path[len(path)-1] = cty.IndexStep{
Key: key,
}
ks := key.AsString()
targetElem := reflect.New(et)
err = fromCtyValue(val, targetElem, path)
tv.SetMapIndex(reflect.ValueOf(ks), targetElem.Elem())
return err != nil
})
if err != nil {
return err
}
path = path[:len(path)-1]
target.Set(tv)
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtySet(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Slice:
if val.IsNull() {
target.Set(reflect.Zero(target.Type()))
return nil
}
length := val.LengthInt()
tv := reflect.MakeSlice(target.Type(), length, length)
i := 0
var err error
val.ForEachElement(func(key cty.Value, val cty.Value) bool {
targetElem := tv.Index(i)
err = fromCtyValue(val, targetElem, path)
if err != nil {
return true
}
i++
return false
})
if err != nil {
return err
}
target.Set(tv)
return nil
case reflect.Array:
if val.IsNull() {
return path.NewErrorf("null value is not allowed")
}
length := val.LengthInt()
if length != target.Len() {
return path.NewErrorf("must be a set of length %d", target.Len())
}
i := 0
var err error
val.ForEachElement(func(key cty.Value, val cty.Value) bool {
targetElem := target.Index(i)
err = fromCtyValue(val, targetElem, path)
if err != nil {
return true
}
i++
return false
})
if err != nil {
return err
}
return nil
// TODO: decode into set.Set instance
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyObject(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Struct:
attrTypes := val.Type().AttributeTypes()
targetFields := structTagIndices(target.Type())
path = append(path, nil)
for k, i := range targetFields {
if _, exists := attrTypes[k]; !exists {
// If the field in question isn't able to represent nil,
// that's an error.
fk := target.Field(i).Kind()
switch fk {
case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface:
// okay
default:
return path.NewErrorf("missing required attribute %q", k)
}
}
}
for k := range attrTypes {
path[len(path)-1] = cty.GetAttrStep{
Name: k,
}
fieldIdx, exists := targetFields[k]
if !exists {
return path.NewErrorf("unsupported attribute %q", k)
}
ev := val.GetAttr(k)
targetField := target.Field(fieldIdx)
err := fromCtyValue(ev, targetField, path)
if err != nil {
return err
}
}
path = path[:len(path)-1]
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyTuple(val cty.Value, target reflect.Value, path cty.Path) error {
switch target.Kind() {
case reflect.Struct:
elemTypes := val.Type().TupleElementTypes()
fieldCount := target.Type().NumField()
if fieldCount != len(elemTypes) {
return path.NewErrorf("a tuple of %d elements is required", fieldCount)
}
path = append(path, nil)
for i := range elemTypes {
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(i)),
}
ev := val.Index(cty.NumberIntVal(int64(i)))
targetField := target.Field(i)
err := fromCtyValue(ev, targetField, path)
if err != nil {
return err
}
}
path = path[:len(path)-1]
return nil
default:
return likelyRequiredTypesError(path, target)
}
}
func fromCtyCapsule(val cty.Value, target reflect.Value, path cty.Path) error {
if target.Kind() == reflect.Ptr {
// Walk through indirection until we get to the last pointer,
// which we might set to null below.
target = fromCtyPopulatePtr(target, true)
if val.IsNull() {
target.Set(reflect.Zero(target.Type()))
return nil
}
// Since a capsule contains a pointer to an object, we'll preserve
// that pointer on the way out and thus allow the caller to recover
// the original object, rather than a copy of it.
eType := val.Type().EncapsulatedType()
if !eType.AssignableTo(target.Elem().Type()) {
// Our interface contract promises that we won't expose Go
// implementation details in error messages, so we need to keep
// this vague. This can only arise if a calling application has
// more than one capsule type in play and a user mixes them up.
return path.NewErrorf("incorrect type %s", val.Type().FriendlyName())
}
target.Set(reflect.ValueOf(val.EncapsulatedValue()))
return nil
} else {
if val.IsNull() {
return path.NewErrorf("null value is not allowed")
}
// If our target isn't a pointer then we will attempt to copy
// the encapsulated value into it.
eType := val.Type().EncapsulatedType()
if !eType.AssignableTo(target.Type()) {
// Our interface contract promises that we won't expose Go
// implementation details in error messages, so we need to keep
// this vague. This can only arise if a calling application has
// more than one capsule type in play and a user mixes them up.
return path.NewErrorf("incorrect type %s", val.Type().FriendlyName())
}
// We know that EncapsulatedValue is always a pointer, so we
// can safely call .Elem on its reflect.Value.
target.Set(reflect.ValueOf(val.EncapsulatedValue()).Elem())
return nil
}
}
// fromCtyPopulatePtr recognizes when target is a pointer type and allocates
// a value to assign to that pointer, which it returns.
//
// If the given value has multiple levels of indirection, like **int, these
// will be processed in turn so that the return value is guaranteed to be
// a non-pointer.
//
// As an exception, if decodingNull is true then the returned value will be
// the final level of pointer, if any, so that the caller can assign it
// as nil to represent a null value. If the given target value is not a pointer
// at all then the returned value will be just the given target, so the caller
// must test if the returned value is a pointer before trying to assign nil
// to it.
func fromCtyPopulatePtr(target reflect.Value, decodingNull bool) reflect.Value {
for {
if target.Kind() == reflect.Interface && !target.IsNil() {
e := target.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
target = e
}
}
if target.Kind() != reflect.Ptr {
break
}
// Stop early if we're decodingNull and we've found our last indirection
if target.Elem().Kind() != reflect.Ptr && decodingNull && target.CanSet() {
break
}
if target.IsNil() {
target.Set(reflect.New(target.Type().Elem()))
}
target = target.Elem()
}
return target
}
// likelyRequiredTypesError returns an error that states which types are
// acceptable by making some assumptions about what types we support for
// each target Go kind. It's not a precise science but it allows us to return
// an error message that is cty-user-oriented rather than Go-oriented.
//
// Generally these error messages should be a matter of last resort, since
// the calling application should be validating user-provided value types
// before decoding anyway.
func likelyRequiredTypesError(path cty.Path, target reflect.Value) error {
switch target.Kind() {
case reflect.Bool:
return path.NewErrorf("bool value is required")
case reflect.String:
return path.NewErrorf("string value is required")
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fallthrough
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
fallthrough
case reflect.Float32, reflect.Float64:
return path.NewErrorf("number value is required")
case reflect.Slice, reflect.Array:
return path.NewErrorf("list or set value is required")
case reflect.Map:
return path.NewErrorf("map or object value is required")
case reflect.Struct:
switch {
case target.Type().AssignableTo(bigFloatType) || target.Type().AssignableTo(bigIntType):
return path.NewErrorf("number value is required")
case target.Type().AssignableTo(setType):
return path.NewErrorf("set or list value is required")
default:
return path.NewErrorf("object or tuple value is required")
}
default:
// We should avoid getting into this path, since this error
// message is rather useless.
return path.NewErrorf("incorrect type")
}
}

View File

@ -0,0 +1,108 @@
package gocty
import (
"reflect"
"github.com/zclconf/go-cty/cty"
)
// ImpliedType takes an arbitrary Go value (as an interface{}) and attempts
// to find a suitable cty.Type instance that could be used for a conversion
// with ToCtyValue.
//
// This allows -- for simple situations at least -- types to be defined just
// once in Go and the cty types derived from the Go types, but in the process
// it makes some assumptions that may be undesirable so applications are
// encouraged to build their cty types directly if exacting control is
// required.
//
// Not all Go types can be represented as cty types, so an error may be
// returned which is usually considered to be a bug in the calling program.
// In particular, ImpliedType will never use capsule types in its returned
// type, because it cannot know the capsule types supported by the calling
// program.
func ImpliedType(gv interface{}) (cty.Type, error) {
rt := reflect.TypeOf(gv)
var path cty.Path
return impliedType(rt, path)
}
func impliedType(rt reflect.Type, path cty.Path) (cty.Type, error) {
switch rt.Kind() {
case reflect.Ptr:
return impliedType(rt.Elem(), path)
// Primitive types
case reflect.Bool:
return cty.Bool, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return cty.Number, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return cty.Number, nil
case reflect.Float32, reflect.Float64:
return cty.Number, nil
case reflect.String:
return cty.String, nil
// Collection types
case reflect.Slice:
path := append(path, cty.IndexStep{Key: cty.UnknownVal(cty.Number)})
ety, err := impliedType(rt.Elem(), path)
if err != nil {
return cty.NilType, err
}
return cty.List(ety), nil
case reflect.Map:
if !stringType.AssignableTo(rt.Key()) {
return cty.NilType, path.NewErrorf("no cty.Type for %s (must have string keys)", rt)
}
path := append(path, cty.IndexStep{Key: cty.UnknownVal(cty.String)})
ety, err := impliedType(rt.Elem(), path)
if err != nil {
return cty.NilType, err
}
return cty.Map(ety), nil
// Structural types
case reflect.Struct:
return impliedStructType(rt, path)
default:
return cty.NilType, path.NewErrorf("no cty.Type for %s", rt)
}
}
func impliedStructType(rt reflect.Type, path cty.Path) (cty.Type, error) {
if valueType.AssignableTo(rt) {
// Special case: cty.Value represents cty.DynamicPseudoType, for
// type conformance checking.
return cty.DynamicPseudoType, nil
}
fieldIdxs := structTagIndices(rt)
if len(fieldIdxs) == 0 {
return cty.NilType, path.NewErrorf("no cty.Type for %s (no cty field tags)", rt)
}
atys := make(map[string]cty.Type, len(fieldIdxs))
{
// Temporary extension of path for attributes
path := append(path, nil)
for k, fi := range fieldIdxs {
path[len(path)-1] = cty.GetAttrStep{Name: k}
ft := rt.Field(fi).Type
aty, err := impliedType(ft, path)
if err != nil {
return cty.NilType, err
}
atys[k] = aty
}
}
return cty.Object(atys), nil
}

11
vendor/github.com/zclconf/go-cty/cty/json/doc.go generated vendored Normal file
View File

@ -0,0 +1,11 @@
// Package json provides functions for serializing cty types and values in
// JSON format, and for decoding them again.
//
// Since the cty type system is a superset of the JSON type system,
// round-tripping through JSON is lossy unless type information is provided
// both at encoding time and decoding time. Callers of this package are
// therefore suggested to define their expected structure as a cty.Type
// and pass it in consistently both when encoding and when decoding, though
// default (type-lossy) behavior is provided for situations where the precise
// representation of the data is not significant.
package json

193
vendor/github.com/zclconf/go-cty/cty/json/marshal.go generated vendored Normal file
View File

@ -0,0 +1,193 @@
package json
import (
"bytes"
"encoding/json"
"sort"
"github.com/zclconf/go-cty/cty"
)
func marshal(val cty.Value, t cty.Type, path cty.Path, b *bytes.Buffer) error {
if val.IsMarked() {
return path.NewErrorf("value has marks, so it cannot be seralized")
}
// If we're going to decode as DynamicPseudoType then we need to save
// dynamic type information to recover the real type.
if t == cty.DynamicPseudoType && val.Type() != cty.DynamicPseudoType {
return marshalDynamic(val, path, b)
}
if val.IsNull() {
b.WriteString("null")
return nil
}
if !val.IsKnown() {
return path.NewErrorf("value is not known")
}
// The caller should've guaranteed that the given val is conformant with
// the given type t, so we'll proceed under that assumption here.
switch {
case t.IsPrimitiveType():
switch t {
case cty.String:
json, err := json.Marshal(val.AsString())
if err != nil {
return path.NewErrorf("failed to serialize value: %s", err)
}
b.Write(json)
return nil
case cty.Number:
if val.RawEquals(cty.PositiveInfinity) || val.RawEquals(cty.NegativeInfinity) {
return path.NewErrorf("cannot serialize infinity as JSON")
}
b.WriteString(val.AsBigFloat().Text('f', -1))
return nil
case cty.Bool:
if val.True() {
b.WriteString("true")
} else {
b.WriteString("false")
}
return nil
default:
panic("unsupported primitive type")
}
case t.IsListType(), t.IsSetType():
b.WriteRune('[')
first := true
ety := t.ElementType()
it := val.ElementIterator()
path := append(path, nil) // local override of 'path' with extra element
for it.Next() {
if !first {
b.WriteRune(',')
}
ek, ev := it.Element()
path[len(path)-1] = cty.IndexStep{
Key: ek,
}
err := marshal(ev, ety, path, b)
if err != nil {
return err
}
first = false
}
b.WriteRune(']')
return nil
case t.IsMapType():
b.WriteRune('{')
first := true
ety := t.ElementType()
it := val.ElementIterator()
path := append(path, nil) // local override of 'path' with extra element
for it.Next() {
if !first {
b.WriteRune(',')
}
ek, ev := it.Element()
path[len(path)-1] = cty.IndexStep{
Key: ek,
}
var err error
err = marshal(ek, ek.Type(), path, b)
if err != nil {
return err
}
b.WriteRune(':')
err = marshal(ev, ety, path, b)
if err != nil {
return err
}
first = false
}
b.WriteRune('}')
return nil
case t.IsTupleType():
b.WriteRune('[')
etys := t.TupleElementTypes()
it := val.ElementIterator()
path := append(path, nil) // local override of 'path' with extra element
i := 0
for it.Next() {
if i > 0 {
b.WriteRune(',')
}
ety := etys[i]
ek, ev := it.Element()
path[len(path)-1] = cty.IndexStep{
Key: ek,
}
err := marshal(ev, ety, path, b)
if err != nil {
return err
}
i++
}
b.WriteRune(']')
return nil
case t.IsObjectType():
b.WriteRune('{')
atys := t.AttributeTypes()
path := append(path, nil) // local override of 'path' with extra element
names := make([]string, 0, len(atys))
for k := range atys {
names = append(names, k)
}
sort.Strings(names)
for i, k := range names {
aty := atys[k]
if i > 0 {
b.WriteRune(',')
}
av := val.GetAttr(k)
path[len(path)-1] = cty.GetAttrStep{
Name: k,
}
var err error
err = marshal(cty.StringVal(k), cty.String, path, b)
if err != nil {
return err
}
b.WriteRune(':')
err = marshal(av, aty, path, b)
if err != nil {
return err
}
}
b.WriteRune('}')
return nil
case t.IsCapsuleType():
rawVal := val.EncapsulatedValue()
jsonVal, err := json.Marshal(rawVal)
if err != nil {
return path.NewError(err)
}
b.Write(jsonVal)
return nil
default:
// should never happen
return path.NewErrorf("cannot JSON-serialize %s", t.FriendlyName())
}
}
// marshalDynamic adds an extra wrapping object containing dynamic type
// information for the given value.
func marshalDynamic(val cty.Value, path cty.Path, b *bytes.Buffer) error {
typeJSON, err := MarshalType(val.Type())
if err != nil {
return path.NewErrorf("failed to serialize type: %s", err)
}
b.WriteString(`{"value":`)
marshal(val, val.Type(), path, b)
b.WriteString(`,"type":`)
b.Write(typeJSON)
b.WriteRune('}')
return nil
}

41
vendor/github.com/zclconf/go-cty/cty/json/simple.go generated vendored Normal file
View File

@ -0,0 +1,41 @@
package json
import (
"github.com/zclconf/go-cty/cty"
)
// SimpleJSONValue is a wrapper around cty.Value that adds implementations of
// json.Marshaler and json.Unmarshaler for simple-but-type-lossy automatic
// encoding and decoding of values.
//
// The couplet Marshal and Unmarshal both take extra type information to
// inform the encoding and decoding process so that all of the cty types
// can be represented even though JSON's type system is a subset.
//
// SimpleJSONValue instead takes the approach of discarding the value's type
// information and then deriving a new type from the stored structure when
// decoding. This results in the same data being returned but not necessarily
// with exactly the same type.
//
// For information on how types are inferred when decoding, see the
// documentation of the function ImpliedType.
type SimpleJSONValue struct {
cty.Value
}
// MarshalJSON is an implementation of json.Marshaler. See the documentation
// of SimpleJSONValue for more information.
func (v SimpleJSONValue) MarshalJSON() ([]byte, error) {
return Marshal(v.Value, v.Type())
}
// UnmarshalJSON is an implementation of json.Unmarshaler. See the
// documentation of SimpleJSONValue for more information.
func (v *SimpleJSONValue) UnmarshalJSON(buf []byte) error {
t, err := ImpliedType(buf)
if err != nil {
return err
}
v.Value, err = Unmarshal(buf, t)
return err
}

23
vendor/github.com/zclconf/go-cty/cty/json/type.go generated vendored Normal file
View File

@ -0,0 +1,23 @@
package json
import (
"github.com/zclconf/go-cty/cty"
)
// MarshalType returns a JSON serialization of the given type.
//
// This is just a thin wrapper around t.MarshalJSON, for symmetry with
// UnmarshalType.
func MarshalType(t cty.Type) ([]byte, error) {
return t.MarshalJSON()
}
// UnmarshalType decodes a JSON serialization of the given type as produced
// by either Type.MarshalJSON or MarshalType.
//
// This is a convenience wrapper around Type.UnmarshalJSON.
func UnmarshalType(buf []byte) (cty.Type, error) {
var t cty.Type
err := t.UnmarshalJSON(buf)
return t, err
}

View File

@ -0,0 +1,170 @@
package json
import (
"bytes"
"encoding/json"
"fmt"
"github.com/zclconf/go-cty/cty"
)
// ImpliedType returns the cty Type implied by the structure of the given
// JSON-compliant buffer. This function implements the default type mapping
// behavior used when decoding arbitrary JSON without explicit cty Type
// information.
//
// The rules are as follows:
//
// JSON strings, numbers and bools map to their equivalent primitive type in
// cty.
//
// JSON objects map to cty object types, with the attributes defined by the
// object keys and the types of their values.
//
// JSON arrays map to cty tuple types, with the elements defined by the
// types of the array members.
//
// Any nulls are typed as DynamicPseudoType, so callers of this function
// must be prepared to deal with this. Callers that do not wish to deal with
// dynamic typing should not use this function and should instead describe
// their required types explicitly with a cty.Type instance when decoding.
//
// Any JSON syntax errors will be returned as an error, and the type will
// be the invalid value cty.NilType.
func ImpliedType(buf []byte) (cty.Type, error) {
r := bytes.NewReader(buf)
dec := json.NewDecoder(r)
dec.UseNumber()
ty, err := impliedType(dec)
if err != nil {
return cty.NilType, err
}
if dec.More() {
return cty.NilType, fmt.Errorf("extraneous data after JSON object")
}
return ty, nil
}
func impliedType(dec *json.Decoder) (cty.Type, error) {
tok, err := dec.Token()
if err != nil {
return cty.NilType, err
}
return impliedTypeForTok(tok, dec)
}
func impliedTypeForTok(tok json.Token, dec *json.Decoder) (cty.Type, error) {
if tok == nil {
return cty.DynamicPseudoType, nil
}
switch ttok := tok.(type) {
case bool:
return cty.Bool, nil
case json.Number:
return cty.Number, nil
case string:
return cty.String, nil
case json.Delim:
switch rune(ttok) {
case '{':
return impliedObjectType(dec)
case '[':
return impliedTupleType(dec)
default:
return cty.NilType, fmt.Errorf("unexpected token %q", ttok)
}
default:
return cty.NilType, fmt.Errorf("unsupported JSON token %#v", tok)
}
}
func impliedObjectType(dec *json.Decoder) (cty.Type, error) {
// By the time we get in here, we've already consumed the { delimiter
// and so our next token should be the first object key.
var atys map[string]cty.Type
for {
// Read the object key first
tok, err := dec.Token()
if err != nil {
return cty.NilType, err
}
if ttok, ok := tok.(json.Delim); ok {
if rune(ttok) != '}' {
return cty.NilType, fmt.Errorf("unexpected delimiter %q", ttok)
}
break
}
key, ok := tok.(string)
if !ok {
return cty.NilType, fmt.Errorf("expected string but found %T", tok)
}
// Now read the value
tok, err = dec.Token()
if err != nil {
return cty.NilType, err
}
aty, err := impliedTypeForTok(tok, dec)
if err != nil {
return cty.NilType, err
}
if atys == nil {
atys = make(map[string]cty.Type)
}
atys[key] = aty
}
if len(atys) == 0 {
return cty.EmptyObject, nil
}
return cty.Object(atys), nil
}
func impliedTupleType(dec *json.Decoder) (cty.Type, error) {
// By the time we get in here, we've already consumed the [ delimiter
// and so our next token should be the first value.
var etys []cty.Type
for {
tok, err := dec.Token()
if err != nil {
return cty.NilType, err
}
if ttok, ok := tok.(json.Delim); ok {
if rune(ttok) == ']' {
break
}
}
ety, err := impliedTypeForTok(tok, dec)
if err != nil {
return cty.NilType, err
}
etys = append(etys, ety)
}
if len(etys) == 0 {
return cty.EmptyTuple, nil
}
return cty.Tuple(etys), nil
}

459
vendor/github.com/zclconf/go-cty/cty/json/unmarshal.go generated vendored Normal file
View File

@ -0,0 +1,459 @@
package json
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
)
func unmarshal(buf []byte, t cty.Type, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
tok, err := dec.Token()
if err != nil {
return cty.NilVal, path.NewError(err)
}
if tok == nil {
return cty.NullVal(t), nil
}
if t == cty.DynamicPseudoType {
return unmarshalDynamic(buf, path)
}
switch {
case t.IsPrimitiveType():
val, err := unmarshalPrimitive(tok, t, path)
if err != nil {
return cty.NilVal, err
}
return val, nil
case t.IsListType():
return unmarshalList(buf, t.ElementType(), path)
case t.IsSetType():
return unmarshalSet(buf, t.ElementType(), path)
case t.IsMapType():
return unmarshalMap(buf, t.ElementType(), path)
case t.IsTupleType():
return unmarshalTuple(buf, t.TupleElementTypes(), path)
case t.IsObjectType():
return unmarshalObject(buf, t.AttributeTypes(), path)
case t.IsCapsuleType():
return unmarshalCapsule(buf, t, path)
default:
return cty.NilVal, path.NewErrorf("unsupported type %s", t.FriendlyName())
}
}
func unmarshalPrimitive(tok json.Token, t cty.Type, path cty.Path) (cty.Value, error) {
switch t {
case cty.Bool:
switch v := tok.(type) {
case bool:
return cty.BoolVal(v), nil
case string:
val, err := convert.Convert(cty.StringVal(v), t)
if err != nil {
return cty.NilVal, path.NewError(err)
}
return val, nil
default:
return cty.NilVal, path.NewErrorf("bool is required")
}
case cty.Number:
if v, ok := tok.(json.Number); ok {
tok = string(v)
}
switch v := tok.(type) {
case string:
val, err := cty.ParseNumberVal(v)
if err != nil {
return cty.NilVal, path.NewError(err)
}
return val, nil
default:
return cty.NilVal, path.NewErrorf("number is required")
}
case cty.String:
switch v := tok.(type) {
case string:
return cty.StringVal(v), nil
case json.Number:
return cty.StringVal(string(v)), nil
case bool:
val, err := convert.Convert(cty.BoolVal(v), t)
if err != nil {
return cty.NilVal, path.NewError(err)
}
return val, nil
default:
return cty.NilVal, path.NewErrorf("string is required")
}
default:
// should never happen
panic("unsupported primitive type")
}
}
func unmarshalList(buf []byte, ety cty.Type, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
if err := requireDelim(dec, '['); err != nil {
return cty.NilVal, path.NewError(err)
}
var vals []cty.Value
{
path := append(path, nil)
var idx int64
for dec.More() {
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(idx),
}
idx++
rawVal, err := readRawValue(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read list value: %s", err)
}
el, err := unmarshal(rawVal, ety, path)
if err != nil {
return cty.NilVal, err
}
vals = append(vals, el)
}
}
if err := requireDelim(dec, ']'); err != nil {
return cty.NilVal, path.NewError(err)
}
if len(vals) == 0 {
return cty.ListValEmpty(ety), nil
}
return cty.ListVal(vals), nil
}
func unmarshalSet(buf []byte, ety cty.Type, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
if err := requireDelim(dec, '['); err != nil {
return cty.NilVal, path.NewError(err)
}
var vals []cty.Value
{
path := append(path, nil)
for dec.More() {
path[len(path)-1] = cty.IndexStep{
Key: cty.UnknownVal(ety),
}
rawVal, err := readRawValue(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read set value: %s", err)
}
el, err := unmarshal(rawVal, ety, path)
if err != nil {
return cty.NilVal, err
}
vals = append(vals, el)
}
}
if err := requireDelim(dec, ']'); err != nil {
return cty.NilVal, path.NewError(err)
}
if len(vals) == 0 {
return cty.SetValEmpty(ety), nil
}
return cty.SetVal(vals), nil
}
func unmarshalMap(buf []byte, ety cty.Type, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
if err := requireDelim(dec, '{'); err != nil {
return cty.NilVal, path.NewError(err)
}
vals := make(map[string]cty.Value)
{
path := append(path, nil)
for dec.More() {
path[len(path)-1] = cty.IndexStep{
Key: cty.UnknownVal(cty.String),
}
var err error
k, err := requireObjectKey(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read map key: %s", err)
}
path[len(path)-1] = cty.IndexStep{
Key: cty.StringVal(k),
}
rawVal, err := readRawValue(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read map value: %s", err)
}
el, err := unmarshal(rawVal, ety, path)
if err != nil {
return cty.NilVal, err
}
vals[k] = el
}
}
if err := requireDelim(dec, '}'); err != nil {
return cty.NilVal, path.NewError(err)
}
if len(vals) == 0 {
return cty.MapValEmpty(ety), nil
}
return cty.MapVal(vals), nil
}
func unmarshalTuple(buf []byte, etys []cty.Type, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
if err := requireDelim(dec, '['); err != nil {
return cty.NilVal, path.NewError(err)
}
var vals []cty.Value
{
path := append(path, nil)
var idx int
for dec.More() {
if idx >= len(etys) {
return cty.NilVal, path[:len(path)-1].NewErrorf("too many tuple elements (need %d)", len(etys))
}
path[len(path)-1] = cty.IndexStep{
Key: cty.NumberIntVal(int64(idx)),
}
ety := etys[idx]
idx++
rawVal, err := readRawValue(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read tuple value: %s", err)
}
el, err := unmarshal(rawVal, ety, path)
if err != nil {
return cty.NilVal, err
}
vals = append(vals, el)
}
}
if err := requireDelim(dec, ']'); err != nil {
return cty.NilVal, path.NewError(err)
}
if len(vals) != len(etys) {
return cty.NilVal, path[:len(path)-1].NewErrorf("not enough tuple elements (need %d)", len(etys))
}
if len(vals) == 0 {
return cty.EmptyTupleVal, nil
}
return cty.TupleVal(vals), nil
}
func unmarshalObject(buf []byte, atys map[string]cty.Type, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
if err := requireDelim(dec, '{'); err != nil {
return cty.NilVal, path.NewError(err)
}
vals := make(map[string]cty.Value)
{
objPath := path // some errors report from the object's perspective
path := append(path, nil) // path to a specific attribute
for dec.More() {
var err error
k, err := requireObjectKey(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read object key: %s", err)
}
aty, ok := atys[k]
if !ok {
return cty.NilVal, objPath.NewErrorf("unsupported attribute %q", k)
}
path[len(path)-1] = cty.GetAttrStep{
Name: k,
}
rawVal, err := readRawValue(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read object value: %s", err)
}
el, err := unmarshal(rawVal, aty, path)
if err != nil {
return cty.NilVal, err
}
vals[k] = el
}
}
if err := requireDelim(dec, '}'); err != nil {
return cty.NilVal, path.NewError(err)
}
// Make sure we have a value for every attribute
for k, aty := range atys {
if _, exists := vals[k]; !exists {
vals[k] = cty.NullVal(aty)
}
}
if len(vals) == 0 {
return cty.EmptyObjectVal, nil
}
return cty.ObjectVal(vals), nil
}
func unmarshalCapsule(buf []byte, t cty.Type, path cty.Path) (cty.Value, error) {
rawType := t.EncapsulatedType()
ptrPtr := reflect.New(reflect.PtrTo(rawType))
ptrPtr.Elem().Set(reflect.New(rawType))
ptr := ptrPtr.Elem().Interface()
err := json.Unmarshal(buf, ptr)
if err != nil {
return cty.NilVal, path.NewError(err)
}
return cty.CapsuleVal(t, ptr), nil
}
func unmarshalDynamic(buf []byte, path cty.Path) (cty.Value, error) {
dec := bufDecoder(buf)
if err := requireDelim(dec, '{'); err != nil {
return cty.NilVal, path.NewError(err)
}
var t cty.Type
var valBody []byte // defer actual decoding until we know the type
for dec.More() {
var err error
key, err := requireObjectKey(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read dynamic type descriptor key: %s", err)
}
rawVal, err := readRawValue(dec)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to read dynamic type descriptor value: %s", err)
}
switch key {
case "type":
err := json.Unmarshal(rawVal, &t)
if err != nil {
return cty.NilVal, path.NewErrorf("failed to decode type for dynamic value: %s", err)
}
case "value":
valBody = rawVal
default:
return cty.NilVal, path.NewErrorf("invalid key %q in dynamically-typed value", key)
}
}
if err := requireDelim(dec, '}'); err != nil {
return cty.NilVal, path.NewError(err)
}
if t == cty.NilType {
return cty.NilVal, path.NewErrorf("missing type in dynamically-typed value")
}
if valBody == nil {
return cty.NilVal, path.NewErrorf("missing value in dynamically-typed value")
}
val, err := Unmarshal([]byte(valBody), t)
if err != nil {
return cty.NilVal, path.NewError(err)
}
return val, nil
}
func requireDelim(dec *json.Decoder, d rune) error {
tok, err := dec.Token()
if err != nil {
return err
}
if tok != json.Delim(d) {
return fmt.Errorf("missing expected %c", d)
}
return nil
}
func requireObjectKey(dec *json.Decoder) (string, error) {
tok, err := dec.Token()
if err != nil {
return "", err
}
if s, ok := tok.(string); ok {
return s, nil
}
return "", fmt.Errorf("missing expected object key")
}
func readRawValue(dec *json.Decoder) ([]byte, error) {
var rawVal json.RawMessage
err := dec.Decode(&rawVal)
if err != nil {
return nil, err
}
return []byte(rawVal), nil
}
func bufDecoder(buf []byte) *json.Decoder {
r := bytes.NewReader(buf)
dec := json.NewDecoder(r)
dec.UseNumber()
return dec
}

65
vendor/github.com/zclconf/go-cty/cty/json/value.go generated vendored Normal file
View File

@ -0,0 +1,65 @@
package json
import (
"bytes"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
)
// Marshal produces a JSON representation of the given value that can later
// be decoded into a value of the given type.
//
// A type is specified separately to allow for the given type to include
// cty.DynamicPseudoType to represent situations where any type is permitted
// and so type information must be included to allow recovery of the stored
// structure when decoding.
//
// The given type will also be used to attempt automatic conversions of any
// non-conformant types in the given value, although this will not always
// be possible. If the value cannot be made to be conformant then an error is
// returned, which may be a cty.PathError.
//
// Capsule-typed values can be marshalled, but with some caveats. Since
// capsule values are compared by pointer equality, it is impossible to recover
// a value that will compare equal to the original value. Additionally,
// it's not possible to JSON-serialize the capsule type itself, so it's not
// valid to use capsule types within parts of the value that are conformed to
// cty.DynamicPseudoType. Otherwise, a capsule value can be used as long as
// the encapsulated type itself is serializable with the Marshal function
// in encoding/json.
func Marshal(val cty.Value, t cty.Type) ([]byte, error) {
errs := val.Type().TestConformance(t)
if errs != nil {
// Attempt a conversion
var err error
val, err = convert.Convert(val, t)
if err != nil {
return nil, err
}
}
// From this point onward, val can be assumed to be conforming to t.
buf := &bytes.Buffer{}
var path cty.Path
err := marshal(val, t, path, buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Unmarshal decodes a JSON representation of the given value into a cty Value
// conforming to the given type.
//
// While decoding, type conversions will be done where possible to make
// the result conformant even if the types given in JSON are not exactly
// correct. If conversion isn't possible then an error is returned, which
// may be a cty.PathError.
func Unmarshal(buf []byte, t cty.Type) (cty.Value, error) {
var path cty.Path
return unmarshal(buf, t, path)
}