Documentation
¶
Overview ¶
Package pipeline provides compilation passes for AILANG
Package pipeline provides compilation passes for AILANG ¶
Package pipeline provides compilation passes for AILANG ¶
Package pipeline provides compilation passes for AILANG ¶
Package pipeline provides a unified compilation pipeline for AILANG ¶
Architecture ¶
The pipeline is split into several files by responsibility:
- pipeline.go: Main types, Config, Result, Run entry point (THIS FILE)
- pipeline_single.go: Single-file/REPL pipeline (runSingle)
- pipeline_module.go: Multi-module pipeline with dependencies (runModule)
- pipeline_telemetry.go: Lowering telemetry reporting
- pipeline_helpers.go: Utility functions
- pipeline_types.go: CompileUnit and related types
- lower.go: Operator lowering pass
- specialize.go: Monomorphization pass
- validate_coretypeinfo.go: CoreTypeInfo validation
- var_resolver.go: Var type resolution
Usage ¶
result, err := pipeline.Run(cfg, src)
See Also ¶
- internal/ast: Surface AST
- internal/core: Core AST (ANF)
- internal/types: Type system
- internal/elaborate: Surface → Core elaboration
- internal/eval: Core evaluator
Package pipeline provides monomorphization for polymorphic functions ¶
Architecture ¶
The monomorphization pass is split into several files:
- specialize.go: Specializer struct, Specialize entry point, statistics (THIS FILE)
- specialize_types.go: Type manipulation (canonicalTypeFingerprint, substituteType, etc.)
- specialize_expr.go: Expression specialization (specializeExpr)
- specialize_lambda.go: Lambda specialization (specializeLambda)
- specialize_clone.go: Expression cloning with fresh node IDs (cloneExpr)
- specialize_helpers.go: Helper functions (isRecursive, patternBoundVars, copyEnv, etc.)
Usage ¶
specializer := NewSpecializer(&typeChecker.CoreTI) specializedProg, err := specializer.Specialize(coreProg) stats := specializer.GetStats()
See Also ¶
- internal/core: Core AST
- internal/types: Type system
- design_docs/planned/v0_4_0/m-poly-a.md: Monomorphization design
Index ¶
- Variables
- func AssertNoOperators(prog *core.Program) error
- func AssertProgramLowered(prog *core.Program) error
- func CreateTypeMismatchError(op core.IntrinsicOp, leftType, rightType types.Type) error
- func EraseDebugFromEffectRow(row *types.Row) *types.Row
- func EraseEffectFromRow(row *types.Row, effect string) *types.Row
- func GetAllBuiltinNames() []string
- func GetBuiltinName(op core.IntrinsicOp, typ string) (string, error)
- func GetBuiltinType(name string) string
- func GetOpSymbol(op core.IntrinsicOp) string
- func InjectPrelude(env *types.TypeEnv) *types.TypeEnv
- func IsBuiltinRegistered(name string) bool
- func IsEntryModule(publicEnv *iface.Iface) bool
- func IsEntryModuleFromAST(file *ast.File) bool
- func IsOperatorTableComplete() error
- func ModuleCacheKey(compilerVersion string, sourceContent string, depDigests map[string]string) string
- func ValidateCoreTypeInfo(prog *core.Program, coreTI types.CoreTypeInfo) error
- func ValidateEffects(surfaceAST *ast.File, coreProg *core.Program, coreTypeInfo types.CoreTypeInfo) error
- func WalkCore(prog *core.Program, visit func(core.CoreExpr))
- type Artifacts
- type CacheEntry
- type CacheManifest
- type CacheStore
- func (cs *CacheStore) Clear() error
- func (cs *CacheStore) LoadArtifacts(moduleID string) (*CachedModule, error)
- func (cs *CacheStore) Lookup(moduleID, cacheKey string) (*CacheEntry, bool)
- func (cs *CacheStore) Save() error
- func (cs *CacheStore) Stats() (entries int, totalCompileMs int64)
- func (cs *CacheStore) Store(moduleID string, entry *CacheEntry)
- func (cs *CacheStore) StoreArtifacts(moduleID string, cm *CachedModule) error
- type CachedModule
- type CompileUnit
- type Config
- type ConstructorInfo
- type CoreSanityError
- type DebugEraser
- type FallbackEvent
- type MetricsCollector
- func (mc *MetricsCollector) Finalize() *PipelineMetrics
- func (mc *MetricsCollector) IsEnabled() bool
- func (mc *MetricsCollector) RecordFromResult(result *Result)
- func (mc *MetricsCollector) RecordPhase(name string, durationMs int64)
- func (mc *MetricsCollector) SetStats(modulesCompiled, specializations, operatorsLowered int)
- type Mode
- type OpLowerer
- func (l *OpLowerer) AddError(err error)
- func (l *OpLowerer) GetTelemetry() []FallbackEvent
- func (l *OpLowerer) Lower(prog *core.Program) (*core.Program, error)
- func (l *OpLowerer) SetEnableTelemetry(enable bool)
- func (l *OpLowerer) SetResolvedConstraints(constraints map[uint64]*types.ResolvedConstraint)
- type OpMapping
- type PipelineMetrics
- type Result
- type SkipReason
- type Source
- type SpecializationKey
- type SpecializationLimits
- type SpecializationStats
- type Specializer
- type ValidationGap
- type VarResolver
Constants ¶
This section is empty.
Variables ¶
var OperatorSemantics = map[string]string{
"div_Int": "Integer division truncates toward zero (e.g., -7/2 = -3)",
"mod_Int": "Integer modulo has the sign of the dividend (e.g., -7%3 = -1)",
"div_Float": "Float division follows IEEE 754 (division by zero produces ±Inf)",
"mod_Float": "Float modulo follows IEEE 754 (mod by zero produces NaN)",
"eq_Float": "Float equality: NaN != NaN is false, all other comparisons standard",
"ne_Float": "Float inequality: NaN != x is true for all x (including NaN)",
"lt_Float": "Float less-than: any comparison with NaN is false",
"and_Bool": "Boolean AND short-circuits: false && _ returns false without evaluating RHS",
"or_Bool": "Boolean OR short-circuits: true || _ returns true without evaluating RHS",
}
OperatorSemantics documents the semantics of each operator
var OperatorTable = map[core.IntrinsicOp]OpMapping{ core.OpAdd: {Builtin: "add", Types: []string{"Int", "Float"}}, core.OpSub: {Builtin: "sub", Types: []string{"Int", "Float"}}, core.OpMul: {Builtin: "mul", Types: []string{"Int", "Float"}}, core.OpDiv: {Builtin: "div", Types: []string{"Int", "Float"}}, core.OpMod: {Builtin: "mod", Types: []string{"Int", "Float"}}, core.OpEq: {Builtin: "eq", Types: []string{"Int", "Float", "String", "Bool"}}, core.OpNe: {Builtin: "ne", Types: []string{"Int", "Float", "String", "Bool"}}, core.OpLt: {Builtin: "lt", Types: []string{"Int", "Float", "String"}}, core.OpLe: {Builtin: "le", Types: []string{"Int", "Float", "String"}}, core.OpGt: {Builtin: "gt", Types: []string{"Int", "Float", "String"}}, core.OpGe: {Builtin: "ge", Types: []string{"Int", "Float", "String"}}, core.OpConcat: {Builtin: "concat", Types: []string{"List"}}, core.OpAnd: {Builtin: "and", Types: []string{"Bool"}}, core.OpOr: {Builtin: "or", Types: []string{"Bool"}}, core.OpNot: {Builtin: "not", Types: []string{"Bool"}}, core.OpNeg: {Builtin: "neg", Types: []string{"Int", "Float"}}, core.OpBitwiseAnd: {Builtin: "bitwiseAnd", Types: []string{"Int"}}, core.OpBitwiseXor: {Builtin: "bitwiseXor", Types: []string{"Int"}}, core.OpBitwiseNot: {Builtin: "bitwiseNot", Types: []string{"Int"}}, core.OpShiftLeft: {Builtin: "shiftLeft", Types: []string{"Int"}}, core.OpShiftRight: {Builtin: "shiftRight", Types: []string{"Int"}}, }
OperatorTable defines all operator to builtin mappings
Functions ¶
func AssertNoOperators ¶
AssertNoOperators ensures no operator nodes remain after lowering
func AssertProgramLowered ¶
AssertProgramLowered ensures the program has been through the lowering pass
func CreateTypeMismatchError ¶
func CreateTypeMismatchError(op core.IntrinsicOp, leftType, rightType types.Type) error
CreateTypeMismatchError creates a structured type mismatch error for operators
func EraseDebugFromEffectRow ¶
EraseDebugFromEffectRow removes the "Debug" label from an effect row. If the row becomes empty (no labels, no tail), returns nil (pure). If the row was nil (pure), returns nil. Delegates to the generic EraseEffectFromRow.
func EraseEffectFromRow ¶
EraseEffectFromRow removes a named effect from an effect row. Returns nil if the row becomes empty (pure).
func GetAllBuiltinNames ¶
func GetAllBuiltinNames() []string
GetAllBuiltinNames returns all registered builtin names (sorted)
func GetBuiltinName ¶
func GetBuiltinName(op core.IntrinsicOp, typ string) (string, error)
GetBuiltinName returns the monomorphic builtin name for an operator and type
func GetBuiltinType ¶
GetBuiltinType returns the type signature for a builtin
func GetOpSymbol ¶
func GetOpSymbol(op core.IntrinsicOp) string
GetOpSymbol returns the string representation of an operator
func InjectPrelude ¶
InjectPrelude adds prelude type bindings to a type environment.
The prelude is a curated set of convenience functions designed to reduce syntactic friction for entry modules and REPL use. It provides commonly-used functions without requiring explicit imports.
**AI-First Design Philosophy:** "Minimize syntactic entropy" - teach the compiler to carry context so the AI doesn't have to. The prelude removes boilerplate (e.g., `import std/io (println)`) while preserving AILANG's core principle: effects remain explicit in type signatures (! {IO}).
**Prelude contents:**
- println : string -> () ! {IO} -- Print with newline (most common use case)
**Note:** `print` (no newline) requires explicit import: `import std/io (print)`
**Shadowing:** User definitions shadow prelude (no warning, intentional)
**Entry Module Detection:** Caller is responsible for determining if this is an entry module. Use IsEntryModuleFromAST(file) to check before type checking.
**Note:** This only injects TYPE bindings. Value bindings are injected separately in the evaluator via InjectPreludeValues().
func IsBuiltinRegistered ¶
IsBuiltinRegistered checks if a builtin is registered in the evaluator
func IsEntryModule ¶
IsEntryModule checks if the given public environment contains an exported main function.
An entry module is defined as:
- Module exports a function named "main"
- The main function has arity 0 (no parameters)
Entry modules get the prelude injected automatically. Library modules do not.
func IsEntryModuleFromAST ¶
IsEntryModuleFromAST checks if the given AST file contains an exported main function.
This is used for early detection before type checking, allowing prelude injection to happen before type checking rather than after.
An entry module is defined as:
- File contains a function declaration named "main"
- The main function is exported (IsExport = true)
- The main function has 0 parameters
Entry modules get the prelude injected automatically. Library modules do not.
func IsOperatorTableComplete ¶
func IsOperatorTableComplete() error
IsOperatorComplete checks if all IntrinsicOp values have mappings
func ModuleCacheKey ¶
func ModuleCacheKey(compilerVersion string, sourceContent string, depDigests map[string]string) string
ModuleCacheKey computes a deterministic cache key for a module. The key incorporates:
- Cache format version (cacheKeyVersion, bumped on format changes)
- Compiler identity (typically the build commit from internal/version.Commit) — this invalidates cache on every rebuild, so bugfixes to elaboration, type-checking, or op-lowering take effect without manual cache nukes. For tests, any stable string works.
- Module source content hash
- Sorted dependency interface digests (invalidates when any dep changes)
Returns hex-encoded SHA-256.
func ValidateCoreTypeInfo ¶
func ValidateCoreTypeInfo(prog *core.Program, coreTI types.CoreTypeInfo) error
ValidateCoreTypeInfo walks the Core AST and verifies every node has a type in CoreTypeInfo.
CONTRACT: This validator runs AFTER type checking and BEFORE lowering. Every Core node must have an entry in CoreTypeInfo (type variables are acceptable for polymorphic code; this checks presence, not concreteness).
Why this matters: - Lowering relies on CoreTypeInfo for type-directed code generation - Missing types cause "cannot lower unknown variant" panics with no context - This fail-fast approach gives clear diagnostics at compile time
Synthetic nodes: The validator skips compiler-generated nodes (e.g., Prelude builtins, injected symbols). To mark a node as synthetic, set node.CoreNode.Flags.Synthetic = true during elaboration. (TODO: Add Flags field to CoreNode in future PR)
Strict mode: Currently always enabled. In the future, --strict-coreti flag will elevate warnings (unreachable code) to errors. Default is strict in CI.
Returns:
- nil if all nodes are typed
- ValidationError listing all gaps (NodeID, kind, position, hint)
func ValidateEffects ¶
func ValidateEffects(surfaceAST *ast.File, coreProg *core.Program, coreTypeInfo types.CoreTypeInfo) error
ValidateEffects validates that functions declare all effects they use Compares declared effects from Surface AST with required effects from Core AST Returns error if a function uses effects not declared in its signature Ghost effects (e.g., Debug) are filtered from required effects — callers never need to declare them.
Types ¶
type Artifacts ¶
type Artifacts struct {
AST *ast.File
Core *core.Program
CoreTI types.CoreTypeInfo // M-DX23: Type info for Core expressions (for typed codegen)
Typed interface{} // TODO: Add typed AST when available
Linked interface{} // TODO: Add linked program when available
}
Artifacts contains intermediate representations
type CacheEntry ¶
type CacheEntry struct {
CacheKey string `json:"cache_key"`
IfaceDigest string `json:"iface_digest"`
IfaceJSON []byte `json:"iface_json,omitempty"`
CompileTimeMs int64 `json:"compile_time_ms"`
Timestamp time.Time `json:"timestamp"`
}
CacheEntry represents a single cached module.
type CacheManifest ¶
type CacheManifest struct {
Version string `json:"version"`
Entries map[string]*CacheEntry `json:"entries"`
}
CacheManifest tracks cached module compilation state.
type CacheStore ¶
type CacheStore struct {
// contains filtered or unexported fields
}
CacheStore manages the on-disk compilation cache.
func NewCacheStore ¶
func NewCacheStore(projectDir string) (*CacheStore, error)
NewCacheStore creates or loads a cache store from the given directory.
func (*CacheStore) LoadArtifacts ¶
func (cs *CacheStore) LoadArtifacts(moduleID string) (*CachedModule, error)
LoadArtifacts deserializes a CachedModule from disk.
func (*CacheStore) Lookup ¶
func (cs *CacheStore) Lookup(moduleID, cacheKey string) (*CacheEntry, bool)
Lookup checks if a module has a valid cache entry for the given key.
func (*CacheStore) Stats ¶
func (cs *CacheStore) Stats() (entries int, totalCompileMs int64)
Stats returns cache statistics.
func (*CacheStore) Store ¶
func (cs *CacheStore) Store(moduleID string, entry *CacheEntry)
Store writes a cache entry for a module.
func (*CacheStore) StoreArtifacts ¶
func (cs *CacheStore) StoreArtifacts(moduleID string, cm *CachedModule) error
StoreArtifacts serializes a CachedModule to disk alongside the manifest. Core program is gob-encoded; CoreTypeInfo, Iface, and Constructors are JSON-encoded.
type CachedModule ¶
type CachedModule struct {
Core *core.Program // Core IR (gob-encoded on disk)
CoreTI types.CoreTypeInfo // Type info for Core nodes (JSON-encoded)
Iface *iface.Iface // Module interface
Constructors map[string]*ConstructorInfo // ADT constructors
}
CachedModule holds the full compiled state for a module, enabling compilation skip on cache hit. M-INCREMENTAL-TYPECHECK.
type CompileUnit ¶
type CompileUnit struct {
ID string // Module ID/path
Surface *ast.File // Parsed AST
Core *core.Program // Core representation
CoreTI types.CoreTypeInfo // M-DX23: Type info for Core expressions
Iface *iface.Iface // Module interface
TypeEnv interface{} // Type environment (placeholder)
Constructors map[string]*ConstructorInfo // ADT constructors defined in this module
}
CompileUnit represents a module compilation unit
func (*CompileUnit) GetCore ¶
func (cu *CompileUnit) GetCore() *core.Program
GetCore returns the Core AST (implements link.CompileUnit interface)
func (*CompileUnit) GetModuleID ¶
func (cu *CompileUnit) GetModuleID() string
GetModuleID returns the module ID (implements link.CompileUnit interface)
type Config ¶
type Config struct {
Mode Mode // Execution mode (Check or Eval)
JSON bool // Output JSON format
Compact bool // Use compact JSON
DumpCore bool // Show Core AST
DumpCoreLowered bool // Show Core after lowering
DumpTyped bool // Show Typed AST
TraceDefaulting bool // Trace type defaulting
DryLink bool // Show linking without eval
RequireLowering bool // Fail if operators not lowered
ExperimentalBinopShim bool // Feature flag for operator shim
FailOnShim bool // Fail if shim would be used (CI mode)
TrackInstantiations bool // Track polymorphic type instantiations
LedgerHook func(decision string) // Optional decision hook
DisableMonomorphization bool // Disable monomorphization pass (emergency escape hatch)
DisableVarResolution bool // Disable Var type resolution (M-DX4 workaround, default enabled)
DebugCompile bool // Show compilation statistics (specialization counts, etc.)
StrictSyntaxMode bool // Disable syntactic sugar (require canonical syntax)
RelaxModules bool // Relax MOD010 validation (allow module path mismatches with warning)
NoCache bool // M-PERF6: Disable compilation cache (--no-cache)
ReleaseMode bool // M-DEBUG-ERASURE: Erase Debug ghost effect (--release)
// M-DX11: Type debugging
DebugTypes bool // Enable type inference debugging output
DebugTypesNode uint64 // Filter debug output to specific node (0 = all nodes)
// Environment from REPL (optional)
TypeEnv *types.TypeEnv
InstEnv *types.InstanceEnv
DictReg *types.DictionaryRegistry
Instances map[string]core.DictValue
EvalEnv *eval.Environment
// Global resolver for non-module evaluation (v0.2.0 hotfix)
GlobalResolver eval.GlobalResolver
// contains filtered or unexported fields
}
Config contains pipeline configuration options
type ConstructorInfo ¶
type ConstructorInfo struct {
TypeName string // ADT type name (e.g., "Option")
CtorName string // Constructor name (e.g., "Some")
FieldTypes []ast.Type // Field types from AST
Arity int // Number of fields
TypeParamCount int // M-TAPP-FIX: Number of type parameters (e.g., Option[a] = 1)
TypeParamNames []string // M-POLY-ADT: Type parameter names (e.g., ["a"] for Result[a])
InternalFieldTypes []types.Type // M-POLY-ADT: Actual field types for type scheme building
}
ConstructorInfo holds information about a constructor for interface building
type CoreSanityError ¶
CoreSanityError represents a Core IR invariant violation
func (*CoreSanityError) Error ¶
func (e *CoreSanityError) Error() string
type DebugEraser ¶
type DebugEraser struct{}
DebugEraser removes the Debug ghost effect from a Core program. In release mode, Debug calls become unit literals and Debug is removed from all effect rows, making Debug-only functions pure.
type FallbackEvent ¶
type FallbackEvent struct {
Op core.IntrinsicOp
NodeID uint64
Fallback string // "CoreTI-hit", "ResolvedConstraints", "Default"
Location string // Source location if available
}
FallbackEvent tracks when CoreTI lookup misses during lowering
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector collects pipeline metrics
func NewMetricsCollector ¶
func NewMetricsCollector(filename string, isModule bool) *MetricsCollector
NewMetricsCollector creates a new metrics collector Only enabled if AILANG_METRICS=1 is set
func (*MetricsCollector) Finalize ¶
func (mc *MetricsCollector) Finalize() *PipelineMetrics
Finalize calculates final metrics and optionally sends to hub
func (*MetricsCollector) IsEnabled ¶
func (mc *MetricsCollector) IsEnabled() bool
IsEnabled returns whether metrics collection is enabled
func (*MetricsCollector) RecordFromResult ¶
func (mc *MetricsCollector) RecordFromResult(result *Result)
RecordFromResult populates metrics from a pipeline Result
func (*MetricsCollector) RecordPhase ¶
func (mc *MetricsCollector) RecordPhase(name string, durationMs int64)
RecordPhase records a phase timing from the Result.PhaseTimings map
func (*MetricsCollector) SetStats ¶
func (mc *MetricsCollector) SetStats(modulesCompiled, specializations, operatorsLowered int)
SetStats sets compilation statistics
type OpLowerer ¶
type OpLowerer struct {
CoreTI types.CoreTypeInfo // Core NodeID → inferred types (for type-guided lowering)
// contains filtered or unexported fields
}
OpLowerer performs type-directed lowering of intrinsic operations
func NewOpLowerer ¶
func NewOpLowerer(typeEnv *types.TypeEnv, coreTI types.CoreTypeInfo) *OpLowerer
NewOpLowerer creates a new operation lowerer
func (*OpLowerer) GetTelemetry ¶
func (l *OpLowerer) GetTelemetry() []FallbackEvent
GetTelemetry returns collected telemetry events
func (*OpLowerer) SetEnableTelemetry ¶
SetEnableTelemetry enables/disables fallback telemetry tracking
func (*OpLowerer) SetResolvedConstraints ¶
func (l *OpLowerer) SetResolvedConstraints(constraints map[uint64]*types.ResolvedConstraint)
SetResolvedConstraints sets the resolved constraints from type checking
type OpMapping ¶
type OpMapping struct {
Builtin string // Base builtin name (e.g., "add")
Types []string // Supported types (e.g., ["Int", "Float"])
}
OpMapping defines how an intrinsic operation maps to builtins
type PipelineMetrics ¶
type PipelineMetrics struct {
// Timing metrics (milliseconds)
// Single-file pipeline phases
LexTime int64 `json:"lex_ms,omitempty"`
ParseTime int64 `json:"parse_ms,omitempty"`
ElaborateTime int64 `json:"elaborate_ms,omitempty"`
TypeCheckTime int64 `json:"typecheck_ms,omitempty"`
DictElabTime int64 `json:"dict_elab_ms,omitempty"`
MonomorphTime int64 `json:"monomorph_ms,omitempty"`
LowerTime int64 `json:"lower_ms,omitempty"`
LinkTime int64 `json:"link_ms,omitempty"`
ANFVerifyTime int64 `json:"anf_verify_ms,omitempty"`
// Module pipeline phases
LoadTime int64 `json:"load_ms,omitempty"` // Module loading (for multi-module)
TopoTime int64 `json:"topo_ms,omitempty"` // Topological sort
CompileTime int64 `json:"compile_ms,omitempty"` // All modules compilation (aggregate)
// Shared phases
EvalTime int64 `json:"eval_ms,omitempty"`
TotalTime int64 `json:"total_ms"`
// Resource metrics
MemoryDeltaBytes int64 `json:"memory_delta_bytes"`
AllocsCount int64 `json:"allocs_count"`
// Compilation stats
ModulesCompiled int `json:"modules_compiled"`
Specializations int `json:"specializations"`
OperatorsLowered int `json:"operators_lowered"`
// Context
Filename string `json:"filename"`
IsModule bool `json:"is_module"`
Timestamp int64 `json:"timestamp"`
}
PipelineMetrics contains timing and resource metrics from compilation
type Result ¶
type Result struct {
Value eval.Value
Type types.Type
Constraints []types.Constraint
Errors []error // TODO: Use structured errors
Warnings []*elaborate.ExhaustivenessWarning // Exhaustiveness warnings
Artifacts Artifacts
Interface *iface.Iface // Module interface (for modules only)
Modules map[string]*loader.LoadedModule // Loaded modules with Core (for module execution)
EnvLockDigest string
PhaseTimings map[string]int64 // milliseconds
Instantiations map[string]interface{} // Polymorphic instantiation tracking
// M-DX11: Type debugging
TypeChecker *types.CoreTypeChecker // Type checker (for debug output)
DebugSink *types.VerboseDebugSink // Debug events (when DebugTypes enabled)
// M-DX19: Dictionary registry with derived type class instances
DictReg *types.DictionaryRegistry
}
Result contains pipeline output
func Run ¶
Run executes the full compilation pipeline
For simple expressions/REPL, routes to runSingle (pipeline_single.go). For files with potential imports, routes to runModule (pipeline_module.go).
Pipeline metrics are collected when AILANG_METRICS=1 is set. Use AILANG_METRICS_VERBOSE=1 for detailed timing breakdown to stderr. Use AILANG_HUB_URL to send metrics to the collaboration hub.
type SkipReason ¶
type SkipReason struct {
DefSym string // Function symbol
Reason string // Human-readable reason
Location string // Source location (if available)
}
SkipReason describes why a function was not specialized
type SpecializationKey ¶
type SpecializationKey struct {
DefSym string // Original function symbol
TypesFingerprint string // Canonical fingerprint of argument types
}
SpecializationKey uniquely identifies a specialized function instance
func (SpecializationKey) String ¶
func (k SpecializationKey) String() string
String returns a human-readable representation
type SpecializationLimits ¶
type SpecializationLimits struct {
MaxPerFunction int // Maximum specializations per function (default: 16)
MaxPerModule int // Maximum specializations per module (default: 512)
}
SpecializationLimits defines resource limits for monomorphization
func DefaultSpecializationLimits ¶
func DefaultSpecializationLimits() SpecializationLimits
DefaultSpecializationLimits returns conservative default limits
type SpecializationStats ¶
type SpecializationStats struct {
TotalSpecializations int
PerFunction map[string]int
SkippedFunctions []SkipReason
CacheHits int
CacheMisses int
}
Statistics returns diagnostic information about specialization
type Specializer ¶
type Specializer struct {
CoreTI *types.CoreTypeInfo // Type information for Core nodes
Cache map[SpecializationKey]core.CoreExpr // Memoization cache
PerFunction map[string]int // Count specializations per function
TotalCount int // Total specialization count
Limits SpecializationLimits // Resource limits
Skipped []SkipReason // Functions skipped (for diagnostics)
CacheHits int // Number of cache hits
CacheMisses int // Number of cache misses
// contains filtered or unexported fields
}
Specializer performs call-site monomorphization of polymorphic functions
func NewSpecializer ¶
func NewSpecializer(coreTI *types.CoreTypeInfo) *Specializer
NewSpecializer creates a new monomorphization pass
func (*Specializer) GetStats ¶
func (s *Specializer) GetStats() SpecializationStats
GetStats returns specialization statistics for debugging
func (*Specializer) Specialize ¶
Specialize performs monomorphization on a Core program Returns the specialized program and any errors encountered
type ValidationGap ¶
type ValidationGap struct {
NodeID uint64
ExprKind string // "Lit(Float)", "Intrinsic(OpLe)", "Var", etc.
Position string // From OriginalSpan() if available
Hint string // Actionable suggestion for fixing
IsStrict bool // If false, only warn (for unreachable code in future)
}
ValidationGap represents a Core node missing from CoreTypeInfo
type VarResolver ¶
type VarResolver struct {
// contains filtered or unexported fields
}
ResolveVarTypes propagates monomorphic types from bindings to Var occurrences (M-DX4).
Problem: After type inference and ApplySubstitution, Var nodes may still have type variables (α4, etc.) in CoreTI because the substitution doesn't always capture bindings.
Solution: For each Var with a TVar in CoreTI, look up its binding (Let value or lambda param) and if the binding has a concrete type (non-TVar head), copy it to the Var.
Rules:
- Only propagate from monomorphic bindings (concrete heads: Int, Float, String, Bool, List)
- Never invent types; only copy existing concrete types
- Preserve polymorphism: don't over-constrain lambda params or polymorphic lets
- Idempotent: running twice has no effect
This is a WORKAROUND for M-DX4. The principled fix (M-POLY-B) will re-elaborate specialized bodies after monomorphization, which will naturally resolve all operator types.
func NewVarResolver ¶
func NewVarResolver(coreTI types.CoreTypeInfo) *VarResolver
NewVarResolver creates a new Var type resolver
func (*VarResolver) Resolve ¶
func (r *VarResolver) Resolve(prog *core.Program)
Resolve walks the Core AST and resolves Var types from bindings
Source Files
¶
- cache_key.go
- cache_store.go
- compile_unit.go
- core_sanity.go
- debug_erasure.go
- metrics.go
- op_lowering.go
- op_table.go
- package_resolver.go
- pipeline.go
- pipeline_converters.go
- pipeline_module.go
- pipeline_module_compile.go
- pipeline_module_imports.go
- pipeline_single.go
- pipeline_telemetry.go
- prelude.go
- resolve_vars.go
- specialize.go
- specialize_clone.go
- specialize_expr.go
- specialize_helpers.go
- specialize_lambda.go
- specialize_types.go
- validate_coretypeinfo.go
- validate_effects.go