Skip to content

Commit d4776e8

Browse files
lang/funcs: type conversion functions can convert null values
We had intended these functions to attempt to convert any given value, but there is a special behavior in the function system where functions must opt in to being able to handle dynamically-typed arguments so that we don't need to repeat the special case for that inside every function implementation. In this case we _do_ want to specially handle dynamically-typed values, because the keyword "null" in HCL produces cty.NullVal(cty.DynamicPseudoType) and we want the conversion function to convert it to a null of a more specific type. These conversion functions are already just a thin wrapper around the underlying type conversion functionality anyway, and that already supports converting dynamic-typed values in the expected way, so we can just opt in to allowing dynamically-typed values and let the conversion functionality do the expected work. Fixing this allows module authors to use type conversion functions to give additional type information to Terraform in situations that are too ambiguous to be handled automatically by the type inference/unification process. Previously tostring(null) was effectively a no-op, totally ignoring the author's request to treat the null as a string.
1 parent 0028a26 commit d4776e8

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

internal/lang/funcs/conversion.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,10 @@ func MakeToFunc(wantTy cty.Type) function.Function {
3030
// messages to be more appropriate for an explicit type
3131
// conversion, whereas the cty function system produces
3232
// messages aimed at _implicit_ type conversions.
33-
Type: cty.DynamicPseudoType,
34-
AllowNull: true,
35-
AllowMarked: true,
33+
Type: cty.DynamicPseudoType,
34+
AllowNull: true,
35+
AllowMarked: true,
36+
AllowDynamicType: true,
3637
},
3738
},
3839
Type: func(args []cty.Value) (cty.Type, error) {

internal/lang/funcs/conversion_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,16 @@ func TestTo(t *testing.T) {
3333
cty.NullVal(cty.String),
3434
``,
3535
},
36+
{
37+
// This test case represents evaluating the expression tostring(null)
38+
// from HCL, since null in HCL is cty.NullVal(cty.DynamicPseudoType).
39+
// The result in that case should still be null, but a null specifically
40+
// of type string.
41+
cty.NullVal(cty.DynamicPseudoType),
42+
cty.String,
43+
cty.NullVal(cty.String),
44+
``,
45+
},
3646
{
3747
cty.StringVal("a").Mark("boop"),
3848
cty.String,

0 commit comments

Comments
 (0)