Documentation
¶
Index ¶
- func ASTTypeToSchemaNode(expr ast.Expr, structMap map[string]*StructInfo, currentPkg string, ...) (*ir.Node, error)
- func DiscoverFiles(pkgPath string) ([]string, error)
- func ExtractComments(decl ast.Decl) []string
- func ExtractFieldComments(field *ast.Field) []string
- func ExtractImports(file *ast.File) map[string]string
- func FlattenEmbeddedFields(structs []*StructInfo) error
- func GenerateCode(structs []*StructInfo, schemas map[string]*schema.Schema, ...) (string, error)
- func GenerateFromTonyIRMethod(s *StructInfo, sSchema *schema.Schema, currentPkgPath string) (string, error)
- func GenerateFromTonyMethod(structInfo *StructInfo) (string, error)
- func GenerateSchema(allStructs []*StructInfo, targetStruct *StructInfo, loader *PackageLoader) (*ir.Node, error)
- func GenerateToTonyIRMethod(s *StructInfo, sSchema *schema.Schema, currentPkgPath string) (string, error)
- func GenerateToTonyMethod(structInfo *StructInfo) (string, error)
- func GetStructSchemaTag(typ reflect.Type) (*gomap.StructSchema, error)
- func GoTypeToSchemaNode(typ reflect.Type, fieldInfo *FieldInfo, structMap map[string]*StructInfo, ...) (*ir.Node, error)
- func HasFromTonyMethod(typ reflect.Type) bool
- func HasToTonyMethod(typ reflect.Type) bool
- func LoadSchema(schemaName string, pkgDir string, config *CodegenConfig, cache *SchemaCache, ...) (*schema.Schema, error)
- func ParseFile(filename string) (*ast.File, *token.FileSet, error)
- func ParseStructTag(tag string) (map[string]string, error)
- func ParseTonyTag(tagContent string) (map[string]string, error)
- func ResolveFieldTypes(structs []*StructInfo, pkgDir string, pkgName string) error
- func ResolveSchemaPath(schemaName string, pkgDir string, config *CodegenConfig) (string, error)
- func ResolveType(expr ast.Expr, pkg *ast.Package) (reflect.Type, error)
- func WriteSchema(schema *ir.Node, outputPath string) error
- func WriteSchemasToSingleFile(schemas []*ir.Node, outputPath string) error
- type CodegenConfig
- type Cycle
- type DependencyGraph
- type FieldInfo
- type GeneratedSchema
- type PackageInfo
- type PackageLoader
- func (l *PackageLoader) FindASTStructType(pkg *packages.Package, typeName string) (*ast.StructType, error)
- func (l *PackageLoader) FindNamedType(pkg *packages.Package, typeName string) (*types.TypeName, types.Type, error)
- func (l *PackageLoader) FindStructType(pkg *packages.Package, typeName string) (*types.TypeName, *types.Struct, error)
- func (l *PackageLoader) FindType(pkg *packages.Package, typeName string) (types.Object, error)
- func (l *PackageLoader) LoadPackage(importPath string) (*packages.Package, error)
- type SchemaCache
- type SchemaInfo
- type StructInfo
- type TypeResolver
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 ¶
DiscoverFiles finds all .go files in a package directory. This is a convenience function that wraps DiscoverPackages for a single package.
func ExtractComments ¶
ExtractComments extracts comments from a declaration. Returns a slice of comment strings with "# " prefix (Tony format).
func ExtractFieldComments ¶
ExtractFieldComments extracts comments from a field declaration. Returns a slice of comment strings with "# " prefix (Tony format).
func ExtractImports ¶ added in v0.0.2
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 ¶
HasFromTonyMethod checks if a type has a FromTony() method.
func HasToTonyMethod ¶
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 ParseStructTag ¶ added in v0.0.2
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
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 ¶
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 ¶
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 []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
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
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.