model

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2026 License: Apache-2.0 Imports: 13 Imported by: 1

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

Examples

Constants

View Source
const DefaultFileName = "types_gen.go"

Variables

This section is empty.

Functions

func RenderFunctionStub

func RenderFunctionStub(fd *ast.FuncDecl) string

RenderFunctionStub renders a free-standing function declaration signature with an empty body.

func RenderMethodStub

func RenderMethodStub(fd *ast.FuncDecl) string

RenderMethodStub renders a method declaration signature with an empty body. It expects a parsed *ast.FuncDecl.

func RenderTypeBodyFromSpec

func RenderTypeBodyFromSpec(spec *ast.TypeSpec) string

RenderTypeBodyFromSpec renders the body of a type specification, excluding the leading "type <Name>" prefix.

Types

type Alias

type Alias struct {
	PkgPath    string
	Name       string
	TypeParams []TypeParam
	Target     Node
}

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 AliasType

func AliasType(pkgPath, name string, target Node) *Alias

AliasType creates a type alias node.

func NewAlias

func NewAlias(opts ...AliasOption) (*Alias, error)

func (*Alias) Kind

func (n *Alias) Kind() Kind

Kind returns the Kind of the Alias node.

type AliasOption

type AliasOption func(*Alias) error

Alias

func WithAliasName

func WithAliasName(nm string) AliasOption

func WithAliasPkg

func WithAliasPkg(p string) AliasOption

func WithAliasTarget

func WithAliasTarget(t Node) AliasOption

type Array

type Array struct {
	Len  int
	Elem Node
}

Array represents an array type. Example: [3]string → &Array{Len:3, Elem:&Basic{Name:"string"}}

func ArrayOf

func ArrayOf(length int, elem Node) *Array

ArrayOf creates an array node.

func NewArray

func NewArray(opts ...ArrayOption) (*Array, error)

func (*Array) Kind

func (n *Array) Kind() Kind

Kind returns the Kind of the Array node.

type ArrayOption

type ArrayOption func(*Array) error

Array

func WithArrayElem

func WithArrayElem(t Node) ArrayOption

func WithArrayLen

func WithArrayLen(n int) ArrayOption

type Basic

type Basic struct {
	Name    string
	PkgPath string // empty for builtins
}

Basic represents built-in or package-local basic types. Example: int → &Basic{Name:"int"}

func BasicType

func BasicType(name string) *Basic

BasicType creates a basic/builtin type node.

func NewBasic

func NewBasic(opts ...BasicOption) (*Basic, error)

func (*Basic) Kind

func (n *Basic) Kind() Kind

Kind returns the Kind of the Basic node.

type BasicOption

type BasicOption func(*Basic) error

Basic

func WithBasicName

func WithBasicName(n string) BasicOption

func WithBasicPkg

func WithBasicPkg(p string) BasicOption

type Chan

type Chan struct {
	Dir  int
	Elem Node
}

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 ChanOf

func ChanOf(dir int, elem Node) *Chan

ChanOf creates a channel node. Dir is compatible with ast.ChanDir.

func NewChan

func NewChan(opts ...ChanOption) (*Chan, error)

func (*Chan) Kind

func (n *Chan) Kind() Kind

Kind returns the Kind of the Chan node.

type ChanOption

type ChanOption func(*Chan) error

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

type FieldOption func(*Field) error

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

type Func struct {
	Params     []Field
	Results    []Field
	Variadic   bool
	TypeParams []TypeParam
}

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.

func (*Func) Kind

func (n *Func) Kind() Kind

Kind returns the Kind of the Func node.

type FuncBuilder

type FuncBuilder struct{ F *Func }

FuncBuilder builds Func nodes fluently.

func NewFunc

func NewFunc() *FuncBuilder

NewFunc returns a builder for a function signature node.

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

type FuncOption func(*Func) error

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) AddConst

func (f *GoFile) AddConst(c ConstDecl)

AddConst appends a const declaration and merges its imports.

func (*GoFile) AddEmbed

func (f *GoFile) AddEmbed(varName string, fsinst *embed.FS)

AddEmbed registers an embedded FS instance under the provided variable name.

func (*GoFile) AddImport

func (f *GoFile) AddImport(ref ImportRef)

AddImport inserts an import reference if it does not already exist.

func (*GoFile) AddSideEffectImport

func (f *GoFile) AddSideEffectImport(path string)

AddSideEffectImport adds an import with alias '_' for side effects.

func (*GoFile) AddType

func (f *GoFile) AddType(t *Type)

AddType appends t to the file and merges its imports.

func (*GoFile) AddVar

func (f *GoFile) AddVar(v VarDecl)

AddVar appends a var declaration and merges its imports.

func (*GoFile) HasConst

func (f *GoFile) HasConst(name string) bool

HasConst reports whether a const with the given name is present.

func (*GoFile) HasEmbed

func (f *GoFile) HasEmbed(varName string) bool

HasEmbed reports whether an embedded FS instance exists for varName.

func (*GoFile) HasImport

func (f *GoFile) HasImport(path, alias string) bool

HasImport reports if the file has an import with the provided path/alias.

func (*GoFile) HasType

func (f *GoFile) HasType(name string) bool

HasType reports whether a type with the given name is queued for rendering.

func (*GoFile) HasVar

func (f *GoFile) HasVar(name string) bool

HasVar reports whether a var with the given name is present.

func (*GoFile) Render

func (f *GoFile) Render() (string, error)

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

func (f *GoFile) RenderWithMethods() (string, error)

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

type ImportEntry struct {
	Alias string
	Path  string
}

ImportEntry represents a single import path and alias.

type ImportRef

type ImportRef struct {
	Path  string
	Alias string
}

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.

func (ImportRef) Key

func (r ImportRef) Key() string

Key returns a deterministic key combining path and alias used for deduplication across collections.

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

func NewImportSet(currentPkg string) *ImportSet

NewImportSet creates a new ImportSet for the provided current package path.

func (*ImportSet) AliasFor

func (s *ImportSet) AliasFor(pkgPath string) string

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.

func (*ImportSet) QualIdent

func (s *ImportSet) QualIdent(pkgPath, ident string) ast.Expr

QualIdent returns an AST expression representing ident qualified with the import alias for pkgPath when needed.

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

func (n *Interface) AddMethod(m Method)

AddMethod appends a method if a method with the same name does not already exist.

func (*Interface) HasMethod

func (n *Interface) HasMethod(name string) bool

HasMethod reports whether a method with the given name exists.

func (*Interface) Kind

func (n *Interface) Kind() Kind

Kind returns the Kind of the Interface node.

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.

const (
	KindUnknown Kind = iota
	KindBasic
	KindNamed
	KindAlias
	KindPointer
	KindSlice
	KindArray
	KindMap
	KindChan
	KindFunc
	KindInterface
	KindStruct
	KindUnion
)

type Map

type Map struct {
	Key  Node
	Elem Node
}

Map represents a map type. Example: map[string]int → &Map{Key:&Basic{Name:"string"}, Elem:&Basic{Name:"int"}}

func MapOf

func MapOf(key, elem Node) *Map

MapOf creates a map node.

func NewMap

func NewMap(opts ...MapOption) (*Map, error)

func (*Map) Kind

func (n *Map) Kind() Kind

Kind returns the Kind of the Map node.

type MapOption

type MapOption func(*Map) error

Map

func WithMapElem

func WithMapElem(v Node) MapOption

func WithMapKey

func WithMapKey(k Node) MapOption

type Method

type Method struct {
	Name string
	Type Func
}

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

type MethodOption func(*Method) error

Method options and constructor

func WithMethodFunc

func WithMethodFunc(fn Func) MethodOption

func WithMethodName

func WithMethodName(name string) MethodOption

type MethodSet

type MethodSet struct {
	Value   []Method
	Pointer []Method
}

MethodSet groups value and pointer receiver methods for a named type.

type Module

type Module struct {
	Path     string
	Packages map[string]*Package // key: package import path
}

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

func (m *Module) AddOrGetPackage(pkgPath string) *Package

AddOrGetPackage returns a package for pkgPath, creating and registering a new one when it does not already exist.

func (*Module) AddPackage

func (m *Module) AddPackage(p *Package) *Package

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

func (m *Module) HasPackage(pkgPath string) bool

HasPackage reports whether a package with the given import path exists.

func (*Module) Package

func (m *Module) Package(pkgPath string) *Package

Package returns the package by import path if present, otherwise nil.

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 NamedType

func NamedType(pkgPath, name string, underlying Node) *Named

NamedType creates a named type node with optional underlying node.

func NewNamed

func NewNamed(opts ...NamedOption) (*Named, error)

func (*Named) AddMethod

func (n *Named) AddMethod(m Method)

AddMethod adds a method to the value receiver if it is not already present.

func (*Named) AddPtrMethod

func (n *Named) AddPtrMethod(m Method)

AddPtrMethod adds a method to the pointer receiver if not present.

func (*Named) HasMethod

func (n *Named) HasMethod(name string, ptr bool) bool

HasMethod reports whether a method with the given name exists on the value receiver when ptr is false, or the pointer receiver when ptr is true.

func (*Named) Kind

func (n *Named) Kind() Kind

Kind returns the Kind of the Named node.

type NamedOption

type NamedOption func(*Named) error

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

func (n *Namespace) AddExternal(pkgPath, typeName, alias string)

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

func (n *Namespace) AddImport(ref ImportRef)

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

func (n *Namespace) AddType(t *Type)

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) HasImport

func (n *Namespace) HasImport(path, alias string) bool

HasImport reports whether an import with the given path/alias exists.

func (*Namespace) HasType

func (n *Namespace) HasType(name string) bool

HasType reports whether a named type exists in the namespace.

func (*Namespace) KeyOf

func (n *Namespace) KeyOf(t *Type) string

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

func (n *Namespace) Render() (string, error)

Render renders using the namespace's default package name. It is a thin wrapper over RenderFile.

func (*Namespace) RenderFile

func (n *Namespace) RenderFile(pkgName string) (string, error)

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

func (p *Package) AddConst(c ConstDecl)

AddConst adds a package-level constant if not already present by name and merges its imports.

func (*Package) AddDependency

func (p *Package) AddDependency(dep *Package)

AddDependency inserts a dependency if not already present (by PkgPath).

func (*Package) AddFile

func (p *Package) AddFile(f *GoFile)

AddFile appends a GoFile to the package and merges its imports.

func (*Package) AddImport

func (p *Package) AddImport(ref ImportRef)

AddImport inserts an import reference if it is not already present.

func (*Package) AddOrGetFile

func (p *Package) AddOrGetFile(name, pkgName string) *GoFile

AddOrGetFile returns a file with the given name, creating and adding a new file with provided package name when missing.

func (*Package) AddType

func (p *Package) AddType(t *Type)

AddType appends a type to the package and merges its imports.

func (*Package) AddVar

func (p *Package) AddVar(v VarDecl)

AddVar adds a package-level variable if not already present by name and merges its imports.

func (*Package) DefaultFile

func (p *Package) DefaultFile(pkgName string) *GoFile

DefaultFile returns (and creates if missing) a default file for this package.

func (*Package) FileByName

func (p *Package) FileByName(name string) *GoFile

FileByName returns the first file with the given Name, or nil if none.

func (*Package) FunctionsByFile

func (p *Package) FunctionsByFile() map[string][]*Function

FunctionsByFile groups functions by source filename when available.

func (*Package) HasConst

func (p *Package) HasConst(name string) bool

HasConst reports whether a const with the given name exists in the package.

func (*Package) HasImport

func (p *Package) HasImport(path, alias string) bool

HasImport reports whether an import with the given path/alias exists.

func (*Package) HasType

func (p *Package) HasType(name string) bool

HasType reports whether the package contains a type with the given name.

func (*Package) HasVar

func (p *Package) HasVar(name string) bool

HasVar reports whether a var with the given name exists in the package.

func (*Package) RenderFiles

func (p *Package) RenderFiles() (map[string]string, error)

RenderFiles returns a map of filename -> source using each GoFile's Render().

func (*Package) RenderFilesWithMethods

func (p *Package) RenderFilesWithMethods() (map[string]string, error)

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

func (p *Package) WriteFiles(dir string) error

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

func (p *Package) WriteFilesWithMethods(dir string) error

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)

func PointerTo

func PointerTo(elem Node) *Pointer

PointerTo creates a pointer node.

func (*Pointer) Kind

func (n *Pointer) Kind() Kind

Kind returns the Kind of the Pointer node.

type PointerOption

type PointerOption func(*Pointer) error

Pointer

func WithElem

func WithElem(t Node) PointerOption

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)

func SliceOf

func SliceOf(elem Node) *Slice

SliceOf creates a slice node.

func (*Slice) Kind

func (n *Slice) Kind() Kind

Kind returns the Kind of the Slice node.

type SliceOption

type SliceOption func(*Slice) error

Slice

func WithSliceElem

func WithSliceElem(t Node) SliceOption

type Struct

type Struct struct {
	Fields []Field // declaration order preserved
}

Struct represents a struct type. Example: struct{ ID int; Name string }

func (*Struct) AddField

func (n *Struct) AddField(f Field)

AddField appends a field if a non-embedded field with the same name does not already exist. Embedded fields are not de-duplicated.

func (*Struct) HasField

func (n *Struct) HasField(name string) bool

HasField reports whether a field with the given name exists. Only named (non-embedded) fields are considered.

func (*Struct) Kind

func (n *Struct) Kind() Kind

Kind returns the Kind of the Struct node.

type StructBuilder

type StructBuilder struct{ S *Struct }

StructBuilder builds Struct nodes fluently.

func NewStruct

func NewStruct() *StructBuilder

NewStruct returns a builder for a struct node.

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

type Term struct {
	Type   Node
	Approx bool
}

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

func (t *Type) Body() string

Body returns the Go syntax fragment that forms the right-hand side of the type declaration. The result is cached internally.

func (*Type) MethodStubs

func (t *Type) MethodStubs() []string

MethodStubs returns rendered stubs for value and pointer receiver methods.

func (*Type) ToGenDecl

func (t *Type) ToGenDecl(currentPkg string, aliases map[string]string) *ast.GenDecl

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

func (t *Type) ToTypeSpec(currentPkg string, aliases map[string]string) *ast.TypeSpec

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

type TypeParam struct {
	Name       string
	Constraint Node // may be nil
}

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.

type Union

type Union struct {
	Terms []Term
}

Union represents a generic type union constraint (e.g. ~int | ~string). Example: ~int | string → &Union{Terms: []Term{{Type:&Basic{Name:"int"}, Approx:true}, {Type:&Basic{Name:"string"}}}}

func (*Union) Kind

func (n *Union) Kind() Kind

Kind returns the Kind of the Union node.

type VarDecl

type VarDecl struct {
	Name    string
	Type    ast.Expr // optional
	Value   ast.Expr // optional
	Imports map[string]ImportRef
}

VarDecl represents a single variable declaration.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL