Skip to content

Commit

Permalink
Generate return types
Browse files Browse the repository at this point in the history
  • Loading branch information
dbanck committed Oct 6, 2022
1 parent 9eef8d1 commit 7a695b6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 14 deletions.
8 changes: 4 additions & 4 deletions internal/funcs/0.12/base_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 32 additions & 10 deletions internal/funcs/0.12/funcgen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,38 @@ import (
"log"
"os"
"text/template"

"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/function/stdlib"
)

type function struct {
type fun struct {
Name string
InternalName string
ReturnType string
Function function.Function
}

var functions = []function{
var functions = []fun{
{
Name: "csvdecode",
InternalName: "CSVDecodeFunc",
ReturnType: "cty.DynamicPseudoType",
Function: stdlib.CSVDecodeFunc,
},
{
Name: "formatdate",
InternalName: "FormatDateFunc",
ReturnType: "cty.String",
Function: stdlib.FormatDateFunc,
},
{
Name: "jsondecode",
InternalName: "JSONDecodeFunc",
ReturnType: "cty.DynamicPseudoType",
Function: stdlib.JSONDecodeFunc,
},
{
Name: "reverse",
InternalName: "ReverseListFunc",
ReturnType: "cty.DynamicPseudoType",
Function: stdlib.ReverseListFunc,
},
}

Expand Down Expand Up @@ -65,20 +69,22 @@ func BaseFunctions() map[string]schema.FuncSignature {
"{{ .Name }}": {
Params: stdlib.{{ .InternalName }}.Params(),
VarParam: stdlib.{{ .InternalName }}.VarParam(),
ReturnTypes: {{ .ReturnType }}, // TODO use stdlib.FormatDateFunc.ReturnType(cty.DynamicPseudoType)
ReturnTypes: {{ getReturnType .Function }},
Description: stdlib.{{ .InternalName }}.Description(),
},
{{- end }}
}
}
`
tpl, err := template.New("output").Parse(outputTpl)
tpl, err := template.New("output").Funcs(template.FuncMap{
"getReturnType": getReturnType,
}).Parse(outputTpl)
if err != nil {
log.Fatal(err)
}

type data struct {
Functions []function
Functions []fun
}

err = tpl.Execute(output, data{
Expand All @@ -88,3 +94,19 @@ func BaseFunctions() map[string]schema.FuncSignature {
log.Fatal(err)
}
}

func getReturnType(f function.Function) (string, error) {
args := make([]cty.Type, 0)
for _, param := range f.Params() {
args = append(args, param.Type)
}
if f.VarParam() != nil {
args = append(args, f.VarParam().Type)
}

returnType, err := f.ReturnType(args)
if err != nil {
return "", err
}
return returnType.GoString(), nil
}

0 comments on commit 7a695b6

Please sign in to comment.