codegen

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2025 License: Apache-2.0 Imports: 15 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) (*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 FormatCycleError

func FormatCycleError(cycles []*Cycle) string

FormatCycleError formats a cycle error message for user display.

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 GenerateFromTonyMethod

func GenerateFromTonyMethod(structInfo *StructInfo, s *schema.Schema) (string, error)

GenerateFromTonyMethod generates a FromTony() method for a struct.

func GenerateSchema

func GenerateSchema(allStructs []*StructInfo, targetStruct *StructInfo) (*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 schemadef= tag)

The schema has:

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

func GenerateToTonyMethod

func GenerateToTonyMethod(structInfo *StructInfo, s *schema.Schema) (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) (*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, pkgPath string, config *CodegenConfig, cache *SchemaCache, generatedSchemas map[string]*GeneratedSchema) (*schema.Schema, error)

LoadSchema loads a schema from filesystem or cache. schemaName can be:

  • "person" (local schema, same package)
  • "models.person" (cross-package reference)

It tries to load from:

  1. Cache (if already loaded)
  2. Newly generated schemas (from Phase 2, same package)
  3. Filesystem (relative to package, then module-relative)
  4. Schema registry (if config.SchemaRegistry is set)

func ParseFile

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

ParseFile parses a Go source file and returns its AST.

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, pkgPath string, config *CodegenConfig) (string, error)

ResolveSchemaPath finds the path to a schema file. Tries multiple locations:

  1. Same directory as package (for local schemas)
  2. Schema directory (if config.SchemaDir is set, preserves structure)
  3. Flat schema directory (if config.SchemaDirFlat is set)
  4. Module-relative paths
  5. Schema registry (if config.SchemaRegistry is set)

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 ValidateSchema

func ValidateSchema(s *schema.Schema, schemaName string) error

ValidateSchema validates that a schema has the required structure.

func WriteSchema

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

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

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 struct {
	// Path is the sequence of struct names forming the cycle
	Path []string
}

Cycle represents a circular dependency detected in the graph.

func DetectCycles

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

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

type DependencyGraph

type DependencyGraph struct {
	// Nodes maps struct name to StructInfo
	Nodes map[string]*StructInfo

	// Edges maps struct name to list of struct names it depends on
	Edges map[string][]string

	// ReverseEdges maps struct name to list of struct names that depend on it
	ReverseEdges map[string][]string
}

DependencyGraph represents a directed graph of struct dependencies. An edge A -> B means struct A depends on struct B (A has a field of type B).

func BuildDependencyGraph

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

BuildDependencyGraph builds a dependency graph from a list of structs. Only structs with schemadef= tags are included in the graph (they're the ones we generate schemas for). Dependencies are detected by analyzing field types that reference other structs.

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
}

FieldInfo holds field information extracted from struct definition

type GeneratedSchema

type GeneratedSchema struct {
	Name     string
	IRNode   *ir.Node
	FilePath string
}

GeneratedSchema holds a schema that was just generated (from Phase 2)

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 SchemaCache

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

SchemaCache holds loaded schemas to avoid reloading

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 schemadef=)
	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.StructType
}

StructInfo holds parsed struct information from Go source

func ExtractStructs

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

ExtractStructs extracts all struct type declarations from an AST file. Returns structs with schema= or schemadef= tags.

func TopologicalSort

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

TopologicalSort performs a topological sort on the dependency graph. Returns structs in dependency order (dependencies come before dependents). Returns an error if cycles are detected.

Jump to

Keyboard shortcuts

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