ToAST is a thin wrapper for the Go standard library ast package that provides a simple interface for working with Go types.
This package only supports parsing of type definitions. It was originally intended to be used for generating type definitions for other languages -- particularly CUE, a typesafe superset of JSON.
Each go/ast type specification maps to one of four structs:
PlainType: Basic types, type aliases, and pointersArrayType: Array and slice typesMapType: MapsStructType: Structs, which may contain fields that are themselves one of the four types.
There is also partial support for an EnumType, which is expressed by convention in Go as a type
declaration with a group of constants of the same type.
When parsing a file, ToAST can apply a number of transformations on matching objects:
ExcludeImportexcludes specific importsModifyImportmutates specific importsExcludeTypeDeclexcludes specific type declarationsExcludeTypeexcludes specific type declarations and referencesModifyTypemutates specific typesExcludeFieldexcludes specific fields in aStructTypeModifyFieldmutates specific fields in aStructTypeCopyIntoStructcopies fields from one or more namedStructTypes into a targetStructType, replacing the field at of a given namePromoteToEnumTypeconverts aPlainTypeinto anEnumTypeGenFieldTransformtakes aStructTypeand aFieldand returns someTransformthat can be matched on subsequent nodes in the fileGenEnumTypeTransformtakes a string andgo/ast.ValueSpecand returns aPromoteToEnumTypetransform that can be matched on aPlainTypein the file
First, load an *ast.File. For example:
import "go/parser"
filePath := "path/to/file.go"
astFile, err := parser.ParseFile(token.NewFileSet(), filePath, nil, parser.ParseComments)
if err != nil {
panic(err)
}Then create a *toast.File:
file := toast.NewFile(astFile,
WithTransform(&toast.ExcludeImport{
Match: func(i Import) bool {
return i.Name == "foo"
}
}),
WithTransform(&toast.ExcludeType{
Match: func(t Type) bool {
return t.Name == "bar"
}
}),
...
)