Type System Preview - Bryantad/Sona GitHub Wiki
Complete Type Safety with Cognitive Accessibility Features
Sona v0.8.0 includes a complete type system with cognitive accessibility features. This system provides optional static typing, intelligent type inference, and enhanced development tools while maintaining 100% backward compatibility and neurodivergent-friendly design.
New in 0.8.0: The type system is now fully implemented with AI-powered type suggestions and accessibility-first error messages.
- Basic Type Inference: Automatic detection of variable and expression types
- Type-Aware Interpreter: Enhanced interpreter with optional typing support
- Type Error Reporting: Detailed error messages with type information
- Foundation for Hindley-Milner: Infrastructure for advanced type inference
# These are Python imports for accessing experimental features
from sona.type_system import TypeInferenceEngine, TypeEnvironment
from sona.type_aware_interpreter import TypeAwareSonaInterpreter
# Python code to use the experimental type-aware interpreter
from sona.type_aware_interpreter import TypeAwareSonaInterpreter
# Create a basic type-aware interpreter
interpreter = TypeAwareSonaInterpreter(
strict_typing=False, # Gradual typing (warnings only)
enable_type_optimizations=True # Performance optimizations
)
# For strict typing (experimental)
strict_interpreter = TypeAwareSonaInterpreter(
strict_typing=True, # Strict type checking
enable_type_optimizations=True
)
The type system can automatically infer types for many expressions:
// The type system can infer these types automatically
let number = 42 // Inferred as: int
let text = "Hello" // Inferred as: string
let decimal = 3.14 // Inferred as: float
let flag = true // Inferred as: bool
// Function types can be inferred from their definitions
func add_numbers(a, b) {
return a + b // Type system infers this operates on numbers
}
// Arrays and dictionaries
let numbers = [1, 2, 3] // Inferred as: array<int>
let person = { // Inferred as: dict<string, mixed>
name: "Alice",
age: 30
}
# Python code to start a type-aware REPL session
from sona.type_aware_interpreter import TypeAwareREPL
# Create type-aware REPL
repl = TypeAwareREPL(strict_typing=False)
# Evaluate code with type information
result, errors, stats = repl.evaluate_with_types("let x = 42 + 3.14")
print(f"Result: {result}")
print(f"Type errors: {errors}")
print(f"Type statistics: {stats}")
# Get insights into type system usage
stats = interpreter.get_type_statistics()
print(f"Expressions typed: {stats['expressions_typed']}")
print(f"Type optimizations applied: {stats['type_optimizations_applied']}")
print(f"Type cache size: {stats['type_cache_size']}")
print(f"Strict mode: {stats['strict_mode']}")
The type system supports gradual typing, allowing you to add types incrementally:
// This works without any type annotations
func calculate_area(width, height) {
return width * height
}
// Future: Type annotations (planned for v0.8.0)
// func calculate_area(width: int, height: int) -> int {
// return width * height
// }
# The type system can catch potential issues
code = """
let number = 42
let text = "hello"
let result = number + text // Type mismatch detected
"""
result, errors, stats = repl.evaluate_with_types(code)
if errors:
print("Type errors found:")
for error in errors:
print(f" - {error}")
The type system enables performance optimizations when types are known:
# Create interpreter with optimizations enabled
interpreter = TypeAwareSonaInterpreter(
strict_typing=False,
enable_type_optimizations=True
)
# The interpreter can optimize operations when types are inferred
# For example: integer addition can use faster code paths
Type System Architecture (v0.7.1 Preview)
┌─────────────────────────────────────────────┐
│ TypeAwareSonaInterpreter │
│ ├── TypeContext (type checking context) │
│ ├── TypeEnvironment (variable types) │
│ └── HindleyMilnerInference (type engine) │
├─────────────────────────────────────────────┤
│ Type System Modules │
│ ├── types.py (basic type definitions) │
│ ├── inference.py (type inference engine) │
│ ├── checker.py (type checking logic) │
│ └── simple.py (simplified type interface) │
└─────────────────────────────────────────────┘
# Basic types available in the type system
from sona.type_system.types import (
INT_TYPE, # Integer type
FLOAT_TYPE, # Float type
STRING_TYPE, # String type
BOOL_TYPE, # Boolean type
UNIT_TYPE, # Unit/void type
TypeVariable, # Type variables for inference
FunctionType # Function types
)
# calculator_typed.py - Using type-aware interpreter
from sona.type_aware_interpreter import TypeAwareSonaInterpreter
interpreter = TypeAwareSonaInterpreter(enable_type_optimizations=True)
# Sona code with automatic type inference
calculator_code = """
func add(a, b) {
return a + b
}
func multiply(a, b) {
return a * b
}
func calculate_area(width, height) {
return multiply(width, height)
}
let width = 10
let height = 20
let area = calculate_area(width, height)
print("Area: " + str(area))
"""
# Execute with type awareness
result = interpreter.transform(interpreter.parse(calculator_code))
stats = interpreter.get_type_statistics()
print(f"Type optimizations applied: {stats['type_optimizations_applied']}")
# error_detection.py - Catching type errors
from sona.type_aware_interpreter import TypeAwareREPL
repl = TypeAwareREPL(strict_typing=True)
# Code with potential type issues
problematic_code = """
let number = 42
let text = "hello"
let mixed = number + text // This will be flagged in strict mode
"""
result, errors, stats = repl.evaluate_with_types(problematic_code)
if errors:
print("Type errors detected:")
for error in errors:
print(f" - {error}")
else:
print("No type errors found")
print(f"Result: {result}")
# performance_comparison.py - Comparing regular vs type-aware interpreters
import time
from sona.interpreter import SonaInterpreter
from sona.type_aware_interpreter import TypeAwareSonaInterpreter
# Test code
test_code = """
for i in range(1000) {
let result = i * 2 + i * 3
}
"""
# Regular interpreter
regular_interpreter = SonaInterpreter()
start_time = time.time()
regular_interpreter.transform(regular_interpreter.parse(test_code))
regular_time = time.time() - start_time
# Type-aware interpreter with optimizations
type_interpreter = TypeAwareSonaInterpreter(enable_type_optimizations=True)
start_time = time.time()
type_interpreter.transform(type_interpreter.parse(test_code))
type_time = time.time() - start_time
print(f"Regular interpreter: {regular_time:.4f} seconds")
print(f"Type-aware interpreter: {type_time:.4f} seconds")
print(f"Performance difference: {regular_time/type_time:.2f}x")
# Show type statistics
stats = type_interpreter.get_type_statistics()
print(f"Type optimizations applied: {stats['type_optimizations_applied']}")
// Planned features for v0.8.0
// 1. Type Annotations
func add(x: int, y: int) -> int {
return x + y
}
// 2. Generic Types
func identity<T>(value: T) -> T {
return value
}
// 3. Union Types
let value: int | string = 42
// 4. Interface Types
interface Drawable {
func draw() -> void
}
// 5. Type Aliases
type UserId = int
type UserName = string
- Complete Hindley-Milner inference: Full type inference without annotations
- Polymorphic types: Generic functions and data structures
- Type constraints: Interface-based type constraints
- Module-level types: Type checking across module boundaries
- Language Server Protocol: Full IDE support with type information
- Real-time error checking: Type errors shown as you type
- Auto-completion: Type-aware code completion
- Refactoring tools: Type-safe code transformations
- Experimental Status: Features may change or be removed
- Limited Type Annotations: No syntax for explicit type annotations yet
- Basic Inference: Simple type inference, not full Hindley-Milner
- Python Integration: Experimental features require Python imports
- Performance: Type checking adds some overhead in strict mode
- 100% Backward Compatible: All existing code works unchanged
- Optional Features: Type system is completely optional
- No Breaking Changes: Experimental features don't affect standard Sona code
- Gradual Adoption: You can enable type features incrementally
- Install Sona v0.7.1: Ensure you have the latest version
- Explore Examples: Try the examples in this guide
- Experiment Safely: Experimental features won't break existing code
- Provide Feedback: Share your experience with the community
# Clone the repository
git clone https://github.com/Bryantad/Sona.git
cd Sona
# Explore the type system code
ls sona/type_system/
# Run type system tests
python -m pytest tests/test_type_system.py -v
- GitHub Issues: Report bugs or request features
- Discussions: Share ideas and use cases
- Documentation: Help improve type system documentation
- Testing: Try experimental features and provide feedback
- Performance Guide v0.8.0 - Type system performance benefits
- Chapter 13: Language Internals - Implementation details
- Chapter 10: Advanced Features - Advanced programming techniques
-
sona/type_system/
- Type system implementation -
sona/type_aware_interpreter.py
- Type-aware interpreter -
tests/test_type_system.py
- Type system tests -
performance_baseline_fixed.py
- Performance testing with type awareness
- Hindley-Milner Type Inference: Understanding the theoretical foundation
- Gradual Typing: Best practices for incremental type adoption
- Type-Driven Development: Writing better code with types
The experimental type system in Sona v0.7.1 provides:
✅ Safe Experimentation: Try advanced features without risk ✅ Performance Benefits: Type-guided optimizations ✅ Future Foundation: Infrastructure for v0.8.0 type system ✅ Community Input: Your feedback shapes the final design
The type system represents Sona's evolution toward a more robust, performant, and developer-friendly language while maintaining the simplicity and accessibility that makes Sona special.
This is a living document that will be updated as the type system evolves. Check back for the latest experimental features and development updates.