Documentation
¶
Overview ¶
Package model defines an intermediate, reflect-agnostic representation of Go types used by the loader and code generation pipeline. It provides Nodes (basic, named, pointer, slice, map, func, interface, struct, union), type parameters for generics, containers for packages/files, and helpers to render go/ast declarations and formatted source.
Key types
- Type: single declaration with AST TypeSpec, optional ReflectType link, TypeParams for generics, MethodSet for programmatic access to value and pointer receiver methods, and AST-captured method stubs for exact stub rendering.
- GoFile/Package: containers with import merging and rendering helpers.
- Namespace: minimal aggregator for file-level rendering across types.
Index ¶
- Constants
- func RenderFunctionStub(fd *ast.FuncDecl) string
- func RenderMethodStub(fd *ast.FuncDecl) string
- func RenderTypeBodyFromSpec(spec *ast.TypeSpec) string
- type Alias
- type AliasOption
- type Array
- type ArrayOption
- type Basic
- type BasicOption
- type Chan
- type ChanOption
- type ConstDecl
- type Field
- type FieldOption
- type Func
- type FuncBuilder
- type FuncOption
- type Function
- type GoFile
- func (f *GoFile) AddConst(c ConstDecl)
- func (f *GoFile) AddEmbed(varName string, fsinst *embed.FS)
- func (f *GoFile) AddImport(ref ImportRef)
- func (f *GoFile) AddSideEffectImport(path string)
- func (f *GoFile) AddType(t *Type)
- func (f *GoFile) AddVar(v VarDecl)
- func (f *GoFile) HasConst(name string) bool
- func (f *GoFile) HasEmbed(varName string) bool
- func (f *GoFile) HasImport(path, alias string) bool
- func (f *GoFile) HasType(name string) bool
- func (f *GoFile) HasVar(name string) bool
- func (f *GoFile) Render() (string, error)
- func (f *GoFile) RenderWithMethods() (string, error)
- func (f *GoFile) RenderWithOptions(opts RenderOptions) (string, error)
- type ImportEntry
- type ImportRef
- type ImportSet
- type Interface
- type InterfaceBuilder
- type Kind
- type Map
- type MapOption
- type Method
- type MethodOption
- type MethodSet
- type Module
- type Named
- type NamedOption
- type Namespace
- func (n *Namespace) AddExternal(pkgPath, typeName, alias string)
- func (n *Namespace) AddImport(ref ImportRef)
- func (n *Namespace) AddType(t *Type)
- func (n *Namespace) BuildFiles(opts RenderOptions) (map[string]*GoFile, error)
- func (n *Namespace) HasImport(path, alias string) bool
- func (n *Namespace) HasType(name string) bool
- func (n *Namespace) KeyOf(t *Type) string
- func (n *Namespace) Render() (string, error)
- func (n *Namespace) RenderFile(pkgName string) (string, error)
- type Node
- type Package
- func (p *Package) AddConst(c ConstDecl)
- func (p *Package) AddDependency(dep *Package)
- func (p *Package) AddFile(f *GoFile)
- func (p *Package) AddImport(ref ImportRef)
- func (p *Package) AddOrGetFile(name, pkgName string) *GoFile
- func (p *Package) AddType(t *Type)
- func (p *Package) AddVar(v VarDecl)
- func (p *Package) DefaultFile(pkgName string) *GoFile
- func (p *Package) FileByName(name string) *GoFile
- func (p *Package) FunctionsByFile() map[string][]*Function
- func (p *Package) HasConst(name string) bool
- func (p *Package) HasImport(path, alias string) bool
- func (p *Package) HasType(name string) bool
- func (p *Package) HasVar(name string) bool
- func (p *Package) RenderFiles() (map[string]string, error)
- func (p *Package) RenderFilesWithMethods() (map[string]string, error)
- func (p *Package) RenderFilesWithOptions(opts RenderOptions, includeFreeFunctions bool) (map[string]string, error)
- func (p *Package) RenderFilesWithPackageOptions(po PackageRenderOptions) (map[string]string, error)
- func (p *Package) WriteFiles(dir string) error
- func (p *Package) WriteFilesWithMethods(dir string) error
- func (p *Package) WriteFilesWithOptions(dir string, opts RenderOptions, includeFreeFunctions bool) error
- func (p *Package) WriteFilesWithPackageOptions(dir string, po PackageRenderOptions) error
- type PackageRenderOptions
- type Pointer
- type PointerOption
- type RenderOptions
- type Slice
- type SliceOption
- type Struct
- type StructBuilder
- type Term
- type Type
- type TypeParam
- type Union
- type VarDecl
Examples ¶
Constants ¶
const DefaultFileName = "types_gen.go"
Variables ¶
This section is empty.
Functions ¶
func RenderFunctionStub ¶
RenderFunctionStub renders a free-standing function declaration signature with an empty body.
func RenderMethodStub ¶
RenderMethodStub renders a method declaration signature with an empty body. It expects a parsed *ast.FuncDecl.
func RenderTypeBodyFromSpec ¶
RenderTypeBodyFromSpec renders the body of a type specification, excluding the leading "type <Name>" prefix.
Types ¶
type Alias ¶
Alias represents an explicit type alias (optionally generic). Example: type IDs[T any] = []T → &Alias{Name:"IDs", TypeParams:[]TypeParam{{Name:"T", Constraint:&Basic{Name:"any"}}}, Target:&Slice{Elem:&Named{Name:"T"}}} Not produced by FromReflect but supported by ToAST.
func NewAlias ¶
func NewAlias(opts ...AliasOption) (*Alias, error)
type AliasOption ¶
Alias
func WithAliasName ¶
func WithAliasName(nm string) AliasOption
func WithAliasPkg ¶
func WithAliasPkg(p string) AliasOption
func WithAliasTarget ¶
func WithAliasTarget(t Node) AliasOption
type Array ¶
Array represents an array type. Example: [3]string → &Array{Len:3, Elem:&Basic{Name:"string"}}
func NewArray ¶
func NewArray(opts ...ArrayOption) (*Array, error)
type ArrayOption ¶
Array
func WithArrayElem ¶
func WithArrayElem(t Node) ArrayOption
func WithArrayLen ¶
func WithArrayLen(n int) ArrayOption
type Basic ¶
Basic represents built-in or package-local basic types. Example: int → &Basic{Name:"int"}
func NewBasic ¶
func NewBasic(opts ...BasicOption) (*Basic, error)
type BasicOption ¶
Basic
func WithBasicName ¶
func WithBasicName(n string) BasicOption
func WithBasicPkg ¶
func WithBasicPkg(p string) BasicOption
type Chan ¶
Chan represents a channel type. Example: chan int → &Chan{Dir:int(token.SEND|token.RECV), Elem:&Basic{Name:"int"}} Dir is compatible with ast.ChanDir.
func NewChan ¶
func NewChan(opts ...ChanOption) (*Chan, error)
type ChanOption ¶
Chan
func WithChanDir ¶
func WithChanDir(dir int) ChanOption
func WithChanElem ¶
func WithChanElem(t Node) ChanOption
type ConstDecl ¶
type ConstDecl struct {
Name string
Type ast.Expr // optional
Value ast.Expr // optional
Imports map[string]ImportRef
}
ConstDecl represents a single constant declaration. Type and/or Value may be nil; at least one should be provided to produce a meaningful declaration.
type Field ¶
type Field struct {
Name string // empty for embedded fields
Type Node
Tag string // raw, without backticks
Embedded bool
}
Field describes a struct field or function parameter/result.
Field is a helper value; it is not a Node.
func NewField ¶
func NewField(opts ...FieldOption) (Field, error)
type FieldOption ¶
Field options and constructor
func WithEmbedded ¶
func WithEmbedded(embedded bool) FieldOption
func WithFieldName ¶
func WithFieldName(name string) FieldOption
func WithFieldTag ¶
func WithFieldTag(tag string) FieldOption
func WithFieldType ¶
func WithFieldType(t Node) FieldOption
type Func ¶
Func represents a function type. Example: func(x int) (string, error) → &Func{Params:[]Field{{Type:&Basic{Name:"int"}}}, Results:[]Field{{Type:&Basic{Name:"string"}},{Type:&Basic{Name:"error"}}}}
func MakeFunc ¶
func MakeFunc(opts ...FuncOption) (*Func, error)
MakeFunc constructs a function signature using functional options.
type FuncBuilder ¶
type FuncBuilder struct{ F *Func }
FuncBuilder builds Func nodes fluently.
func (*FuncBuilder) AddParam ¶
func (b *FuncBuilder) AddParam(typ Node) *FuncBuilder
AddParam appends a parameter of type typ.
func (*FuncBuilder) AddResult ¶
func (b *FuncBuilder) AddResult(typ Node) *FuncBuilder
AddResult appends a result of type typ.
func (*FuncBuilder) Build ¶
func (b *FuncBuilder) Build() *Func
Build returns the underlying Func node.
func (*FuncBuilder) SetVariadic ¶
func (b *FuncBuilder) SetVariadic(v bool) *FuncBuilder
SetVariadic marks the function as variadic.
type FuncOption ¶
Func options and constructor
func WithParam ¶
func WithParam(t Node) FuncOption
func WithResult ¶
func WithResult(t Node) FuncOption
func WithVariadic ¶
func WithVariadic(v bool) FuncOption
type Function ¶
type Function struct {
Name string
Type Func
Decl *ast.FuncDecl
File string // optional source filename (base)
}
Function describes a free-standing function in a package.
type GoFile ¶
type GoFile struct {
// Name is an optional logical filename (e.g., types_gen.go).
Name string
PkgName string
Imports map[string]ImportRef // key: path+" "+alias
Types []*Type
Consts []ConstDecl
Vars []VarDecl
// Embeds maps variable name -> embedded FS instance for variables
// declared with //go:embed directives in this file.
Embeds map[string]*embed.FS
}
GoFile represents a single Go source file composed of types and the imports needed to render them under stable, per-file aliasing.
func (*GoFile) AddEmbed ¶
AddEmbed registers an embedded FS instance under the provided variable name.
func (*GoFile) AddSideEffectImport ¶
AddSideEffectImport adds an import with alias '_' for side effects.
func (*GoFile) HasImport ¶
HasImport reports if the file has an import with the provided path/alias.
func (*GoFile) HasType ¶
HasType reports whether a type with the given name is queued for rendering.
func (*GoFile) Render ¶
Render emits a formatted Go source file for the accumulated types and imports.
Example ¶
ExampleGoFile_Render demonstrates rendering a simple file containing a type declaration using AST-based emission.
expr, _ := parser.ParseExpr("struct{ ID int }")
t := &Type{Name: "T", TypeSpec: &ast.TypeSpec{Name: ast.NewIdent("T"), Type: expr}}
gf := &GoFile{PkgName: "example", Types: []*Type{t}}
src, _ := gf.Render()
fmt.Println(strings.HasPrefix(src, "package example"))
Output: true
func (*GoFile) RenderWithMethods ¶
RenderWithMethods is a compatibility helper that currently renders the file including methods; it forwards to Render since Render already includes method stubs after type declarations.
func (*GoFile) RenderWithOptions ¶
func (f *GoFile) RenderWithOptions(opts RenderOptions) (string, error)
RenderWithOptions renders the file with configurable behaviour.
type ImportEntry ¶
ImportEntry represents a single import path and alias.
type ImportRef ¶
ImportRef represents a single import needed by a synthetic type. Path is the fully-qualified import path. Alias is optional; when empty, callers are expected to rely on the package's default name.
type ImportSet ¶
type ImportSet struct {
CurrentPkg string
// contains filtered or unexported fields
}
ImportSet tracks import paths and their assigned aliases in a deterministic way. It is used by AST generation to qualify identifiers and later by the syntetic bridge when emitting import specs.
func NewImportSet ¶
NewImportSet creates a new ImportSet for the provided current package path.
func (*ImportSet) AliasFor ¶
AliasFor returns a deterministic alias for the supplied import path. The result is cached for subsequent calls.
func (*ImportSet) Entries ¶
func (s *ImportSet) Entries() []ImportEntry
Entries returns a deterministically sorted slice of imports.
type Interface ¶
type Interface struct {
Methods []Method // exported only, flattened per reflect
}
Interface represents an interface type with named methods. Example: interface{ Read([]byte) (int,error) }
func (*Interface) AddMethod ¶
AddMethod appends a method if a method with the same name does not already exist.
type InterfaceBuilder ¶
type InterfaceBuilder struct{ I *Interface }
InterfaceBuilder builds Interface nodes fluently.
func NewInterface ¶
func NewInterface() *InterfaceBuilder
NewInterface returns a builder for an interface node.
func (*InterfaceBuilder) AddMethod ¶
func (b *InterfaceBuilder) AddMethod(name string, fn Func) *InterfaceBuilder
AddMethod appends a method if not present.
func (*InterfaceBuilder) AddMethodSig ¶
func (b *InterfaceBuilder) AddMethodSig(name string, params []Node, results []Node, variadic bool) *InterfaceBuilder
AddMethodSig is a convenience to append a method using only parameter/result types.
func (*InterfaceBuilder) Node ¶
func (b *InterfaceBuilder) Node() *Interface
Node returns the underlying Interface.
type Kind ¶
type Kind int
Kind represents the specific shape of a Node.
Stable numeric ordering is required for deterministic behaviour. Do not reorder existing values.
type Map ¶
Map represents a map type. Example: map[string]int → &Map{Key:&Basic{Name:"string"}, Elem:&Basic{Name:"int"}}
type Method ¶
Method describes an interface or named type method.
Method is a helper value; it is not a Node.
func NewMethod ¶
func NewMethod(opts ...MethodOption) (Method, error)
type MethodOption ¶
Method options and constructor
func WithMethodFunc ¶
func WithMethodFunc(fn Func) MethodOption
func WithMethodName ¶
func WithMethodName(name string) MethodOption
type Module ¶
Module models a Go module containing one or more packages. It is intentionally minimal and focused on helper methods for composition and de-duplication.
func (*Module) AddOrGetPackage ¶
AddOrGetPackage returns a package for pkgPath, creating and registering a new one when it does not already exist.
func (*Module) AddPackage ¶
AddPackage registers p under its PkgPath and returns the stored reference. If a package with the same PkgPath exists, it returns the existing one.
func (*Module) HasPackage ¶
HasPackage reports whether a package with the given import path exists.
type Named ¶
type Named struct {
PkgPath string
Name string
Underlying Node // may be nil during cycle resolution
TypeParams []TypeParam
// Methods declared on the named type (value receiver).
Methods []Method
// PtrMethods declared on the pointer to the named type (*T receiver).
PtrMethods []Method
}
Named represents a defined type with a name (optionally generic). Example: type Box[T any] ... → &Named{PkgPath:"example.com/p", Name:"Box", TypeParams:[]TypeParam{{Name:"T", Constraint:&Basic{Name:"any"}}}}
func NewNamed ¶
func NewNamed(opts ...NamedOption) (*Named, error)
func (*Named) AddMethod ¶
AddMethod adds a method to the value receiver if it is not already present.
func (*Named) AddPtrMethod ¶
AddPtrMethod adds a method to the pointer receiver if not present.
type NamedOption ¶
Named
func WithNamedName ¶
func WithNamedName(nm string) NamedOption
func WithNamedPkg ¶
func WithNamedPkg(p string) NamedOption
func WithNamedUnderlying ¶
func WithNamedUnderlying(u Node) NamedOption
type Namespace ¶
type Namespace struct {
// PkgName is the default package name used when rendering if not
// explicitly provided.
PkgName string
// PkgPath is the default package import path for aliasing decisions.
PkgPath string
// Types holds named synthetic types in this namespace.
Types map[string]*Type
// TypesByPkg groups types by their package import path, then by
// type name. This enables multi-package composition and per-package
// file rendering.
TypesByPkg map[string]map[string]*Type
// Imports aggregates all unique imports required by Types. The key
// is path + " " + alias which keeps the de-duplication logic
// consistent with the loader's behaviour.
Imports map[string]ImportRef
// External optionally tracks referenced external package types for
// documentation or higher-level tooling. The key is an import path and
// the value is a list of type names referenced from that package.
External map[string][]string
// Index provides a qualified lookup keyed by "<pkgPath>.<name>" (or
// just name when pkgPath is empty). This avoids collisions across
// packages and provides a stable identity for metadata overlays.
Index map[string]*Type
}
Namespace groups a set of synthetic types along with the aggregated imports required to render them into a single Go source file.
func (*Namespace) AddExternal ¶
AddExternal records usage of a type from another package under pkgPath and merges a default import for that package (if not already present). Alias is optional; pass empty to use the package's default name.
func (*Namespace) AddImport ¶
AddImport adds an import reference to the namespace if it does not already exist. This can be useful when external types are referenced only in method or function stubs attached later.
func (*Namespace) AddType ¶
AddType registers t in the namespace and merges its imports into the namespace-level Imports collection. Imports are de-duplicated by the composite key path + " " + alias.
func (*Namespace) BuildFiles ¶
func (n *Namespace) BuildFiles(opts RenderOptions) (map[string]*GoFile, error)
BuildFiles constructs a GoFile per package import path containing the types that belong to that package. The returned map is keyed by pkgPath. Callers can render each file with Render or RenderWithOptions.
Note: opts currently affects only rendering; it is accepted for future extension and symmetry with GoFile rendering helpers.
func (*Namespace) KeyOf ¶
KeyOf returns a qualified key for the provided type in the form "<pkgPath>.<name>" when a package path is present, otherwise just the type name. It is safe to call with a nil receiver or argument.
func (*Namespace) Render ¶
Render renders using the namespace's default package name. It is a thin wrapper over RenderFile.
func (*Namespace) RenderFile ¶
RenderFile renders all types stored in the namespace into a single Go source file. It emits the package clause using pkgName, followed by an aggregated import block and the type declarations. The result is go/format formatted.
type Node ¶
type Node interface {
Kind() Kind
}
Node is a single type node in the synthetic model graph.
All concrete nodes must be immutable once constructed.
type Package ¶
type Package struct {
// Name is the package name as declared in the source files.
Name string
// PkgPath is the full import path of the package, e.g.
// "example.com/project/pkg".
PkgPath string
// Types lists all discovered type declarations in the package.
Types []*Type
// Imports lists unique imports used across the package.
Imports []ImportRef
// Files holds optional file-level groupings when callers organise
// declarations per file.
Files []*GoFile
Consts []ConstDecl
Vars []VarDecl
// Dependencies lists non-standard-library packages imported by this
// package that were recursively loaded via LoadPackageDeep.
Dependencies []*Package
// Funcs holds free-standing functions declared in this package.
Funcs []*Function
}
Package represents a loaded Go package used by the synthetic type utilities. It intentionally models only the minimal shape required by the tests and loader in this package.
func (*Package) AddConst ¶
AddConst adds a package-level constant if not already present by name and merges its imports.
func (*Package) AddDependency ¶
AddDependency inserts a dependency if not already present (by PkgPath).
func (*Package) AddOrGetFile ¶
AddOrGetFile returns a file with the given name, creating and adding a new file with provided package name when missing.
func (*Package) AddVar ¶
AddVar adds a package-level variable if not already present by name and merges its imports.
func (*Package) DefaultFile ¶
DefaultFile returns (and creates if missing) a default file for this package.
func (*Package) FileByName ¶
FileByName returns the first file with the given Name, or nil if none.
func (*Package) FunctionsByFile ¶
FunctionsByFile groups functions by source filename when available.
func (*Package) HasConst ¶
HasConst reports whether a const with the given name exists in the package.
func (*Package) RenderFiles ¶
RenderFiles returns a map of filename -> source using each GoFile's Render().
func (*Package) RenderFilesWithMethods ¶
RenderFilesWithMethods renders each file using Render() (which includes method stubs) and appends free-standing function stubs per file.
func (*Package) RenderFilesWithOptions ¶
func (p *Package) RenderFilesWithOptions(opts RenderOptions, includeFreeFunctions bool) (map[string]string, error)
RenderFilesWithOptions renders files using per-file RenderWithOptions and optionally appends free-standing function stubs.
func (*Package) RenderFilesWithPackageOptions ¶
func (p *Package) RenderFilesWithPackageOptions(po PackageRenderOptions) (map[string]string, error)
RenderFilesWithPackageOptions renders all files using the provided package options. File-specific overrides take precedence over the global Render options. When IncludeFreeFunctions is true, free-standing functions are appended per file.
Example ¶
ExamplePackage_RenderFilesWithPackageOptions shows how to render files with interleaved method stubs at the package level.
// Build a minimal method AST for demonstration.
fdSrc := "package p\nfunc (a A) M(){}\n"
f, _ := parser.ParseFile(token.NewFileSet(), "m.go", fdSrc, 0)
fd := f.Decls[0].(*ast.FuncDecl)
a := &Type{Name: "A", TypeSpec: &ast.TypeSpec{Name: ast.NewIdent("A"), Type: ast.NewIdent("struct{}")}, MethodsAST: []*ast.FuncDecl{fd}}
pkg := &Package{Name: "p", Files: []*GoFile{{Name: "a.go", PkgName: "p", Types: []*Type{a}}}}
out, _ := pkg.RenderFilesWithPackageOptions(PackageRenderOptions{Render: RenderOptions{InterleaveMethodStubs: true}})
fmt.Println(strings.Contains(out["a.go"], "func (a A) M()"))
Output: true
func (*Package) WriteFiles ¶
WriteFiles writes rendered files to the specified directory using the default rendering (types with generics + method stubs). Directories are created as needed.
func (*Package) WriteFilesWithMethods ¶
WriteFilesWithMethods writes rendered files (including method stubs and free function stubs) to the specified directory.
func (*Package) WriteFilesWithOptions ¶
func (p *Package) WriteFilesWithOptions(dir string, opts RenderOptions, includeFreeFunctions bool) error
WriteFilesWithOptions writes files rendered with the given options and flag controlling whether free functions are included.
func (*Package) WriteFilesWithPackageOptions ¶
func (p *Package) WriteFilesWithPackageOptions(dir string, po PackageRenderOptions) error
WriteFilesWithPackageOptions writes files using package-wide rendering options, including file-specific overrides.
type PackageRenderOptions ¶
type PackageRenderOptions struct {
Render RenderOptions
IncludeFreeFunctions bool
FileOptions map[string]RenderOptions // filename -> options
}
PackageRenderOptions controls package-level rendering across all files. FileOptions, when provided, overrides the global Render options for specific filenames.
type Pointer ¶
type Pointer struct {
Elem Node
}
Pointer represents a pointer type. Example: *T → &Pointer{Elem:&Named{Name:"T"}}
func NewPointer ¶
func NewPointer(opts ...PointerOption) (*Pointer, error)
type RenderOptions ¶
type RenderOptions struct {
// InterleaveMethodStubs places method stubs immediately after each
// corresponding type declaration instead of batching at the end.
InterleaveMethodStubs bool
// ImportAliases optionally overrides the alias used when referring to
// external packages by import path. Keys are full import paths, values
// are aliases to use (e.g., "github.com/acme/foo" -> "fooalias"). When
// provided, both import declarations and selector emission from model Nodes
// will prefer these aliases.
ImportAliases map[string]string
}
RenderOptions controls rendering behaviour.
type Slice ¶
type Slice struct {
Elem Node
}
Slice represents a slice type. Example: []int → &Slice{Elem:&Basic{Name:"int"}}
func NewSlice ¶
func NewSlice(opts ...SliceOption) (*Slice, error)
type Struct ¶
type Struct struct {
Fields []Field // declaration order preserved
}
Struct represents a struct type. Example: struct{ ID int; Name string }
func (*Struct) AddField ¶
AddField appends a field if a non-embedded field with the same name does not already exist. Embedded fields are not de-duplicated.
type StructBuilder ¶
type StructBuilder struct{ S *Struct }
StructBuilder builds Struct nodes fluently.
func (*StructBuilder) AddField ¶
func (b *StructBuilder) AddField(name string, typ Node, tag string, embedded bool) *StructBuilder
AddField appends a field to the struct. Duplicate named non-embedded fields are ignored (see Struct.AddField).
func (*StructBuilder) Node ¶
func (b *StructBuilder) Node() *Struct
Node returns the underlying Struct.
type Term ¶
Term represents a single element in a union constraint; Approx indicates '~'. Example: ~int → Term{Type:&Basic{Name:"int"}, Approx:true}
type Type ¶
type Type struct {
Name string // logical type name
PkgPath string // logical package path
// ReflectType is an optional reference to an existing compiled type
// from a runtime/registry layer.
ReflectType reflect.Type
// LinkedinType is deprecated; use ReflectType. Kept for one cycle of
// backward compatibility.
LinkedinType reflect.Type
// TypeSpec is the AST source of truth for the type.
TypeSpec *ast.TypeSpec
// Imports lists imports needed for this type's declaration,
// keyed by alias ("" for default).
Imports map[string]*ImportRef
// MethodsAST holds parsed method declarations with a value receiver of this type.
MethodsAST []*ast.FuncDecl
// PtrMethodsAST holds parsed method declarations with a pointer receiver of this type.
PtrMethodsAST []*ast.FuncDecl
// Methods holds parsed method signatures attached to this type. Value
// contains methods with a value receiver; Pointer contains methods with a
// pointer receiver. This mirrors the AST lists and provides a model-level
// view for programmatic access.
Methods MethodSet
// TypeParams declares generic type parameters for this type declaration.
TypeParams []TypeParam
// contains filtered or unexported fields
}
Type is a synthetic/codegen description of a Go type.
func (*Type) Body ¶
Body returns the Go syntax fragment that forms the right-hand side of the type declaration. The result is cached internally.
func (*Type) MethodStubs ¶
MethodStubs returns rendered stubs for value and pointer receiver methods.
func (*Type) ToGenDecl ¶
ToGenDecl creates a full type declaration (GenDecl) for this Type including its type parameters.
Example (Generics) ¶
ExampleType_ToGenDecl_generics shows how a Type with TypeParams and an alias render via ToGenDecl.
// type Box[T any] struct{ V T }
box := &Type{
Name: "Box",
PkgPath: "example.com/p",
TypeParams: []TypeParam{{Name: "T", Constraint: &Basic{Name: "any"}}},
TypeSpec: &ast.TypeSpec{
Name: ast.NewIdent("Box"),
Type: &ast.StructType{Fields: &ast.FieldList{List: []*ast.Field{{Names: []*ast.Ident{ast.NewIdent("V")}, Type: ast.NewIdent("T")}}}},
},
}
// type IDs[T any] = []T
alias := &Type{
Name: "IDs",
PkgPath: "example.com/p",
TypeParams: []TypeParam{{Name: "T", Constraint: &Basic{Name: "any"}}},
TypeSpec: &ast.TypeSpec{Name: ast.NewIdent("IDs"), Type: &ast.ArrayType{Elt: ast.NewIdent("T")}, Assign: token.Pos(1)},
}
var buf1, buf2 strings.Builder
_ = printer.Fprint(&buf1, token.NewFileSet(), box.ToGenDecl("example.com/p", nil))
_ = printer.Fprint(&buf2, token.NewFileSet(), alias.ToGenDecl("example.com/p", nil))
fmt.Println(strings.Contains(buf1.String(), "type Box[T any]"))
fmt.Println(strings.Contains(buf2.String(), "type IDs[T any] = []T"))
Output: true true
func (*Type) ToTypeSpec ¶
ToTypeSpec builds a go/ast.TypeSpec for this type and includes generic type parameters (TypeParams) when present. If t.TypeSpec is non-nil it is shallow-copied to preserve the original Type node.
type TypeParam ¶
TypeParam represents a single type parameter with an optional constraint. Constraint is expressed as a Node; for identifiers like "any" or "comparable" it will be a Basic with that name; for interface or union constraints it will reflect the parsed structure best‑effort.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package transform provides a small, composable layer to apply structural rewrites to syntetic/model graphs without polluting the core model or the builders.
|
Package transform provides a small, composable layer to apply structural rewrites to syntetic/model graphs without polluting the core model or the builders. |