Wrap any function that returns primitive
What would you like to be added?
In go function that would return int does not work as expected with go template as any function call is wrapped with (get (fromJson. The fromJson would convert any integer to float64.
Why is this needed?
To work with idiomatic go code and not worry about go template.
So I hacked up a weird workaround for this issue via this change to bootstrap.go:
// typeatest is the implementation of the go syntax `_, _ := m.(t)`.
func typetest(typ string, value, zero any) []any {
if TypeIs(typ, value) {
return []any{value, true}
}
return []any{zero, false}
}
// typeassertion is the implementation of the go syntax `_ := m.(t)`.
func typeassertion(typ string, value any) any {
// canCastToInt is a workaround for JSON always representing numbers as
// float64's. If a value is a float64 with no fractional value, it's considered
// to be an "integer like" float and therefore will pass when type checked via
// typetest or typeassertion.
canCastToInt := TypeIs("float64", value) && (Float64(value)-Floor(value)) == float64(0)
if typ == "int" && canCastToInt {
return Int(value)
} else if typ == "int32" && canCastToInt {
return Int(value)
} else if typ == "int64" && canCastToInt {
return Int64(value)
}
if !TypeIs(typ, value) {
panic(fmt.Sprintf("expected type of %q got: %T", typ, value))
}
return value
}
It could very well bite us if we need something to be an integral float64 but I don't think we'll ever actually hit that case.
That's great! I'm not sure how the type assertion would be included in the transpiled code for particular function call or rather it's returned value.
Thinking a bit more on I think a better solution would be to add a Cast option to the Call AST Node as that'll be less error prone.