codegen

package
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2025 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ASTTypeToSchemaNode

func ASTTypeToSchemaNode(expr ast.Expr, structMap map[string]*StructInfo, currentPkg string, loader *PackageLoader, imports map[string]string) (*ir.Node, error)

ASTTypeToSchemaNode converts an AST type expression to an IR schema node. This is used when we only have AST information (before type resolution).

func DiscoverFiles

func DiscoverFiles(pkgPath string) ([]string, error)

DiscoverFiles finds all .go files in a package directory. This is a convenience function that wraps DiscoverPackages for a single package.

func ExtractComments

func ExtractComments(decl ast.Decl) []string

ExtractComments extracts comments from a declaration. Returns a slice of comment strings with "# " prefix (Tony format).

func ExtractFieldComments

func ExtractFieldComments(field *ast.Field) []string

ExtractFieldComments extracts comments from a field declaration. Returns a slice of comment strings with "# " prefix (Tony format).

func ExtractImports added in v0.0.2

func ExtractImports(file *ast.File) map[string]string

ExtractImports extracts imports from an AST file. Returns a map of package name -> import path.

func FlattenEmbeddedFields added in v0.0.7

func FlattenEmbeddedFields(structs []*StructInfo) error

FlattenEmbeddedFields flattens embedded fields in all structs. It recursively resolves embedded fields and adds their fields to the embedding struct.

func GenerateCode

func GenerateCode(structs []*StructInfo, schemas map[string]*schema.Schema, config *CodegenConfig) (string, error)

GenerateCode generates Go code for ToTony() and FromTony() methods for all structs. Returns formatted Go source code.

func GenerateFromTonyIRMethod added in v0.0.6

func GenerateFromTonyIRMethod(s *StructInfo, sSchema *schema.Schema, currentPkgPath string) (string, error)

GenerateFromTonyIRMethod generates the FromTonyIR method for a struct.

func GenerateFromTonyMethod

func GenerateFromTonyMethod(structInfo *StructInfo) (string, error)

GenerateFromTonyMethod generates a FromTony() method for a struct.

func GenerateSchema

func GenerateSchema(allStructs []*StructInfo, targetStruct *StructInfo, loader *PackageLoader) (*ir.Node, error)

GenerateSchema generates a schema IR node for a specific struct. allStructs: all structs (used to build struct map for resolving references) targetStruct: the struct to generate the schema for (must have schemagen= tag)

The schema has:

  • signature.name: schema name from schemagen= tag
  • define: map of struct definitions

func GenerateToTonyIRMethod added in v0.0.6

func GenerateToTonyIRMethod(s *StructInfo, sSchema *schema.Schema, currentPkgPath string) (string, error)

GenerateToTonyIRMethod generates the ToTonyIR method for a struct.

func GenerateToTonyMethod

func GenerateToTonyMethod(structInfo *StructInfo) (string, error)

GenerateToTonyMethod generates a ToTony() method for a struct.

func GetStructSchemaTag

func GetStructSchemaTag(typ reflect.Type) (*gomap.StructSchema, error)

GetStructSchemaTag uses reflection to get the struct schema tag. This is a helper that wraps gomap.GetStructSchema for use with reflect.Type. Note: This requires the type to be fully resolved (not just AST). For AST-based parsing, use extractStructSchemaTag instead.

func GoTypeToSchemaNode

func GoTypeToSchemaNode(typ reflect.Type, fieldInfo *FieldInfo, structMap map[string]*StructInfo, currentPkg string, currentStructName string, currentSchemaName string, loader *PackageLoader, imports map[string]string) (*ir.Node, error)

GoTypeToSchemaNode converts a Go type to an IR schema node. This is used for generating schema definitions from Go structs.

Type mappings:

  • string → !irtype ""
  • int, int64, float64, etc. → !irtype 1 (number)
  • bool → !irtype true
  • *T → !or [null, T] (nullable)
  • []T → .array(T) (array)
  • struct → object with fields or .schemaName reference

func HasFromTonyMethod

func HasFromTonyMethod(typ reflect.Type) bool

HasFromTonyMethod checks if a type has a FromTony() method.

func HasToTonyMethod

func HasToTonyMethod(typ reflect.Type) bool

HasToTonyMethod checks if a type has a ToTony() method.

func LoadSchema

func LoadSchema(schemaName string, pkgDir string, config *CodegenConfig, cache *SchemaCache, generatedSchemas map[string]*GeneratedSchema) (*schema.Schema, error)

LoadSchema loads a schema by name. It checks: 1. The generatedSchemas map (for schemas just generated in this run) 2. The schemaCache (for already loaded schemas) 3. The filesystem (resolving the path)

func ParseFile

func ParseFile(filename string) (*ast.File, *token.FileSet, error)

ParseFile parses a Go source file and returns its AST.

func ParseStructTag added in v0.0.2

func ParseStructTag(tag string) (map[string]string, error)

ParseStructTag parses a struct tag string (the content inside `...`) into a map. It handles key-value pairs (key=value) and boolean flags (key). It supports quoted values (key="value with spaces"). It handles comma-separated values.

func ParseTonyTag added in v0.0.2

func ParseTonyTag(tagContent string) (map[string]string, error)

ParseTonyTag parses the content of a "tony" struct tag. Example: `tony:"schemagen=person,optional"` -> tagContent is "schemagen=person,optional"

func ResolveFieldTypes

func ResolveFieldTypes(structs []*StructInfo, pkgDir string, pkgName string) error

ResolveFieldTypes resolves reflect.Type for all fields in the given structs. Uses AST analysis to resolve types to reflect.Type.

func ResolveSchemaPath

func ResolveSchemaPath(schemaName string, pkgDir string, config *CodegenConfig) (string, error)

ResolveSchemaPath resolves the filesystem path for a schema name. schemaName can be: - "person" (local schema) - "models.person" (cross-package reference? handled by registry or convention) - "./schemas/person.tony" (explicit path? usually not in tag)

Search order: 1. If config.SchemaDir is set, look there (preserving package structure?) 2. If config.SchemaDirFlat is set, look there 3. Look in current package directory (pkgDir) 4. Look in schema registry (if configured)

func ResolveType

func ResolveType(expr ast.Expr, pkg *ast.Package) (reflect.Type, error)

ResolveType attempts to resolve an AST type expression to a reflect.Type. This is a helper for when we need reflection-based type information. Returns nil if the type cannot be resolved (e.g., it's a local type that hasn't been loaded).

func WriteSchema

func WriteSchema(schema *ir.Node, outputPath string) error

WriteSchema writes a schema IR node to a .tony file.

func WriteSchemasToSingleFile added in v0.0.2

func WriteSchemasToSingleFile(schemas []*ir.Node, outputPath string) error

WriteSchemasToSingleFile writes multiple schema IR nodes to a single .tony file, separated by "---" document separators.

Types

type CodegenConfig

type CodegenConfig struct {
	// OutputFile is the output file for generated Go code (default: <package>_gen.go)
	OutputFile string

	// SchemaDir is the directory for generated schema files (preserves package structure)
	SchemaDir string

	// SchemaDirFlat is the directory for generated schema files (flat structure)
	SchemaDirFlat string

	// Dir is the directory to scan for Go files (default: current directory)
	Dir string

	// Recursive indicates whether to scan subdirectories recursively
	Recursive bool

	// SchemaRegistry is the path to schema registry for cross-package references (optional)
	SchemaRegistry string

	// Package is the current package being processed
	Package *PackageInfo
}

CodegenConfig holds configuration for code generation

type Cycle

type Cycle []string

Cycle represents a circular dependency path.

func DetectCycles

func DetectCycles(graph *DependencyGraph) ([]Cycle, error)

DetectCycles detects circular dependencies in the graph. Returns a list of cycles found, or nil if no cycles.

type DependencyGraph

type DependencyGraph struct {
	Nodes map[string]*StructInfo
	Edges map[string][]string // Adjacency list: structName -> []dependencyNames
}

DependencyGraph represents a graph of struct dependencies.

func BuildDependencyGraph

func BuildDependencyGraph(structs []*StructInfo) (*DependencyGraph, error)

BuildDependencyGraph builds a dependency graph from a list of structs. A dependency exists if struct A has a field of type struct B.

type FieldInfo

type FieldInfo struct {
	// Name is the struct field name
	Name string

	// SchemaFieldName is the field name in the schema (may differ from struct field name)
	// Extracted from `tony:"field=name"` tag, or defaults to Name
	SchemaFieldName string

	// Type is the Go type of the field
	Type reflect.Type

	// ASTType is the AST representation of the field type (for codegen reference)
	ASTType ast.Expr

	// Optional indicates if the field is optional (nullable or can be empty)
	Optional bool

	// Required indicates if the field is required (overrides type-based inference)
	Required bool

	// Omit indicates if the field should be omitted from schema/code generation
	Omit bool

	// Comments contains field-level comments (above the field declaration)
	Comments []string

	// ASTField is the original AST field node (for reference)
	ASTField *ast.Field

	// IsEmbedded indicates if this is an embedded field
	IsEmbedded bool

	// StructTypeName stores the struct type name when Type is a struct type.
	// This is needed because reflect.StructOf creates anonymous types.
	StructTypeName string

	// TypePkgPath stores the package path for named types from other packages
	// (e.g., "github.com/signadot/tony-format/go-tony/format" for format.Format)
	TypePkgPath string

	// TypeName stores the type name for named types from other packages
	// (e.g., "Format" for format.Format)
	TypeName string

	// ImplementsTextMarshaler indicates if the field type implements encoding.TextMarshaler
	ImplementsTextMarshaler bool

	// ImplementsTextUnmarshaler indicates if the field type implements encoding.TextUnmarshaler
	ImplementsTextUnmarshaler bool
}

FieldInfo holds field information extracted from struct definition

type GeneratedSchema

type GeneratedSchema struct {
	Name     string
	FilePath string // Path where it will be/was written
	// We might add the *ir.Node here if we want to skip reloading from disk
	// But schema.Load parses from file, so we might need to write it first or convert IR to Schema
	// For now, let's assume we load from disk after writing, or we need a way to convert IR -> Schema
	// actually, schema.Schema is the parsed representation. ir.Node is the lower level.
	// Converting ir.Node to schema.Schema in memory is possible but might be complex.
	// Simpler to write to file then load, or just track the path.
	IRNode interface{} // Placeholder if we need it
}

GeneratedSchema holds information about a schema that was just generated in memory

type PackageInfo

type PackageInfo struct {
	// Path is the package import path (e.g., "github.com/user/project/models")
	Path string

	// Dir is the directory containing the package
	Dir string

	// Name is the package name (e.g., "models")
	Name string

	// Files contains paths to all .go files in the package
	Files []string
}

PackageInfo holds information about a Go package

func DiscoverPackages

func DiscoverPackages(dir string, recursive bool) ([]*PackageInfo, error)

DiscoverPackages discovers Go packages in the given directory. If recursive is true, it scans subdirectories recursively.

type PackageLoader added in v0.0.2

type PackageLoader struct {
	// contains filtered or unexported fields
}

PackageLoader loads and caches Go packages.

func NewPackageLoader added in v0.0.2

func NewPackageLoader() *PackageLoader

NewPackageLoader creates a new PackageLoader.

func (*PackageLoader) FindASTStructType added in v0.0.2

func (l *PackageLoader) FindASTStructType(pkg *packages.Package, typeName string) (*ast.StructType, error)

ASTToStructType converts a types.Struct to an ast.StructType (simplified). This is useful if we need to inspect the AST, but for now we might just rely on types.Type.

func (*PackageLoader) FindNamedType added in v0.0.2

func (l *PackageLoader) FindNamedType(pkg *packages.Package, typeName string) (*types.TypeName, types.Type, error)

FindNamedType finds a named type definition in a loaded package. It returns the types.TypeName and the underlying types.Type.

func (*PackageLoader) FindStructType added in v0.0.2

func (l *PackageLoader) FindStructType(pkg *packages.Package, typeName string) (*types.TypeName, *types.Struct, error)

FindStructType finds a struct type definition in a loaded package. It returns the types.TypeName and the underlying *types.Struct.

func (*PackageLoader) FindType added in v0.0.2

func (l *PackageLoader) FindType(pkg *packages.Package, typeName string) (types.Object, error)

FindType looks up a type definition in a loaded package.

func (*PackageLoader) LoadPackage added in v0.0.2

func (l *PackageLoader) LoadPackage(importPath string) (*packages.Package, error)

LoadPackage loads a package by its import path.

type SchemaCache

type SchemaCache struct {
	// contains filtered or unexported fields
}

SchemaCache caches loaded schemas to avoid redundant parsing

func NewSchemaCache

func NewSchemaCache() *SchemaCache

NewSchemaCache creates a new schema cache

type SchemaInfo

type SchemaInfo struct {
	// Name is the schema name (from signature.name)
	Name string

	// Schema is the parsed schema object
	Schema *schema.Schema

	// FilePath is the path to the schema file (if loaded from filesystem)
	FilePath string
}

SchemaInfo holds schema metadata for code generation

type StructInfo

type StructInfo struct {
	// Name is the struct type name
	Name string

	// Package is the package name this struct belongs to
	Package string

	// FilePath is the path to the source file containing this struct
	FilePath string

	// Fields contains information about each struct field
	Fields []*FieldInfo

	// StructSchema holds schema tag information (schema= or schemagen=)
	StructSchema *gomap.StructSchema

	// Comments contains struct-level comments (above the type declaration)
	Comments []string

	// ASTNode is the original AST node for this struct (for reference)
	ASTNode ast.Expr

	// Imports maps package names to import paths for the file containing this struct
	Imports map[string]string

	// Type is the Go type of the struct/type (resolved during type resolution)
	Type reflect.Type

	// ImplementsTextMarshaler indicates if the type implements encoding.TextMarshaler
	ImplementsTextMarshaler bool

	// ImplementsTextUnmarshaler indicates if the type implements encoding.TextUnmarshaler
	ImplementsTextUnmarshaler bool
}

StructInfo holds parsed struct information from Go source

func ExtractTypes added in v0.0.7

func ExtractTypes(file *ast.File, filePath string) ([]*StructInfo, error)

ExtractTypes extracts all type declarations with schema tags from an AST file. Returns types with schema= or schemagen= tags.

func TopologicalSort

func TopologicalSort(graph *DependencyGraph) ([]*StructInfo, error)

TopologicalSort returns the structs in dependency order (dependencies first). Returns error if cycles are detected.

type TypeResolver added in v0.0.2

type TypeResolver struct {
	// contains filtered or unexported fields
}

TypeResolver handles type resolution for a package.

Jump to

Keyboard shortcuts

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