Skip to content

Commit

Permalink
fix: use go/printer to render nodes instead of manual traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
defaulterrr committed Mar 17, 2023
1 parent ad7b506 commit d00a43e
Show file tree
Hide file tree
Showing 5 changed files with 525 additions and 23 deletions.
29 changes: 6 additions & 23 deletions internal/types/interface.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package types

import (
"bytes"
"go/ast"
"go/printer"
"go/token"
)

Expand Down Expand Up @@ -105,29 +107,10 @@ func getTypeParams(typeSpec *ast.TypeSpec) []InterfaceSpecificationParam {
names = append(names, name.Name)
}

paramType := ""

ast.Print(token.NewFileSet(), param.Type)

switch node := param.Type.(type) {
// Direct declarations in form of
// [T int] or [T any]
case *ast.Ident:
paramType = node.Name
// Reference to a type, i.e.
// proto.Message

// we can reference those without worrying about external imports
// due to Go tooling being able to deduce missing imports from
// the surrounding context (files and existing references to types).
// i.e. user already referenced the type in the nearby file.
case *ast.SelectorExpr:
paramType = node.X.(*ast.Ident).Name + "." + node.Sel.Name
// Inline reference, i.e.
// int | float64
case *ast.BinaryExpr:
paramType = node.X.(*ast.Ident).Name + " | " + node.Y.(*ast.Ident).Name
}
var out bytes.Buffer
printer.Fprint(&out, token.NewFileSet(), param.Type)

paramType := out.String()

params = append(params, InterfaceSpecificationParam{
ParamNames: names,
Expand Down
6 changes: 6 additions & 0 deletions snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ func TestSnapshot(t *testing.T) {
outputFile: "./tests/generic_inline_union.go",
expectedOutputFile: "./tests/generic_inline_union.go",
},
{
name: "generics with complex inline union with many types",
inputInterface: "./tests.genericInlineUnionWithManyTypes",
outputFile: "./tests/generic_inline_with_many_options.go",
expectedOutputFile: "./tests/generic_inline_with_many_options.go",
},
}

for _, testCase := range testCases {
Expand Down

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

Loading

0 comments on commit d00a43e

Please sign in to comment.