From b857322d2795d6870140b0c3a9132c808b27819c Mon Sep 17 00:00:00 2001 From: Alisdair McDiarmid Date: Thu, 22 Sep 2022 10:59:20 -0400 Subject: [PATCH] ext/typeexpr: Convert defaults for optional attrs When parsing optional object attribute defaults, we previously verified that the default value was convertible to the attribute type. However, we did not keep this converted value. This commit uses the converted default value, rather than delaying conversion until later. In turn this prevents crashes when transforming collections which contain objects with optional attributes, caused by incompatible object types at the time of defaults application. --- ext/typeexpr/get_type.go | 4 +++- ext/typeexpr/get_type_test.go | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ext/typeexpr/get_type.go b/ext/typeexpr/get_type.go index 98a861e9..890cf8ed 100644 --- a/ext/typeexpr/get_type.go +++ b/ext/typeexpr/get_type.go @@ -249,7 +249,7 @@ func getType(expr hcl.Expression, constraint, withDefaults bool) (cty.Type, *Def // If a default is set for an optional attribute, verify that it is // convertible to the attribute type. if defaultVal, ok := defaultValues[attrName]; ok { - _, err := convert.Convert(defaultVal, aty) + convertedDefaultVal, err := convert.Convert(defaultVal, aty) if err != nil { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, @@ -258,6 +258,8 @@ func getType(expr hcl.Expression, constraint, withDefaults bool) (cty.Type, *Def Subject: defaultExpr.Range().Ptr(), }) delete(defaultValues, attrName) + } else { + defaultValues[attrName] = convertedDefaultVal } } diff --git a/ext/typeexpr/get_type_test.go b/ext/typeexpr/get_type_test.go index 2dca23d2..0249dffb 100644 --- a/ext/typeexpr/get_type_test.go +++ b/ext/typeexpr/get_type_test.go @@ -504,7 +504,9 @@ func TestGetTypeDefaults(t *testing.T) { }, []string{"b"}), }, []string{"a"}), DefaultValues: map[string]cty.Value{ - "a": cty.EmptyObjectVal, + "a": cty.ObjectVal(map[string]cty.Value{ + "b": cty.NullVal(cty.Number), + }), }, Children: map[string]*Defaults{ "a": {