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

  1. Create a Sona file (hello.sona):
let message = "Hello from Sona!"
print(message)
print("2 + 3 =", 2 + 3)
  1. Transpile and run:
sona compile-py hello.sona --run
  1. 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

1. Parser (grammar.lark)

  • Uses Lark parsing library
  • Converts Sona syntax to parse tree
  • Handles all supported language constructs

2. AST Builder (ast_builder.py)

  • Transforms parse tree to Abstract Syntax Tree
  • Validates syntax and structure
  • Provides clean, typed AST nodes

3. Code Generator (python_codegen.py)

  • Converts AST to equivalent Python code
  • Maintains Sona semantics in Python
  • Generates readable, debuggable output

4. Runtime Bridge (runtime.py)

  • 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

  1. Use transpiler for production deployments
  2. Use interpreter for development and testing
  3. Profile with Python tools for optimization
  4. 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

  1. Test with interpreter: sona program.sona
  2. Validate transpilation: sona compile-py program.sona --validate
  3. Check generated code: sona compile-py program.sona --output debug.py
  4. 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

  1. Develop with Sona interpreter for fast iteration
  2. Test core logic with interpreter
  3. Transpile for performance testing
  4. 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:

  1. Try the Quick Start examples
  2. Explore supported features
  3. Check out best practices
  4. 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.