compiler

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Examples

Constants

Variables

View Source
var ErrUnsupportedExtensionWorkflow = errors.New("unsupported extension workflow")

Functions

func BuildIREnvironment

func BuildIREnvironment(typeSystem *types.TypeSystem, registry *verb.Registry) (ir.Environment, error)

BuildIREnvironment converts loaded schema and verb declarations to the immutable declaration environment required by checked compilation.

func CompileChecked

func CompileChecked(ctx context.Context, sources []Source, environment ir.Environment, options CompileOptions) (*ir.Checked, error)

CompileChecked is the production compiler boundary. It parses .eff and .effx sources, lowers their source ASTs without creating executable legacy specs, and returns only an opaque value that has passed ir.Check.

func NewUnifiedSpec

func NewUnifiedSpec(listSpec *list.Spec, flowSpec *flow.Spec, name string) effectus.Spec

NewUnifiedSpec creates a unified spec.

Types

type CapabilityValidator

type CapabilityValidator struct{}

func (*CapabilityValidator) Validate

type CheckedFunctionProvider

type CheckedFunctionProvider interface {
	CheckedFunctionContract() ir.FunctionContract
	CheckedFunctionImplementation() any
	CheckedFunctionDescriptor() any
}

CheckedFunctionProvider supplies the immutable contract required to expose a function to checked predicates. Plain callbacks remain generation metadata.

type CompilationError

type CompilationError struct {
	Type        string // "type_error", "dependency_error", "capability_error"
	Component   string // "verb", "function", "expression"
	Location    string // verb name, function name, etc.
	Message     string
	Suggestions []string
}

CompilationError represents a compilation error

type CompilationResult

type CompilationResult struct {
	Success      bool
	Errors       []CompilationError
	Warnings     []CompilationWarning
	CompiledUnit *CompiledUnit
}

CompilationResult represents the outcome of compilation

type CompilationWarning

type CompilationWarning struct {
	Type     string
	Location string
	Message  string
}

CompilationWarning represents a compilation warning

type CompileOptions

type CompileOptions struct {
	ExecutionPolicy effectusv1.ExecutionPolicy
	Limits          ir.Limits
	// InspectSource receives each normalized AST exactly once before lowering.
	// The callback must treat the file as immutable and must not retain it.
	InspectSource func(path string, file *ast.File)
}

CompileOptions controls properties that must be frozen into checked IR.

type CompiledFunction

type CompiledFunction struct {
	Name               string
	Implementation     interface{}
	ResolverDescriptor any
	TypeSignature      *TypeSignature
	Dependencies       []string
}

CompiledFunction represents a validated function

type CompiledSpec

type CompiledSpec struct {
	List *list.Spec
	Flow *flow.Spec
	Name string
}

CompiledSpec is the legacy in-memory list/flow compatibility result. It can contain callbacks and must not be serialized as a production artifact. Use CompileChecked for validated, callback-free artifacts.

func (*CompiledSpec) Execute

func (s *CompiledSpec) Execute(ctx context.Context, facts effectus.Facts, ex effectus.Executor) error

Execute implements effectus.Spec

func (*CompiledSpec) FlowSpec

func (s *CompiledSpec) FlowSpec() *flow.Spec

FlowSpec returns the compiled flow rules.

func (*CompiledSpec) GetName

func (s *CompiledSpec) GetName() string

GetName implements effectus.Spec

func (*CompiledSpec) ListSpec

func (s *CompiledSpec) ListSpec() *list.Spec

ListSpec returns the compiled list rules.

func (*CompiledSpec) RequiredFacts

func (s *CompiledSpec) RequiredFacts() []string

RequiredFacts implements effectus.Spec

type CompiledUnit

type CompiledUnit struct {
	VerbSpecs              map[string]*CompiledVerbSpec
	Functions              map[string]*CompiledFunction
	TypeSystem             *TypeSystem
	ExecutionPlan          *ExecutionPlan
	CheckedIR              *ir.Checked
	IREnvironment          ir.Environment
	InitialData            map[string]interface{}
	Dependencies           []string // External dependencies required
	Capabilities           []string // Required capabilities
	ExtensionSnapshot      *loader.ExtensionSnapshot
	ExecutionOwnedSnapshot bool // retired after recovery acquires its execution handle
}

CompiledUnit represents a fully validated and ready-to-execute unit

type CompiledVerbSpec

type CompiledVerbSpec struct {
	Spec               *verb.Spec
	ExecutorType       ExecutorType
	ExecutorConfig     ExecutorConfig
	ExecutorDescriptor *loader.ExecutorDescriptor
	Dependencies       []string // Other verbs this depends on
	TypeSignature      *TypeSignature
	ValidationRules    []ValidationRule
}

CompiledVerbSpec represents a validated verb specification

type Compiler

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

Compiler handles parsing and type checking of Effectus files

func NewCompiler

func NewCompiler() *Compiler

NewCompiler creates a new compiler.

func (*Compiler) CompileChecked

func (c *Compiler) CompileChecked(ctx context.Context, sources []Source, environment ir.Environment, options CompileOptions) (*ir.Checked, error)

CompileChecked provides a method facade for callers that already own a Compiler.

func (*Compiler) CompileFiles

func (c *Compiler) CompileFiles(filenames []string, facts effectus.Facts) (effectus.Spec, error)

CompileFiles parses, type checks, and compiles files through the legacy interface API.

func (*Compiler) CompileProgram

func (c *Compiler) CompileProgram(filenames []string, facts effectus.Facts) (*CompiledSpec, error)

CompileProgram parses, type checks, and compiles one concrete program.

func (*Compiler) CompileUncheckedFiles

func (c *Compiler) CompileUncheckedFiles(filenames []string, facts effectus.Facts) (effectus.Spec, error)

CompileUncheckedFiles compiles without type checking. Deprecated: production code must use CompileFiles or CompileProgram.

func (*Compiler) CompileUncheckedProgram

func (c *Compiler) CompileUncheckedProgram(filenames []string, facts effectus.Facts) (*CompiledSpec, error)

CompileUncheckedProgram compiles without type checking.

func (*Compiler) GenerateTypeReport

func (c *Compiler) GenerateTypeReport() string

GenerateTypeReport generates a human-readable report of inferred types

func (*Compiler) GetTypeSystem

func (c *Compiler) GetTypeSystem() *types.TypeSystem

GetTypeSystem returns the compiler's internal type system

func (*Compiler) LoadVerbSpecs

func (c *Compiler) LoadVerbSpecs(filename string) error

LoadVerbSpecs loads verb specifications from a JSON file

func (*Compiler) ParseAndCompileFiles

func (c *Compiler) ParseAndCompileFiles(filenames []string, facts effectus.Facts) (effectus.Spec, error)

ParseAndCompileFiles parses, checks, and compiles through the legacy API. Deprecated: use ParseAndCompileProgram.

func (*Compiler) ParseAndCompileProgram

func (c *Compiler) ParseAndCompileProgram(filenames []string, facts effectus.Facts) (*CompiledSpec, error)

ParseAndCompileProgram parses, type checks, and compiles one concrete program.

func (*Compiler) ParseAndTypeCheck

func (c *Compiler) ParseAndTypeCheck(filename string, facts effectus.Facts) (*ast.File, error)

ParseAndTypeCheck parses a file and performs type checking

Example
// Create a compiler
compiler := NewCompiler()

// Register multiple verb types for demonstration
compiler.typeSystem.RegisterVerbType("SendEmail",
	map[string]*types.Type{
		"to":      {PrimType: types.TypeString},
		"subject": {PrimType: types.TypeString},
		"body":    {PrimType: types.TypeString},
	},
	&types.Type{PrimType: types.TypeBool})

compiler.typeSystem.RegisterVerbType("LogOrder",
	map[string]*types.Type{
		"order_id": {PrimType: types.TypeString},
		"total":    {PrimType: types.TypeFloat},
	},
	&types.Type{PrimType: types.TypeBool})

// Test fact type registration directly
compiler.typeSystem.BuildTypeSchemaFromFacts(&testFacts{
	factRegistry: pathutil.NewRegistry(),
	schema:       &testSchema{},
})

// Generate a type report but don't output it directly to avoid format inconsistencies
_ = compiler.GenerateTypeReport()
fmt.Println("Type Report Summary:")

// Count registered verb types
fmt.Printf("Registered %d verb types\n", 2)

// Show SendEmail registration details
fmt.Println("SendEmail verb has arguments: to, subject, body")

// Show LogOrder registration details
fmt.Println("LogOrder verb has arguments: order_id, total")
Output:
Type Report Summary:
Registered 2 verb types
SendEmail verb has arguments: to, subject, body
LogOrder verb has arguments: order_id, total

func (*Compiler) ParseFile

func (c *Compiler) ParseFile(filename string) (*ast.File, error)

ParseFile parses one file through the shared compiler front end.

func (*Compiler) RegisterProtoTypes

func (c *Compiler) RegisterProtoTypes(protoFile string) error

RegisterProtoTypes registers types from protobuf files

type DependencyOptimizer

type DependencyOptimizer struct{}

func (*DependencyOptimizer) Optimize

func (do *DependencyOptimizer) Optimize(plan *ExecutionPlan) *ExecutionPlan

type DependencyValidator

type DependencyValidator struct{}

func (*DependencyValidator) Validate

type DescriptorExecutorConfig

type DescriptorExecutorConfig struct {
	Descriptor loader.ExecutorDescriptor
}

DescriptorExecutorConfig carries immutable loader output until runtime constructs and owns the transport resource.

func (*DescriptorExecutorConfig) GetType

func (config *DescriptorExecutorConfig) GetType() ExecutorType

func (*DescriptorExecutorConfig) Validate

func (config *DescriptorExecutorConfig) Validate() error

type ErrorPolicy

type ErrorPolicy string

ErrorPolicy defines how to handle errors in execution

const (
	ErrorPolicyFail       ErrorPolicy = "fail"       // Fail entire execution
	ErrorPolicyContinue   ErrorPolicy = "continue"   // Continue with other verbs
	ErrorPolicyRetry      ErrorPolicy = "retry"      // Retry failed verbs
	ErrorPolicyCompensate ErrorPolicy = "compensate" // Run compensation verbs
)

type ErrorReporter

type ErrorReporter struct{}

ErrorReporter handles compilation error reporting

func NewErrorReporter

func NewErrorReporter() *ErrorReporter

type ExecutionPhase

type ExecutionPhase struct {
	Name        string
	Verbs       []string
	Parallel    bool
	Timeout     string
	ErrorPolicy ErrorPolicy
}

ExecutionPhase represents a phase in the execution plan

type ExecutionPlan

type ExecutionPlan struct {
	Phases       []ExecutionPhase
	Dependencies map[string][]string // verb -> dependencies
	Capabilities map[string][]string // verb -> required capabilities
	Executors    map[string]ExecutorConfig
}

ExecutionPlan defines how compiled verbs should be executed

type ExecutionPlanOptimizer

type ExecutionPlanOptimizer struct{}

func (*ExecutionPlanOptimizer) Optimize

func (epo *ExecutionPlanOptimizer) Optimize(plan *ExecutionPlan) *ExecutionPlan

type ExecutorConfig

type ExecutorConfig interface {
	GetType() ExecutorType
	Validate() error
}

ExecutorConfig contains configuration for verb execution

type ExecutorType

type ExecutorType string

ExecutorType defines how a verb should be executed. Checked extension compilation emits ExecutorLocal only. Other values are compatibility types for callers that explicitly own transport lifecycle and runtime factories.

const (
	ExecutorLocal    ExecutorType = "local"    // Execute in-process
	ExecutorHTTP     ExecutorType = "http"     // Execute via HTTP
	ExecutorGRPC     ExecutorType = "grpc"     // Execute via gRPC
	ExecutorMessage  ExecutorType = "message"  // Execute via message queue
	ExecutorExternal ExecutorType = "external" // Execute in external system
	ExecutorMock     ExecutorType = "mock"     // Mock execution for testing
)

type ExtensionCompiler

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

ExtensionCompiler orchestrates the compilation process for extensions

func NewExtensionCompiler

func NewExtensionCompiler() *ExtensionCompiler

NewExtensionCompiler creates a new extension compiler instance

func (*ExtensionCompiler) Compile

Compile stages mutable loaders before it compiles. Production callers should use Stage and CompileSnapshot as separate bounded phases.

func (*ExtensionCompiler) CompileSnapshot

func (c *ExtensionCompiler) CompileSnapshot(ctx context.Context, snapshot *loader.ExtensionSnapshot) (*CompilationResult, error)

CompileSnapshot compiles only immutable in-memory loader output. It does not call mutable filesystem, HTTP, DNS, or OCI loaders.

type FunctionDefinition

type FunctionDefinition struct {
	Name       string
	InputTypes []string
	OutputType string
	Pure       bool // Whether function has side effects
}

FunctionDefinition represents a function signature

type GRPCExecutorConfig

type GRPCExecutorConfig struct {
	Address     string            `json:"address"`
	Method      string            `json:"method"` // Fully-qualified method, e.g. /package.Service/Call
	Timeout     string            `json:"timeout"`
	Metadata    map[string]string `json:"metadata"`
	UseTLS      bool              `json:"useTLS"`
	Insecure    bool              `json:"insecure,omitempty"`
	ServerName  string            `json:"serverName,omitempty"`
	RetrySafe   bool              `json:"retrySafe,omitempty"`
	RetryPolicy *RetryPolicy      `json:"retryPolicy,omitempty"`
}

GRPCExecutorConfig is retained for callers that explicitly own a gRPC transport factory. Checked extension compilation does not emit this config.

func (*GRPCExecutorConfig) GetType

func (gec *GRPCExecutorConfig) GetType() ExecutorType

func (*GRPCExecutorConfig) Validate

func (gec *GRPCExecutorConfig) Validate() error

type HTTPExecutorConfig

type HTTPExecutorConfig struct {
	URL                 string            `json:"url"`
	Method              string            `json:"method"`
	Headers             map[string]string `json:"headers"`
	Timeout             string            `json:"timeout"`
	AllowPrivateNetwork bool              `json:"allowPrivateNetwork,omitempty"`
	RetryPolicy         *RetryPolicy      `json:"retryPolicy,omitempty"`
}

HTTPExecutorConfig is retained for callers that explicitly own an HTTP transport factory. Checked extension compilation does not emit this config.

func (*HTTPExecutorConfig) GetType

func (hec *HTTPExecutorConfig) GetType() ExecutorType

func (*HTTPExecutorConfig) Validate

func (hec *HTTPExecutorConfig) Validate() error

type LocalExecutorConfig

type LocalExecutorConfig struct {
	Implementation loader.VerbExecutor
}

LocalExecutorConfig for in-process execution

func (*LocalExecutorConfig) GetType

func (lec *LocalExecutorConfig) GetType() ExecutorType

func (*LocalExecutorConfig) Validate

func (lec *LocalExecutorConfig) Validate() error

type MessageExecutorConfig

type MessageExecutorConfig struct {
	Publisher           string            `json:"publisher,omitempty"` // "kafka" or "http"
	Brokers             []string          `json:"brokers,omitempty"`
	URL                 string            `json:"url,omitempty"`
	Headers             map[string]string `json:"headers,omitempty"`
	Topic               string            `json:"topic"`
	Queue               string            `json:"queue"`
	Exchange            string            `json:"exchange"`
	RoutingKey          string            `json:"routingKey"`
	Timeout             string            `json:"timeout"`
	AllowPrivateNetwork bool              `json:"allowPrivateNetwork,omitempty"`
	RetryPolicy         *RetryPolicy      `json:"retryPolicy,omitempty"`
}

MessageExecutorConfig is retained for callers that explicitly own a message transport factory. Checked extension compilation does not emit this config.

func (*MessageExecutorConfig) GetType

func (mec *MessageExecutorConfig) GetType() ExecutorType

func (*MessageExecutorConfig) Validate

func (mec *MessageExecutorConfig) Validate() error

type MockExecutorConfig

type MockExecutorConfig struct{}

func (*MockExecutorConfig) GetType

func (mec *MockExecutorConfig) GetType() ExecutorType

func (*MockExecutorConfig) Validate

func (mec *MockExecutorConfig) Validate() error

type Optimizer

type Optimizer interface {
	Optimize(plan *ExecutionPlan) *ExecutionPlan
}

Optimizer interface for execution plan optimization

type RetryPolicy

type RetryPolicy struct {
	MaxRetries      int      `json:"maxRetries"`
	InitialDelay    string   `json:"initialDelay"`
	MaxDelay        string   `json:"maxDelay"`
	BackoffFactor   float64  `json:"backoffFactor"`
	RetryableErrors []string `json:"retryableErrors"`
}

RetryPolicy defines retry behavior for external executors

type SecurityValidator

type SecurityValidator struct{}

func (*SecurityValidator) Validate

type Source

type Source struct {
	Path    string
	Content []byte
	Data    []byte // Deprecated: use Content.
}

Source is one in-memory Effectus source file. Path determines the source dialect and canonical declaration order; Content is never read again after CompileChecked returns.

func LoadSources

func LoadSources(paths []string) ([]Source, error)

LoadSources reads Effectus source paths for CompileChecked. It is the shared file front end used by command-line checked compilation.

type TypeConstraint

type TypeConstraint struct {
	Type        string // "range", "enum", "pattern", "dependency"
	Parameter   string
	Values      []interface{}
	Description string
}

TypeConstraint represents a constraint on types

type TypeDefinition

type TypeDefinition struct {
	Name        string                 `json:"name"`
	Type        string                 `json:"type"` // "primitive", "object", "array", "union"
	Properties  map[string]interface{} `json:"properties,omitempty"`
	ElementType *TypeDefinition        `json:"elementType,omitempty"`
	UnionTypes  []*TypeDefinition      `json:"unionTypes,omitempty"`
	Constraints []TypeConstraint       `json:"constraints,omitempty"`
}

TypeDefinition represents a type in the system

type TypeSignature

type TypeSignature struct {
	InputTypes  map[string]string // arg name -> type
	OutputType  string
	Constraints []TypeConstraint
}

TypeSignature represents the type information for a verb or function

type TypeSystem

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

TypeSystem manages type information and validation

type TypeValidator

type TypeValidator struct{}

Validators and conservative no-op optimizers used by extension compilation.

func (*TypeValidator) Validate

type ValidationRule

type ValidationRule struct {
	Type         string // "input", "output", "capability", "dependency"
	Expression   string
	ErrorMessage string
}

ValidationRule represents a validation rule for a verb

type Validator

type Validator interface {
	Validate(typeSystem *TypeSystem, verbs map[string]*CompiledVerbSpec) ([]CompilationError, []CompilationWarning)
}

Validator interface for compilation validation

Jump to

Keyboard shortcuts

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