ferret icon indicating copy to clipboard operation
ferret copied to clipboard

Add type tracking for variables in compiler where possible

Open Copilot opened this issue 7 months ago • 0 comments

This PR implements type tracking for variables in the Ferret compiler, addressing the TODO comment in the codebase and enabling better compile-time type information where it can be determined.

Problem

Previously, all variables in the compiler were assigned TypeUnknown, even when the type could be determined at compile time from literal assignments. This made it impossible to leverage type information for optimization or better error reporting.

Solution

Added AST-based type detection for literal variable assignments by:

  1. Enhanced global variable storage - Modified the symbol table to store type information for global variables using the existing Variable struct instead of a simple map
  2. AST-based type detection - Added logic to detect literal types directly from the AST during variable declaration compilation
  3. Runtime type conversion - Added RuntimeTypeToValueType utility function to convert between runtime types and compiler ValueType enum

Examples

The compiler now correctly tracks types for literal assignments:

LET stringVar = "hello"     // → TypeString (3)
LET intVar = 42             // → TypeInt (1)  
LET floatVar = 3.14         // → TypeFloat (2)
LET boolVar = TRUE          // → TypeBool (4)
LET arrayVar = [1, 2, 3]    // → TypeList (5)
LET objVar = {name: "test"} // → TypeMap (6)

// Complex expressions still fall back to TypeUnknown
LET resultVar = someFunction()  // → TypeUnknown (0)
LET calcVar = 1 + 2            // → TypeUnknown (0)

Implementation Details

  • Minimal changes: Only modified 3 core files in the compiler package
  • Backward compatible: All existing functionality continues to work unchanged
  • Surgical approach: Type detection only where it's reliably possible (literals)
  • Comprehensive testing: Added unit tests and integration tests to validate type tracking

The implementation follows the principle of "where it's possible" - only detecting types when they can be reliably determined at compile time from the AST, avoiding any runtime overhead or complex type inference.

Testing

All existing tests pass, and new tests validate:

  • Type conversion utility functions work correctly
  • Literal type detection works for all supported literal types
  • Non-literal expressions correctly fall back to TypeUnknown
  • Global variable lookup and resolution work with type information

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot avatar Aug 31 '25 03:08 Copilot