Skip to content

Commit

Permalink
lang/funcs: type conversion functions can convert null values
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
apparentlymart committed Apr 20, 2022
1 parent 0028a26 commit d4776e8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
7 changes: 4 additions & 3 deletions internal/lang/funcs/conversion.go
Expand Up @@ -30,9 +30,10 @@ func MakeToFunc(wantTy cty.Type) function.Function {
// messages to be more appropriate for an explicit type
// conversion, whereas the cty function system produces
// messages aimed at _implicit_ type conversions.
Type: cty.DynamicPseudoType,
AllowNull: true,
AllowMarked: true,
Type: cty.DynamicPseudoType,
AllowNull: true,
AllowMarked: true,
AllowDynamicType: true,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
Expand Down
10 changes: 10 additions & 0 deletions internal/lang/funcs/conversion_test.go
Expand Up @@ -33,6 +33,16 @@ func TestTo(t *testing.T) {
cty.NullVal(cty.String),
``,
},
{
// This test case represents evaluating the expression tostring(null)
// from HCL, since null in HCL is cty.NullVal(cty.DynamicPseudoType).
// The result in that case should still be null, but a null specifically
// of type string.
cty.NullVal(cty.DynamicPseudoType),
cty.String,
cty.NullVal(cty.String),
``,
},
{
cty.StringVal("a").Mark("boop"),
cty.String,
Expand Down

0 comments on commit d4776e8

Please sign in to comment.