Documentation
¶
Overview ¶
Package golang provides Go code generation from AILANG Core AST.
This package implements Phase 1 (M-GAME-A) of the game support enablement: - ADT → Go struct generation with discriminator pattern - Pure function → Go function generation - Export keyword support
Generated code uses discriminator structs for sum types (not interfaces) to ensure cache-friendly, branch-predictable layouts for game engines.
Code is split across multiple files for maintainability: - codegen.go: Core types, initialization, and main generation loop - codegen_runtime.go: Runtime helper functions (Cons, RecordUpdate, arithmetic) - codegen_decl.go: Declaration generation (functions, variables) - codegen_expr.go: Expression generation (literals, lambdas, applications) - codegen_match.go: Pattern matching generation - codegen_ops.go: Binary/unary operations, records, lists, tuples
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST. This file generates type class dictionary implementations.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
This file contains record-related code generation: - Record literals (typed structs and map[string]interface{}) - Record field access and updates - Helper functions for record type handling
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
Package golang provides Go code generation from AILANG Core AST.
M-CODEGEN-VALUE-TYPES: This file contains type analysis for value vs pointer decisions.
Index ¶
- func ClearDerivedEqTypes()
- func EscapeKeyword(s string) string
- func GenerateEmptyPackage(config PackageConfig) error
- func GenerateEnsuresChecks(contracts []*core.Contract, funcName string) string
- func GeneratePackage(prog *core.Program, config PackageConfig) error
- func GenerateRequiresChecks(contracts []*core.Contract, funcName string) string
- func IsGoKeyword(s string) bool
- func IsLeafRecord(fieldTypes map[string]string) bool
- func IsPointerType(t GoType) bool
- func IsUserDefinedType(goType string) bool
- func SanitizeGoIdentifier(s string) string
- func SuggestPackageName(moduleName string) string
- func ToCamelCase(s string) string
- func ToGoFieldName(s string) string
- func ToGoFuncName(s string, exported bool) string
- func ToGoTypeName(s string) string
- func ToGoVarName(s string) string
- func ToKindConstName(typeName, variantName string) string
- func ToKindTypeName(typeName string) string
- func ToPascalCase(s string) string
- func ToVariantStructName(typeName, variantName string) string
- func ValidatePackageName(name string) error
- func ZeroValue(t GoType) string
- type ADTConstructorInfo
- type ADTGenerator
- func (g *ADTGenerator) GenerateTypeDecl(decl *ast.TypeDecl) ([]byte, error)
- func (g *ADTGenerator) GenerateTypeDecls(decls []*ast.TypeDecl) ([]byte, error)
- func (g *ADTGenerator) GetADTSliceTypes() map[string]bool
- func (g *ADTGenerator) GetValueThreshold() int
- func (g *ADTGenerator) SetValueThreshold(threshold int)
- type AIGenerator
- type BoolMatchChainEntry
- type ContractGenerator
- type DebugGenerator
- type DerivedEqType
- type EffectHandler
- func DefaultAIHandler() EffectHandler
- func DefaultClockHandler() EffectHandler
- func DefaultContractHandler() EffectHandler
- func DefaultDebugHandler() EffectHandler
- func DefaultEnvHandler() EffectHandler
- func DefaultFSHandler() EffectHandler
- func DefaultNetHandler() EffectHandler
- func DefaultRandHandler() EffectHandler
- type EffectsGenerator
- type FuncTypeOverride
- type Generator
- func (g *Generator) AnalyzeRecordType(fieldTypes map[string]string) (TypeCategory, bool)
- func (g *Generator) Generate(prog *core.Program) ([]byte, error)
- func (g *Generator) GenerateDictionaries() ([]byte, error)
- func (g *Generator) GenerateRuntime() ([]byte, error)
- func (g *Generator) GenerateToWriter(prog *core.Program, w io.Writer) error
- func (g *Generator) GetModuleName() string
- func (g *Generator) GetRecordTypeByFields(fieldNames map[string]bool) *RecordTypeInfo
- func (g *Generator) GetValueThreshold() int
- func (g *Generator) GoReprForType(typeName string) (goType string, isPointer bool)
- func (g *Generator) GoTypeStringForType(typeName string) string
- func (g *Generator) IsPointerType(typeName string) bool
- func (g *Generator) IsValueType(typeName string) bool
- func (g *Generator) LookupADTConstructor(typeName, ctorName string) (*ADTConstructorInfo, bool)
- func (g *Generator) LookupADTConstructorByQualifiedName(qualifiedKey string) (*ADTConstructorInfo, bool)
- func (g *Generator) RegisterADTConstructor(typeName, ctorName string, fieldCount int)
- func (g *Generator) RegisterADTConstructorFull(typeName, ctorName string, fieldTypes, fieldNames []string)
- func (g *Generator) RegisterADTConstructorWithTypes(typeName, ctorName string, fieldTypes []string)
- func (g *Generator) RegisterADTSliceType(typeName string)
- func (g *Generator) RegisterADTSliceTypes(types map[string]bool)
- func (g *Generator) RegisterDerivedEqType(typeName string, constructors []string)
- func (g *Generator) RegisterFunctionType(name string, paramTypes []GoType, returnType GoType)
- func (g *Generator) RegisterRecordType(name string, fields []string, fieldTypes map[string]string)
- func (g *Generator) RegisterRecordTypeWithAnalysis(name string, fields []string, fieldTypes map[string]string)
- func (g *Generator) ResetPerModuleState()
- func (g *Generator) SetCoreTypeInfo(cti types.CoreTypeInfo)
- func (g *Generator) SetModuleName(name string)
- func (g *Generator) SetSkipRuntimeHelpers(skip bool)
- func (g *Generator) SetValueThreshold(threshold int)
- func (g *Generator) SetVerifyContracts(enabled bool)
- type GoType
- type HandlerMethod
- type LetBoolMatchEntry
- type PackageConfig
- type Param
- type RecordTypeInfo
- type StringConvKind
- type TypeCategory
- type TypeMapper
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClearDerivedEqTypes ¶
func ClearDerivedEqTypes()
ClearDerivedEqTypes clears the derived Eq types registry. M-CODEGEN-DICTIONARIES M4: Called at start of compilation for fresh state.
func EscapeKeyword ¶
EscapeKeyword adds an underscore suffix if the string is a Go keyword.
func GenerateEmptyPackage ¶
func GenerateEmptyPackage(config PackageConfig) error
GenerateEmptyPackage generates an empty Go package with just the package declaration. Useful for testing package structure.
func GenerateEnsuresChecks ¶
GenerateEnsuresChecks generates Go code for ensures contract checks. M-VERIFY: Called before return in function body generation. Returns the Go code to insert before return.
func GeneratePackage ¶
func GeneratePackage(prog *core.Program, config PackageConfig) error
GeneratePackage generates a complete Go package from a Core program. Creates the output directory and writes all generated files.
func GenerateRequiresChecks ¶
GenerateRequiresChecks generates Go code for requires contract checks. M-VERIFY: Called at the start of function body generation. Returns the Go code to insert at function entry.
func IsGoKeyword ¶
IsGoKeyword returns true if the string is a Go reserved keyword.
func IsLeafRecord ¶
IsLeafRecord checks if all field types are primitives (no nested records, ADTs, or slices). M-CODEGEN-VALUE-TYPES: Leaf records are candidates for value type generation.
Returns true if all fields are primitive types (int64, float64, bool, string). Returns false if any field is:
- A user-defined type (e.g., *Camera, Coord)
- A slice (e.g., []int64, []*NPC)
- A map (e.g., map[string]interface{})
- An interface{}
Note: Uses isPrimitiveGoType from codegen_ops.go.
func IsPointerType ¶
IsPointerType returns true if the Go type should be a pointer. Sum types and recursive types use pointers.
func IsUserDefinedType ¶
IsUserDefinedType returns true if the Go type is a user-defined type (ADT, struct, etc.) rather than a primitive type. Used to determine if slice elements need interface{} wrapping. M-CODEGEN-SUSTAINABILITY: Exported so compile_types.go can use the same implementation.
func SanitizeGoIdentifier ¶
SanitizeGoIdentifier ensures a string is a valid Go identifier. Replaces invalid characters with underscores and ensures it doesn't start with a digit.
func SuggestPackageName ¶
SuggestPackageName suggests a valid Go package name from a module name.
func ToCamelCase ¶
ToCamelCase converts snake_case or PascalCase to camelCase. Used for package-private Go identifiers.
Examples:
"hello_world" -> "helloWorld" "HelloWorld" -> "helloWorld" "hello" -> "hello"
func ToGoFieldName ¶
ToGoFieldName converts an AILANG record field name to a Go struct field name. AILANG uses snake_case, Go uses PascalCase for exported fields.
Examples:
"frame_input" -> "FrameInput" "x" -> "X" "position" -> "Position"
func ToGoFuncName ¶
ToGoFuncName converts an AILANG function name to a Go function name. Exported functions use PascalCase, private functions use camelCase. Also strips $ prefix from type variables.
Examples:
"step", true -> "Step" "step", false -> "step" "init_world", true -> "InitWorld" "init_world", false -> "initWorld"
func ToGoTypeName ¶
ToGoTypeName converts an AILANG type name to a valid Go type name. AILANG types are already PascalCase, so this is mostly a passthrough with validation. Also strips $ prefix from type variables.
Examples:
"Tree" -> "Tree" "FrameInput" -> "FrameInput" "$a" -> "A" (type variable)
func ToGoVarName ¶
ToGoVarName converts an AILANG variable name to a Go variable name. Variables are always package-private (camelCase). Also sanitizes invalid characters like $ (from type variables). Go reserved keywords are escaped with underscore suffix.
Examples:
"world" -> "world" "frame_input" -> "frameInput" "$a" -> "a" (type variable) "$foo_bar" -> "fooBar" "default" -> "default_" (escaped Go keyword)
func ToKindConstName ¶
ToKindConstName generates a kind constant name for sum type discriminators. Avoids double-prefixing if the variant name already starts with the type name.
Examples:
"Tree", "Leaf" -> "TreeKindLeaf" "Tree", "Node" -> "TreeKindNode" "Selection", "SelectionTile" -> "SelectionKindTile" (not "SelectionKindSelectionTile")
func ToKindTypeName ¶
ToKindTypeName generates a kind type name for sum type discriminators.
Examples:
"Tree" -> "TreeKind"
func ToPascalCase ¶
ToPascalCase converts snake_case or camelCase to PascalCase. Used for exported Go identifiers.
Examples:
"hello_world" -> "HelloWorld" "helloWorld" -> "HelloWorld" "hello" -> "Hello" "_private" -> "Private" "_" -> "_" (special case for wildcard)
func ToVariantStructName ¶
ToVariantStructName generates a variant struct name for sum types. Avoids double-prefixing if the variant name already starts with the type name.
Examples:
"Tree", "Leaf" -> "TreeLeaf" "Tree", "Node" -> "TreeNode" "Selection", "SelectionTile" -> "SelectionTile" (not "SelectionSelectionTile") "Selection", "None" -> "SelectionNone"
func ValidatePackageName ¶
ValidatePackageName checks if a string is a valid Go package name.
Types ¶
type ADTConstructorInfo ¶
type ADTConstructorInfo struct {
TypeName string // The ADT type name (e.g., "Selection")
CtorName string // The constructor name (e.g., "SelectionNone")
GoFuncName string // The Go constructor function name (e.g., "NewSelectionSelectionNone")
FieldCount int // Number of fields (0 for nullary constructors)
FieldTypes []string // Go type strings for each field (e.g., ["int64", "float64"])
FieldNames []string // Original field names (e.g., ["x", "y"]) - empty strings for positional fields
}
ADTConstructorInfo holds information about an ADT constructor.
type ADTGenerator ¶
type ADTGenerator struct {
PackageName string
// contains filtered or unexported fields
}
ADTGenerator generates Go code for AILANG algebraic data types. Uses the discriminator struct pattern for sum types (not interfaces).
func NewADTGenerator ¶
func NewADTGenerator(packageName string) *ADTGenerator
NewADTGenerator creates a new ADT code generator.
func (*ADTGenerator) GenerateTypeDecl ¶
func (g *ADTGenerator) GenerateTypeDecl(decl *ast.TypeDecl) ([]byte, error)
GenerateTypeDecl generates Go code for a type declaration.
func (*ADTGenerator) GenerateTypeDecls ¶
func (g *ADTGenerator) GenerateTypeDecls(decls []*ast.TypeDecl) ([]byte, error)
GenerateTypeDecls generates Go code for multiple type declarations.
func (*ADTGenerator) GetADTSliceTypes ¶
func (g *ADTGenerator) GetADTSliceTypes() map[string]bool
GetADTSliceTypes returns the set of ADT types that appear in list fields. M-DX12: Used by Generator to generate typed slice converters.
func (*ADTGenerator) GetValueThreshold ¶
func (g *ADTGenerator) GetValueThreshold() int
GetValueThreshold returns the current value threshold.
func (*ADTGenerator) SetValueThreshold ¶
func (g *ADTGenerator) SetValueThreshold(threshold int)
SetValueThreshold sets the maximum field count for value-type records. M-CODEGEN-VALUE-TYPES: Records with <= threshold fields AND all primitive fields are generated as value types instead of pointers.
type AIGenerator ¶
type AIGenerator struct {
PackageName string
// contains filtered or unexported fields
}
AIGenerator generates Go code for AI effect types and context.
func NewAIGenerator ¶
func NewAIGenerator(packageName string) *AIGenerator
NewAIGenerator creates a new AI code generator.
func (*AIGenerator) GenerateAITypes ¶
func (g *AIGenerator) GenerateAITypes() ([]byte, error)
GenerateAITypes generates the ai_handler.go file content. This includes AIHandler interface, StubAIHandler, AIContext, and ErrNoAIHandler.
type BoolMatchChainEntry ¶
type BoolMatchChainEntry struct {
Condition core.CoreExpr // The condition (scrutinee of match), nil for final else
TrueBody core.CoreExpr // What to return when condition is true
LetBindings []core.CoreExpr // ANF let bindings that precede this condition
}
BoolMatchChainEntry represents one condition-result pair in a bool match chain. M-CODEGEN-LIST: Used to flatten nested bool matches into if-else chains.
type ContractGenerator ¶
type ContractGenerator struct {
PackageName string
// contains filtered or unexported fields
}
ContractGenerator generates Go code for contract types and context. M-VERIFY: Similar to DebugGenerator pattern.
func NewContractGenerator ¶
func NewContractGenerator(packageName string) *ContractGenerator
NewContractGenerator creates a new Contract code generator.
func (*ContractGenerator) GenerateContractTypes ¶
func (g *ContractGenerator) GenerateContractTypes() ([]byte, error)
GenerateContractTypes generates the contract_types.go file content. This includes ContractMode, ContractCheck, ContractOutput, and ContractContext.
type DebugGenerator ¶
type DebugGenerator struct {
PackageName string
// contains filtered or unexported fields
}
DebugGenerator generates Go code for Debug effect types and context.
func NewDebugGenerator ¶
func NewDebugGenerator(packageName string) *DebugGenerator
NewDebugGenerator creates a new Debug code generator.
func (*DebugGenerator) GenerateDebugTypes ¶
func (g *DebugGenerator) GenerateDebugTypes() ([]byte, error)
GenerateDebugTypes generates the debug_types.go file content. This includes DebugOutput, LogEntry, AssertionResult, and DebugContext. For release mode with build tags, use GenerateDebugTypesDebug and GenerateDebugTypesRelease.
func (*DebugGenerator) GenerateDebugTypesDebug ¶
func (g *DebugGenerator) GenerateDebugTypesDebug() ([]byte, error)
GenerateDebugTypesDebug generates debug_types_debug.go file for debug builds. This is the full implementation with actual logging.
func (*DebugGenerator) GenerateDebugTypesRelease ¶
func (g *DebugGenerator) GenerateDebugTypesRelease() ([]byte, error)
GenerateDebugTypesRelease generates a no-op debug_types_release.go file. In release mode, Debug operations are zero-cost stubs.
type DerivedEqType ¶
type DerivedEqType struct {
TypeName string // Go type name (e.g., "Color")
Constructors []string // List of constructor names (e.g., ["Red", "Green", "Blue"])
}
DerivedEqType stores information about an ADT type that derives Eq. M-CODEGEN-DICTIONARIES M4: Used to generate dict_Eq_<TypeName> for ADTs.
type EffectHandler ¶
type EffectHandler struct {
Name string // Effect name (e.g., "Rand", "Clock")
Methods []HandlerMethod
}
EffectHandler describes an effect that needs a handler implementation.
func DefaultAIHandler ¶
func DefaultAIHandler() EffectHandler
DefaultAIHandler returns the AI effect handler definition. This is used by the EffectsGenerator to add AI to the handlers.
func DefaultClockHandler ¶
func DefaultClockHandler() EffectHandler
DefaultClockHandler returns the default Clock effect handler definition.
func DefaultContractHandler ¶
func DefaultContractHandler() EffectHandler
DefaultContractHandler returns the Contract effect handler definition.
func DefaultDebugHandler ¶
func DefaultDebugHandler() EffectHandler
DefaultDebugHandler returns the Debug effect handler definition. This is used by the EffectsGenerator to add Debug to the handlers.
func DefaultEnvHandler ¶
func DefaultEnvHandler() EffectHandler
DefaultEnvHandler returns the default Env effect handler definition.
func DefaultFSHandler ¶
func DefaultFSHandler() EffectHandler
DefaultFSHandler returns the default FS effect handler definition.
func DefaultNetHandler ¶
func DefaultNetHandler() EffectHandler
DefaultNetHandler returns the default Net effect handler definition.
func DefaultRandHandler ¶
func DefaultRandHandler() EffectHandler
DefaultRandHandler returns the default Rand effect handler definition.
type EffectsGenerator ¶
type EffectsGenerator struct {
PackageName string
// contains filtered or unexported fields
}
EffectsGenerator generates Go code for effect handlers.
func NewEffectsGenerator ¶
func NewEffectsGenerator(packageName string) *EffectsGenerator
NewEffectsGenerator creates a new effects code generator.
func (*EffectsGenerator) GenerateHandlers ¶
func (g *EffectsGenerator) GenerateHandlers(handlers []EffectHandler) ([]byte, error)
GenerateHandlers generates handler interfaces for the given effects.
type FuncTypeOverride ¶
FuncTypeOverride stores explicit function type signatures from AST annotations. M-CODEGEN-TYPED-PARAMS: Used to override inferred structural types with declared nominal types.
type Generator ¶
type Generator struct {
// PackageName is the Go package name for generated code
PackageName string
// TypeMapper handles AILANG → Go type conversions
TypeMapper *TypeMapper
// contains filtered or unexported fields
}
Generator produces Go source code from AILANG Core AST.
func (*Generator) AnalyzeRecordType ¶
func (g *Generator) AnalyzeRecordType(fieldTypes map[string]string) (TypeCategory, bool)
AnalyzeRecordType determines the TypeCategory for a record type. M-CODEGEN-VALUE-TYPES: Two-step heuristic:
- Eligibility: Must be a leaf record (all primitive fields)
- Threshold: Field count must be ≤ threshold
Returns TypeCategoryValue for small, primitive-only records. Returns TypeCategoryPointer for all other records.
func (*Generator) Generate ¶
Generate produces Go source code from a Core program. Returns the formatted Go source code.
func (*Generator) GenerateDictionaries ¶
GenerateDictionaries produces the dictionaries.go file containing type class dictionary implementations for built-in types. M-CODEGEN-DICTIONARIES: Generates dict_Num_Int, dict_Ord_*, dict_Eq_*, etc.
func (*Generator) GenerateRuntime ¶
GenerateRuntime produces just the runtime helpers as a standalone Go file. Use this to generate a separate runtime.go when compiling multiple files.
func (*Generator) GenerateToWriter ¶
GenerateToWriter writes generated Go code to the provided writer.
func (*Generator) GetModuleName ¶
GetModuleName returns the current module name used for function namespacing. M-DX18: Used for debugging and testing.
func (*Generator) GetRecordTypeByFields ¶
func (g *Generator) GetRecordTypeByFields(fieldNames map[string]bool) *RecordTypeInfo
GetRecordTypeByFields looks up a record type by matching its field names. M-DX13: Used to infer the struct type from a record literal's fields. Returns nil if no matching record type is found. M-TYPENAME-NESTED-PROPAGATION: Also returns nil if multiple types match (ambiguous). Callers should use CoreTypeInfo TypeName when available for unambiguous selection.
func (*Generator) GetValueThreshold ¶
GetValueThreshold returns the current value threshold. M-CODEGEN-VALUE-TYPES: Used for testing and debugging.
func (*Generator) GoReprForType ¶
GoReprForType returns the Go type representation for an AILANG type name. M-CODEGEN-VALUE-TYPES: This is THE single source of truth for value vs pointer decisions. ALL codegen paths MUST use this function to determine Go type representations.
Returns:
- goType: The Go type name (e.g., "Coord" or "World")
- isPointer: true if the type should be used as a pointer (*Type)
Rules:
- Registered record types use their analyzed Category
- Unknown types default to pointer (safe fallback)
- Primitive types are never registered here (handled by isPrimitiveGoType)
func (*Generator) GoTypeStringForType ¶
GoTypeStringForType returns the Go type string for an AILANG type name. M-CODEGEN-VALUE-TYPES: Convenience wrapper that returns the full type string.
Examples:
- "Coord" (if value type)
- "*World" (if pointer type)
func (*Generator) IsPointerType ¶
IsPointerType checks if a registered type is a pointer type. M-CODEGEN-VALUE-TYPES: Inverse of IsValueType for convenience. Returns true for unknown types (safe fallback).
func (*Generator) IsValueType ¶
IsValueType checks if a registered type is a value type. M-CODEGEN-VALUE-TYPES: Used for conditional codegen logic. Returns false for unknown types (safe fallback to pointer semantics).
func (*Generator) LookupADTConstructor ¶
func (g *Generator) LookupADTConstructor(typeName, ctorName string) (*ADTConstructorInfo, bool)
LookupADTConstructor looks up an ADT constructor by name. M-DX22: Supports both qualified (TypeName.CtorName) and unqualified (CtorName) lookups. If typeName is provided, tries qualified lookup first. Falls back to unqualified lookup for backwards compatibility.
func (*Generator) LookupADTConstructorByQualifiedName ¶
func (g *Generator) LookupADTConstructorByQualifiedName(qualifiedKey string) (*ADTConstructorInfo, bool)
LookupADTConstructorByQualifiedName looks up by fully qualified key (TypeName.CtorName). M-DX22: Use when you have both type and constructor names.
func (*Generator) RegisterADTConstructor ¶
RegisterADTConstructor registers an ADT constructor for proper code generation. This enables VarGlobal references to ADT constructors to generate the correct Go constructor function calls (e.g., NewSelectionSelectionNone() instead of SelectionNone). M-DX22: Uses TypeName.CtorName as key to handle same-named constructors in different ADTs. Deprecated: Use RegisterADTConstructorWithTypes for proper type assertions.
func (*Generator) RegisterADTConstructorFull ¶
func (g *Generator) RegisterADTConstructorFull(typeName, ctorName string, fieldTypes, fieldNames []string)
RegisterADTConstructorFull registers an ADT constructor with field types and names. This enables proper field access in pattern matching with named fields. M-DX22: Uses TypeName.CtorName as key to handle same-named constructors in different ADTs.
func (*Generator) RegisterADTConstructorWithTypes ¶
RegisterADTConstructorWithTypes registers an ADT constructor with field type information. This enables proper type assertions when calling constructors from generated code. Deprecated: Use RegisterADTConstructorFull for named field support.
func (*Generator) RegisterADTSliceType ¶
RegisterADTSliceType marks an ADT type as needing a slice converter function. M-DX12: This is called when encountering [ADT] in a record/struct field.
func (*Generator) RegisterADTSliceTypes ¶
RegisterADTSliceTypes registers multiple ADT types for slice converter generation. M-DX12: Used to transfer types discovered during type generation to the code generator.
func (*Generator) RegisterDerivedEqType ¶
RegisterDerivedEqType registers an ADT type for derived Eq dictionary generation. M-CODEGEN-DICTIONARIES M4: Called during compilation for types with `deriving (Eq)`.
func (*Generator) RegisterFunctionType ¶
RegisterFunctionType registers an explicit function type signature from AST. M-CODEGEN-TYPED-PARAMS: This ensures declared types (e.g., ArrivalState) are used instead of inferred structural types (TRecord{...}) which can cause cross-module contamination.
func (*Generator) RegisterRecordType ¶
RegisterRecordType registers a record type for typed struct literal generation. M-DX13: Enables generating &World{Field: val} instead of map[string]interface{}{...}. The fields slice should contain Go field names (PascalCase), and fieldTypes maps each Go field name to its Go type string.
M-CODEGEN-VALUE-TYPES: DEPRECATED - use RegisterRecordTypeWithAnalysis for automatic value vs pointer analysis. This method defaults to pointer category for backward compatibility but does NOT analyze field types.
func (*Generator) RegisterRecordTypeWithAnalysis ¶
func (g *Generator) RegisterRecordTypeWithAnalysis(name string, fields []string, fieldTypes map[string]string)
RegisterRecordTypeWithAnalysis registers a record type with automatic category analysis. M-CODEGEN-VALUE-TYPES: Convenience method that combines registration with analysis.
func (*Generator) ResetPerModuleState ¶
func (g *Generator) ResetPerModuleState()
ResetPerModuleState clears per-module name caches between module generation passes. M-CODEGEN-MULTIMOD: When compiling multiple modules to the same Go package, the Generator accumulates function name mappings that can leak across modules. This method resets per-module state while preserving shared type registrations (ADT constructors, record types, slice types) that span all modules.
func (*Generator) SetCoreTypeInfo ¶
func (g *Generator) SetCoreTypeInfo(cti types.CoreTypeInfo)
SetCoreTypeInfo provides type information for generating typed function signatures. M-DX23: When set, functions will be generated with concrete parameter and return types instead of interface{}.
func (*Generator) SetModuleName ¶
SetModuleName sets the module name for function namespacing. M-DX18: Non-exported functions will be prefixed with {moduleName}__ to prevent collisions when multiple modules are compiled to the same Go package. The moduleName should be the last component of the module path (e.g., "solar_demo" from "sim/solar_demo").
func (*Generator) SetSkipRuntimeHelpers ¶
SetSkipRuntimeHelpers controls whether runtime helpers are included in output. Use this when compiling multiple files to avoid duplicate declarations.
func (*Generator) SetValueThreshold ¶
SetValueThreshold sets the maximum field count for value type generation. M-CODEGEN-VALUE-TYPES: Records with ≤threshold primitive-only fields are generated as values. Set to 0 to force all pointers (v0.5.9 behavior). Negative values are treated as 0.
func (*Generator) SetVerifyContracts ¶
SetVerifyContracts enables runtime contract checking. M-VERIFY: When enabled, generates predicate checks for requires/ensures clauses.
type GoType ¶
type GoType string
GoType represents a Go type string that will be emitted in generated code.
const ( GoInt64 GoType = "int64" GoFloat64 GoType = "float64" GoBool GoType = "bool" GoString GoType = "string" GoUnit GoType = "struct{}" )
Common Go types
func MapPrimitiveType ¶
MapPrimitiveType maps a primitive AILANG type name to Go. Used when we only have the type name as a string.
func WithPointer ¶
WithPointer wraps a type in a pointer if needed.
type HandlerMethod ¶
type HandlerMethod struct {
Name string // Method name (e.g., "RandInt")
Params []Param // Parameters
Returns []string // Return types
Doc string // Documentation comment
ExampleDoc string // Example implementation hint
}
HandlerMethod describes a method in an effect handler.
type LetBoolMatchEntry ¶
type LetBoolMatchEntry struct {
Condition core.CoreExpr // The actual comparison expression (e.g., LtFloat(roll, 0.76))
TrueBody core.CoreExpr // What to return when condition is true
}
LetBoolMatchEntry represents one condition-result pair from a Let-Bool-Match chain.
type PackageConfig ¶
type PackageConfig struct {
// PackageName is the Go package name
PackageName string
// OutputDir is the directory to write generated files
OutputDir string
// ModulePath is the Go module path (e.g., "github.com/user/game/gen")
ModulePath string
}
PackageConfig holds configuration for generating a Go package.
type RecordTypeInfo ¶
type RecordTypeInfo struct {
Name string // Go struct name (e.g., "World")
Fields []string // Field names in order (e.g., ["Npcs", "Tiles", "Width", "Height"])
FieldTypes map[string]string // Field name -> Go type (e.g., "Npcs" -> "[]*NPC")
FieldCount int // Number of fields
Category TypeCategory // Value or Pointer
IsLeaf bool // True if all fields are primitives (no nested records/ADTs)
}
RecordTypeInfo holds information about a record type for typed struct generation. M-DX13: Enables generating typed struct literals instead of map[string]interface{}. M-CODEGEN-VALUE-TYPES: Extended with Category for value vs pointer decisions.
type StringConvKind ¶
type StringConvKind int
StringConvKind represents the type of string conversion function.
const ( StringConvNone StringConvKind = iota StringConvFloatToStr StringConvIntToStr )
type TypeCategory ¶
type TypeCategory int
TypeCategory represents whether a record type should be generated as value or pointer in Go. M-CODEGEN-VALUE-TYPES: Size-based strategy for optimal Go code generation.
const ( // TypeCategoryPointer means the type is generated as a pointer (*Type). // Used for: large records, nested records, recursive types, ADTs. TypeCategoryPointer TypeCategory = iota // TypeCategoryValue means the type is generated as a value (Type). // Used for: small leaf records with only primitive fields. TypeCategoryValue )
type TypeMapper ¶
type TypeMapper struct {
// RecordTypeLookup is a callback to look up record types by their field names.
// M-BUGFIX: Used to map TRecord types to named struct types like *BridgeState.
// The callback takes a map of field names and returns the Go type name if found.
RecordTypeLookup func(fields map[string]bool) (string, bool)
// ValueRecordChecker is a callback to check if a record type should be passed by value.
// M-CODEGEN-VALUE-TYPES: Used to determine if TRecord maps to Type or *Type.
// Returns true for value types (leaf records with few fields), false for pointer types.
ValueRecordChecker func(goTypeName string) bool
// contains filtered or unexported fields
}
TypeMapper converts AILANG types to Go types.
func NewTypeMapper ¶
func NewTypeMapper() *TypeMapper
NewTypeMapper creates a new TypeMapper with default type mappings.
func (*TypeMapper) ExtractFuncSignature ¶
func (tm *TypeMapper) ExtractFuncSignature(t types.Type) (paramTypes []GoType, returnType GoType, ok bool)
ExtractFuncSignature extracts parameter types and return type from a function type. M-DX23: Used to generate typed function signatures from CoreTypeInfo. Returns nil slices and empty string if the type is not a function type.
func (*TypeMapper) MapType ¶
func (tm *TypeMapper) MapType(t types.Type) (GoType, error)
MapType converts an AILANG type to its Go representation. Returns the Go type string and any error. M-DX11-TRAVERSE: Uses cycle detection to prevent infinite loops on recursive types.
func (*TypeMapper) RegisterType ¶
func (tm *TypeMapper) RegisterType(ailangName string, goType GoType)
RegisterType registers a custom type mapping. Used when an ADT is defined - we register its Go type name.
Source Files
¶
- adt.go
- ai.go
- codegen.go
- codegen_block.go
- codegen_decl.go
- codegen_dictionaries.go
- codegen_expr.go
- codegen_expr_app.go
- codegen_expr_control.go
- codegen_expr_let.go
- codegen_expr_simple.go
- codegen_match.go
- codegen_match_bool.go
- codegen_ops.go
- codegen_record.go
- codegen_registry.go
- codegen_runtime.go
- codegen_runtime_arith.go
- codegen_runtime_collections.go
- codegen_runtime_misc.go
- codegen_runtime_records.go
- codegen_runtime_slices.go
- codegen_type_analysis.go
- contracts.go
- debug.go
- effects.go
- naming.go
- package.go
- type_analyzer.go
- types.go