Skip to content

Commit

Permalink
make customtype internal, add valast.RegisterType
Browse files Browse the repository at this point in the history
  • Loading branch information
bobheadxi committed Jul 24, 2024
1 parent 568f186 commit 33af7c2
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,7 @@ var (
customTypes = make(map[reflect.Type]func(any) ast.Expr)
)

// Register registers a type that for representation in a custom manner with
// valast. If valast encounters a value or pointer to a value of this type, it
// will use the given render func to generate the appropriate AST representation.
//
// This is useful if a type's fields are private, and can only be represented
// through a constructor - see stdtypes.go for examples.
//
// This mechanism currently only works with struct types.
// See the top-level valast.RegisterType docstring for details.
func Register[T any](render func(value T) ast.Expr) {
customTypesMux.Lock()
var zero T
Expand Down
4 changes: 1 addition & 3 deletions stdtypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"go/ast"
"go/token"
"time"

"github.com/hexops/valast/customtype"
)

// Register custom reprsentations of common structs from stdlib that only
Expand All @@ -15,7 +13,7 @@ func init() {
// For time.Time, returns the AST expression equivalent of:
//
// time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
customtype.Register(func(t time.Time) ast.Expr {
RegisterType(func(t time.Time) ast.Expr {
return &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.Ident{Name: "time"},
Expand Down
14 changes: 14 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,22 @@ import (
"go/ast"
"go/token"
"reflect"

"github.com/hexops/valast/internal/customtype"
)

// RegisterType registers a type that for representation in a custom manner with
// valast. If valast encounters a value or pointer to a value of this type, it
// will use the given render func to generate the appropriate AST representation.
//
// This is useful if a type's fields are private, and can only be represented
// through a constructor - see stdtypes.go for examples.
//
// This mechanism currently only works with struct types.
func RegisterType[T any](render func(value T) ast.Expr) {
customtype.Register(render)
}

type cacheKeyOptions struct {
Unqualify bool
PackagePath string
Expand Down
2 changes: 1 addition & 1 deletion valast.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import (
"strings"
"time"

"github.com/hexops/valast/customtype"
"github.com/hexops/valast/internal/bypass"
"github.com/hexops/valast/internal/customtype"
"golang.org/x/tools/go/packages"
gofumpt "mvdan.cc/gofumpt/format"
)
Expand Down

0 comments on commit 33af7c2

Please sign in to comment.