# Glyph Runtime Architecture
## Overview
The Glyph runtime implements a complete compilation and execution pipeline for the Glyph programming language. It follows an immutable-first design philosophy with capability-based security.
## Compilation Pipeline
### 1. AST to IR Transformation (`ast_to_ir.rs`)
- Converts the parsed AST into an intermediate representation
- Handles scope management for variables
- Transforms control flow into basic blocks
- Prepares function metadata including parameters
### 2. IR to Bytecode Compilation (`ir_to_bytecode.rs`)
- Compiles IR instructions to VM bytecode
- Generates parameter binding instructions for functions
- Calculates jump offsets for control flow
- Maps intrinsic names to capabilities
### 3. High-Level Compiler (`compiler.rs`)
- Orchestrates the entire compilation pipeline
- Provides simple API: `compile()` and `compile_and_run()`
- Maps capability declarations to VM capabilities
- Handles error propagation through the pipeline
## Virtual Machine Design
### Stack-Based Execution
- Values are pushed/popped from an execution stack
- Binary operations consume two values, push one result
- Function calls create new stack frames
### Call Frame Management (`frame.rs`)
- Each function call creates a new frame
- Frames store:
- Local variables (immutable bindings)
- Return address information
- Base pointer for stack cleanup
- Parameter binding happens at function entry
### Memory Management (`memory.rs`)
- Tracks memory allocations
- Enforces memory limits based on capabilities
- Provides usage statistics
### Capability System (`capability.rs`)
- Programs declare required capabilities upfront
- VM enforces capability checks at runtime
- Supports pattern matching for network URLs
- Capabilities include:
- AudioSpeak: Text-to-speech
- DisplayChart/DisplayImage: Visual output
- NetworkFetch: HTTP requests (with URL patterns)
- FileRead/FileWrite: File system access
- SystemInfo: System information access
- MemoryLimited/Unlimited: Memory limits
- TimeUnlimited: Execution time limits
## Key Design Decisions
### Immutability
- All values are immutable
- Variable bindings cannot be reassigned
- Collections operations return new collections
### Parameter Binding
- Function parameters are bound as local variables
- Arguments are passed on the stack in order
- The IR to bytecode compiler generates BindLocal instructions
### Error Handling
- Comprehensive error types for each stage
- Runtime errors include stack under/overflow, undefined variables, type errors
- Capability violations are caught at runtime
### Performance Considerations
- Basic block structure enables future optimizations
- Stack-based VM for efficient execution
- Minimal allocations during execution