YREA-SLS/docs/memory_management.md

2.8 KiB

Title Prev Next
YREA SLS | F Memory Management Module System Examples and Tutorials

Appendix F: Memory Management (Future)

The language specification currently does not include heap memory management. This appendix documents potential future approaches.

Current State: All values are stack-allocated or embedded in data structures.

Pointer Types: The ptr type for raw pointers is planned as a future feature and will be part of the memory management system.

Potential Approaches:

Option A: Manual Management

// Allocate on heap
3.0 4.0 Point alloc     // ( Point -- ptr<Point> )

// Dereference
ptr deref               // ( ptr<T> -- T )

// Store through pointer
new_value ptr store     // ( T ptr<T> -- )

// Free memory
ptr free                // ( ptr<T> -- )

Pros: Full control, predictable, zero overhead
Cons: Error-prone, requires discipline, potential memory leaks

Option B: Reference Counting

// Create reference-counted value
3.0 4.0 Point rc        // ( Point -- rc<Point> )

// Automatic reference counting
value dup               // Increments count
drop                    // Decrements count, frees if zero

Pros: Automatic cleanup, relatively simple
Cons: Runtime overhead, cannot handle cycles, larger memory footprint

Option C: Ownership System (Rust-like)

// Linear types - each value has one owner
value                   // Move semantics by default
value dup               // Error: cannot copy owned value
value ::clone call      // Explicit clone required

Pros: Memory safe, zero overhead, prevents leaks
Cons: Complex type system, restricts stack operations, steep learning curve

Option D: Arena/Region-Based

// Create arena
::arena new             // ( -- arena )

// Allocate in arena
arena 3.0 4.0 Point alloc_in  // ( arena Point -- ptr<Point> )

// Free entire arena
arena free_arena        // ( arena -- )

Pros: Fast allocation, simple bulk deallocation
Cons: Less granular control, memory held until arena freed

Recommendation: Start without heap allocation (current approach). When needed, implement Option A (manual) for simplicity, with Option D (arenas) added later for performance-critical code. The stack-based nature makes ownership tracking (Option C) particularly challenging.

Type Parameter Enforcement Enhancement:

Current State: Type parameters in generic functions are currently suggestions and are not enforced at parse time.

Example:

(T -- T) { dup * } ::square fn  // Currently no error even without Multiplyable constraint

Future Enhancement: The compiler could enforce that type parameters actually constrain how operators and functions act, validated at parse time:

(Multiplyable -- Multiplyable) { dup * } ::square fn  // Enforced constraint

This would provide stronger type safety but add complexity to the type checker.