Transpiler Guide - Bryantad/Sona GitHub Wiki
SonaโPython Transpiler Guide
Unlock Python Performance with Sona Syntax: The Complete Guide to Sona's Transpiler
๐ Introduction
The SonaโPython transpiler is a revolutionary feature in Sona v0.7.1 that allows you to write Sona code and execute it with Python's performance and ecosystem. Instead of running through the Sona interpreter, your code is transpiled (translated) to equivalent Python code and executed natively.
Why Use the Transpiler?
- ๐โโ๏ธ Performance: Execute at Python speed instead of interpreter speed
- ๐ง Debugging: Use Python's excellent debugging tools
- ๐ฆ Integration: Seamlessly integrate with Python libraries
- ๐ฏ Production: Deploy Sona applications in Python environments
- ๐ ๏ธ Development: Better IDE support through generated Python code
๐ Quick Start
Prerequisites
- Sona v0.7.1 or later
- Python 3.8+ installed on your system
Your First Transpilation
- Create a Sona file (
hello.sona
):
let message = "Hello from Sona!"
print(message)
print("2 + 3 =", 2 + 3)
- Transpile and run:
sona compile-py hello.sona --run
- Output:
Hello from Sona!
2 + 3 = 5
That's it! Your Sona code was transpiled to Python and executed.
๐ ๏ธ Installation & Setup
Check Your Installation
Verify that you have the transpiler available:
sona --version
# Should show v0.7.1 or later
sona compile-py --help
# Should show transpiler options
System Requirements
- Sona: v0.7.1+
- Python: 3.8+ (required for execution)
- Platform: Windows, macOS, Linux
๐ป Command Line Interface
Basic Commands
Transpile and Run
# Transpile and immediately execute
sona compile-py program.sona --run
Transpile to File
# Generate Python file
sona compile-py program.sona --output program.py
# Then run the Python file
python program.py
Validate Output
# Transpile with validation
sona compile-py program.sona --validate --run
Command Options
Option | Description | Example |
---|---|---|
--run |
Execute immediately after transpiling | sona compile-py hello.sona --run |
--output |
Save Python code to file | sona compile-py hello.sona --output hello.py |
--validate |
Validate generated Python syntax | sona compile-py hello.sona --validate |
--help |
Show all available options | sona compile-py --help |
๐ฏ Supported Features
โ Fully Supported (v0.7.1)
Variables and Data Types
let name = "Alice"
let age = 25
let height = 5.8
let is_student = true
Arithmetic Operations
let result = (10 + 5) * 2 - 3
let division = 20 / 4
let remainder = 15 % 4
String Operations
let greeting = "Hello, " + "World!"
let full_name = first_name + " " + last_name
let message = "Age: " + str(age)
Print Statements
print("Simple message")
print("Multiple", "arguments", "here")
print("Number:", 42)
print("Calculation:", 10 + 5)
Multi-line Programs
let x = 10
let y = 20
let sum = x + y
let product = x * y
print("Sum:", sum)
print("Product:", product)
Expressions and Parentheses
let complex = ((a + b) * c) - (d / e)
let mixed = (age * 2) + " years old"
โณ Coming Soon (v0.8.0+)
- Control Flow:
if
,while
,for
statements - Functions: Custom function definitions and calls
- Data Structures: Lists, dictionaries, objects
- Modules: Import and export functionality
- Advanced Types: Classes, interfaces, generics
๐๏ธ Architecture Overview
Transpilation Pipeline
The Sona transpiler uses a multi-stage pipeline to convert Sona code to Python:
Sona Source Code
โ
[1] Parse (grammar.lark)
โ
[2] Build AST (ast_builder.py)
โ
[3] Generate Python (python_codegen.py)
โ
[4] Execute (runtime.py)
โ
Python Output
Key Components
grammar.lark
)
1. Parser (- Uses Lark parsing library
- Converts Sona syntax to parse tree
- Handles all supported language constructs
ast_builder.py
)
2. AST Builder (- Transforms parse tree to Abstract Syntax Tree
- Validates syntax and structure
- Provides clean, typed AST nodes
python_codegen.py
)
3. Code Generator (- Converts AST to equivalent Python code
- Maintains Sona semantics in Python
- Generates readable, debuggable output
runtime.py
)
4. Runtime Bridge (- Provides Sona-specific functionality in Python
- Handles type conversions and operations
- Maintains compatibility with Sona behavior
๐ Examples
Example 1: Calculator
// calculator.sona
let a = 15
let b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Remainder:", a % b)
Run it:
sona compile-py calculator.sona --run
Generated Python:
# Auto-generated from calculator.sona
from transpiler.runtime import *
a = 15
b = 4
print("Addition:", sona_add(a, b))
print("Subtraction:", sona_subtract(a, b))
print("Multiplication:", sona_multiply(a, b))
print("Division:", sona_divide(a, b))
print("Remainder:", sona_modulo(a, b))
Example 2: String Processing
// greetings.sona
let first_name = "John"
let last_name = "Doe"
let age = 30
let full_name = first_name + " " + last_name
let introduction = "Hi, I'm " + full_name + " and I'm " + str(age) + " years old."
print(introduction)
print("Welcome to Sona!")
Run it:
sona compile-py greetings.sona --run
Example 3: Complex Expressions
// math_demo.sona
let x = 10
let y = 3
let z = 2
let complex_calc = ((x + y) * z) - (x / y)
let string_result = "Result: " + str(complex_calc)
print("Variables: x=" + str(x) + ", y=" + str(y) + ", z=" + str(z))
print(string_result)
print("Final check:", complex_calc > 20)
๐ ๏ธ Advanced Usage
Working with Generated Python Code
Inspecting Generated Code
# Generate Python file to examine
sona compile-py program.sona --output program.py
# View the generated Python
cat program.py # Linux/Mac
type program.py # Windows
Debugging with Python Tools
# Use Python debugger
python -m pdb program.py
# Use Python profiler
python -m cProfile program.py
Integration with Python Projects
# Import generated Sona code in Python
from program import * # Generated from program.sona
# Use Sona variables and functions
print("Imported from Sona:", some_sona_variable)
Performance Optimization
Transpiler vs Interpreter Performance
Execution Method | Speed | Use Case |
---|---|---|
Sona Interpreter | ~5,000 ops/sec | Development, prototyping |
Python Transpiler | ~50,000+ ops/sec | Production, performance-critical |
Best Practices for Performance
- Use transpiler for production deployments
- Use interpreter for development and testing
- Profile with Python tools for optimization
- Leverage Python libraries through generated code
โ Troubleshooting
Common Issues
1. Parse Errors
Problem: Transpiler fails to parse Sona code
ERROR: Failed to parse Sona code
Solutions:
- Check for double newlines between statements
- Verify proper syntax with Sona interpreter first
- Use
sona
command to test syntax before transpiling
2. Python Syntax Errors in Generated Code
Problem: Generated Python code has syntax errors
ERROR: Generated Python code has syntax errors
Solutions:
- Use
--validate
flag to check generated code - Report the issue if validation passes but execution fails
- Check for unsupported Sona features
3. Runtime Errors
Problem: Transpiled code runs but produces wrong results
ERROR: AttributeError: 'str' object has no attribute...
Solutions:
- Compare with interpreter output
- Check data type expectations
- Use Python debugging tools
Getting Help
Debug Steps
- Test with interpreter:
sona program.sona
- Validate transpilation:
sona compile-py program.sona --validate
- Check generated code:
sona compile-py program.sona --output debug.py
- Run Python directly:
python debug.py
Reporting Issues
When reporting transpiler issues, please include:
- Sona source code that fails
- Generated Python code (use
--output
) - Error messages from both Sona and Python
- Expected vs actual behavior
๐ Best Practices
When to Use the Transpiler
โ Use Transpiler For:
- Production deployments
- Performance-critical applications
- Integration with Python ecosystems
- Debugging complex issues
- Sharing code with Python developers
โ Use Interpreter For:
- Development and prototyping
- Learning Sona syntax
- Quick testing and experimentation
- REPL-style interactive programming
Code Organization
Project Structure
my_sona_project/
โโโ src/
โ โโโ main.sona # Main application
โ โโโ utils.sona # Utility functions
โ โโโ config.sona # Configuration
โโโ build/
โ โโโ main.py # Generated Python
โ โโโ utils.py # Generated Python
โ โโโ config.py # Generated Python
โโโ scripts/
โโโ build.sh # Build script
โโโ deploy.sh # Deployment script
Build Script Example
#!/bin/bash
# build.sh - Transpile all Sona files
mkdir -p build
echo "Transpiling Sona files..."
sona compile-py src/main.sona --output build/main.py
sona compile-py src/utils.sona --output build/utils.py
sona compile-py src/config.sona --output build/config.py
echo "Build complete! Run with: python build/main.py"
Development Workflow
Recommended Workflow
- Develop with Sona interpreter for fast iteration
- Test core logic with interpreter
- Transpile for performance testing
- Deploy using transpiled Python code
Testing Strategy
# Test with interpreter (fast feedback)
sona test_program.sona
# Test with transpiler (production-like)
sona compile-py test_program.sona --run
# Compare outputs (should be identical)
๐ฎ Future Roadmap
v0.8.0 (Coming Soon)
- Control Flow: if/else, while loops, for loops
- Functions: Custom function definitions
- Enhanced Error Messages: Better user-friendly errors
- Source Maps: Line-by-line debugging support
v0.9.0 (Planned)
- Data Structures: Lists, dictionaries, sets
- Module System: Import/export functionality
- Standard Library: Transpiled stdlib modules
- Optimization: Dead code elimination, constant folding
v1.0.0 (Future)
- Object-Oriented: Classes, inheritance, polymorphism
- Advanced Types: Generics, interfaces, type unions
- Package Manager: Direct integration with PyPI
- Production Tools: Profiling, monitoring, deployment
๐ Support & Community
Getting Help
- GitHub Issues: Report bugs or request features
- Documentation: Check other wiki pages for comprehensive guides
- Examples: Browse the
examples/
directory in the repository
Contributing
- Bug Reports: Include code samples and error messages
- Feature Requests: Describe use cases and expected behavior
- Pull Requests: Follow the contributing guidelines
๐ Summary
The SonaโPython transpiler in v0.7.1 provides:
โ
Production-ready transpilation for core features
โ
Simple CLI with sona compile-py
command
โ
Full compatibility with Python ecosystem
โ
Excellent performance with Python execution speed
โ
Strong foundation for future language features
Next Steps:
- Try the Quick Start examples
- Explore supported features
- Check out best practices
- Join the community and help shape the future!
For more information, visit the Sona GitHub repository or check out the other wiki pages for comprehensive language documentation.