### Hello World Python Source Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Example Python code for a simple 'Hello, World!' program. ```python def greet(name: str) -> str: return "Hello, " + name + "!" def main() -> int: message: str = greet("World") print(message) return 0 ``` -------------------------------- ### Test Examples Source: https://github.com/djmahe4/py2rust/blob/main/README.md Command to run the example test suite. ```bash python scripts/test_examples.py ``` -------------------------------- ### Installation via Git Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Command to install py2rust from its Git repository. ```bash # From the root of the py2rust project pip install git+https://github.com/djmahe4/py2rust.git ``` -------------------------------- ### Classes and Protocols Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Demonstrates the mapping of Python classes, constructors, protocols, and decorators to Rust structs and impl patterns. ```python from typing import Protocol class Drawable(Protocol): def draw(self) -> None: ... class Circle: radius: float def __init__(self, r: float) -> None: self.radius = r def draw(self) -> None: print("Drawing Circle") ``` -------------------------------- ### Verify Installation Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Command to verify py2rust installation. ```bash py2rust --help ``` -------------------------------- ### Type Grammar Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md A simplified grammar for type parsing in py2rust, demonstrating an LL(1) grammar where each alternative starts with a distinct terminal, allowing for deterministic parsing. ```plaintext Type → 'int' | 'float' | 'bool' | 'str' | 'list' '[' Type ']' | 'dict' '[' Type ',' Type ']' | 'Optional' '[' Type ']' | ClassName ``` -------------------------------- ### Installation via Pip Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Command to install py2rust using pip. ```bash pip install py2rust ``` -------------------------------- ### Simple Math Example - Python Input Source: https://github.com/djmahe4/py2rust/blob/main/README.md Python code for a simple addition function and main execution. ```python def add(x: int, y: int) -> int: return x + y def main() -> int: a: int = 10 b: int = 5 result: int = add(a, b) print(result) return 0 ``` -------------------------------- ### Cargo Verification Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md Example snippet from py2rust/main.py showing how the `--verify` flag invokes `cargo check` to validate generated Rust code. ```python if config.verify and config.output_file: result = subprocess.run( ['cargo', 'check'], # external compiler tool cwd=tmp_dir_path, capture_output=True, text=True ) if result.returncode != 0: print(f"Cargo verification failed:\n{result.stderr}", ...) return False logger.info("Cargo verification passed") ``` -------------------------------- ### Example Context-Free Grammar for Arithmetic Expressions Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md A sample CFG demonstrating rules for arithmetic expressions involving addition, subtraction, multiplication, division, and parentheses. ```plaintext E -> E + T | E - T | T T -> T * F | T / F | F F -> ( E ) | id | num ``` -------------------------------- ### Python File Operations Example Source: https://github.com/djmahe4/py2rust/blob/main/README.md Demonstrates basic file writing and reading in Python. ```Python def main() -> int: f = open("test.txt", "w") f.write("Hello, World!") f.close() f = open("test.txt", "r") contents = f.read() print(contents) f.close() return 0 ``` -------------------------------- ### Python List Example Source: https://github.com/djmahe4/py2rust/blob/main/README.md Demonstrates a Python function to sum a list of integers. ```Python def sum_list(nums: list[int]) -> int: total: int = 0 for n in range(len(nums)): total = total + nums[n] return total def main() -> int: numbers: list[int] = [1, 2, 3, 4, 5] result: int = sum_list(numbers) print(result) return 0 ``` -------------------------------- ### AST Encoding Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Shows how the parse tree for '3 + 4 * 2' is directly encoded using py2rust's AST node classes. ```python BinOp(op="+", left=IntLiteral(3), right=BinOp(op="*", left=IntLiteral(4), right=IntLiteral(2))) ``` -------------------------------- ### Module Search Path Configuration Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Example of how to specify custom library paths for the py2rust compiler. ```bash py2rust src/main.py --plugin-path ./custom_libs ``` -------------------------------- ### Simple Math Example - Rust Output Source: https://github.com/djmahe4/py2rust/blob/main/README.md Generated Rust code for the simple math example. ```rust fn add(x: i32, y: i32) -> i32 { return x + y; } fn main() -> i32 { let a: i32 = 10; let b: i32 = 5; let result: i32 = add(a, b); println!("{}", result); return 0; } ``` -------------------------------- ### NFA to DFA Subset Construction Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md Mermaid diagram illustrating the conversion of an NFA to a DFA for recognizing 'int' or 'in' keywords versus 'identifier', demonstrating the maximal munch rule. ```mermaid stateDiagram-v2 [*] --> Start Start --> i_state : 'i' i_state --> in_state : 'n' in_state --> int_state : 't' in_state --> accept_in : [Other / End of Word] int_state --> accept_int : [Other / End of Word] Start --> ident_state : [a-hj-z_] i_state --> ident_state : [a-mop-z_] in_state --> ident_state : [a-su-z_] ident_state --> ident_state : [a-zA-Z0-9_] ident_state --> accept_ident : [Other / End of Word] state accept_in { [*] --> InKeyword : accept "in" (KW_IN) } state accept_int { [*] --> IntKeyword : accept "int" (KW_INT) } state accept_ident { [*] --> Identifier : accept identifier (IDENT) } ``` -------------------------------- ### Fibonacci Example - Python Input Source: https://github.com/djmahe4/py2rust/blob/main/README.md Python code for a Fibonacci sequence calculation. ```python def fibonacci(n: int) -> int: if n <= 0: return 0 elif n == 1: return 1 else: a: int = 0 b: int = 1 for i in range(2, n): temp: int = a + b a = b b = temp return b def main() -> int: print(fibonacci(10)) return 0 ``` -------------------------------- ### Python Dictionary Example Source: https://github.com/djmahe4/py2rust/blob/main/README.md Demonstrates Python dictionary manipulation. ```Python def main() -> int: scores: dict[str, int] = {"alice": 90, "bob": 85} scores["charlie"] = 95 alice_score: int = scores["alice"] print(alice_score) return 0 ``` -------------------------------- ### Python Error Handling Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Illustrates how py2rust raises an UnsupportedFeatureError with a suggestion for unsupported Python features. ```python # py2rust/frontend/parser.py:260-266 (_parse_funcdef) if arg.annotation is None: raise self._err( f"Parameter '{arg.arg}' is missing a type annotation", arg, UnsupportedFeatureError, suggestion="Add a type hint like: def f(x: int) -> int:", ) ``` -------------------------------- ### Scoped Resource Management Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Shows how Python's 'with' statement for context managers is lowered to scoped lexical blocks in Rust, utilizing RAII. ```python def read_config(path: str) -> str: # This is lowered to a scoped block, auto-closing the descriptor on drop with open(path, "r") as f: content: str = f.read() return content ``` -------------------------------- ### Sample Error Output Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Example of a formatted error message for a missing type annotation, demonstrating the caret pointer and hint. ```text UnsupportedFeatureError: example.py:3:5: Parameter 'x' is missing a type annotation | def add(x, y: int) -> int: | ^ hint: Add a type hint like: def f(x: int) -> int: ``` -------------------------------- ### State I₂ Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module3_bottom_up_parsing.md State I₂ derived from GOTO(I₀, C) in the LR(0) state construction example. ```plaintext S → C • C C → • c C C → • d ``` -------------------------------- ### Python Collections Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Demonstrates the lowering of Python collections like deque, list, and dict to their Rust equivalents. ```python from collections import deque import heapq def manage_collections() -> int: # Double-ended Queue lowering queue: deque[int] = deque([1, 2, 3]) queue.append(4) val: int = queue.popleft() # List and Dict lowering elements: list[str] = ["A", "B"] mapping: dict[str, int] = {"A": 100} return val ``` -------------------------------- ### State I₁ Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module3_bottom_up_parsing.md State I₁ derived from GOTO(I₀, S) in the LR(0) state construction example. ```plaintext S' → S • (ACCEPT) ``` -------------------------------- ### Example Record Source: https://github.com/djmahe4/py2rust/blob/main/docs/schemas/PATTERN_LEARNING_SCHEMA.md An example of a record in the patterns store. ```json { "timestamp": "2026-05-23T16:42:09.123456+00:00", "pattern_id": "int_to_float_div", "trigger_pattern": "/", "target_rust": "a / b", "replacement_rust": "a as f64 / b as f64", "evidence_count": 2, "confidence": 0.88 } ``` -------------------------------- ### CPython Library Interoperability (Plugins) Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Example of using standard CPython libraries like numpy within compiled Rust code via the --mock-mode flag and PyO3 bindings. ```python import numpy as np def calculate_mean() -> None: # Translated to PyO3 dynamic bindings arr = np.array([1.0, 2.0, 3.0]) print(np.mean(arr)) ``` -------------------------------- ### Bottom-Up Parsing Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module3_bottom_up_parsing.md A step-by-step trace of parsing the string 'id + id * id' using a bottom-up shift-reduce approach. ```text | Stack | Input | Action | |----------------|-----------------|--------| | `$` | `id + id * id$` | Shift `id` | | `$ id` | `+ id * id$` | Reduce `F → id` | | `$ F` | `+ id * id$` | Reduce `T → F` | | `$ T` | `+ id * id$` | Reduce `E → T` | | `$ E` | `+ id * id$` | Shift `+` | | `$ E +` | `id * id$` | Shift `id` | | `$ E + id` | `* id$` | Reduce `F → id` | | `$ E + F` | `* id$` | Reduce `T → F` | | `$ E + T` | `* id$` | Shift `*` (precedence: `*` > `+`) | | `$ E + T *` | `id$` | Shift `id` | | `$ E + T * id` | `$` | Reduce `F → id` | | `$ E + T * F` | `$` | Reduce `T → T * F` | | `$ E + T` | `$` | Reduce `E → E + T` | | `$ E` | `$` | **Accept** | ``` -------------------------------- ### Initial State I₀ Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module3_bottom_up_parsing.md The initial state (I₀) in the canonical collection of LR(0) item sets, derived from the example grammar. ```plaintext S' → • S S → • C C (closure of S' → • S) C → • c C (closure of S → • C C) C → • d ``` -------------------------------- ### Python Class Example Source: https://github.com/djmahe4/py2rust/blob/main/README.md Demonstrates a Python class 'Point' and its usage, translated to Rust. ```Python class Point: x: int = 0 y: int = 0 def __init__(self, x: int, y: int) -> None: self.x = x self.y = y def get_x(self) -> int: return self.x def distance_to(self, other: int) -> int: dx: int = self.x - other dy: int = self.y - 0 return dx + dy def main() -> int: p: Point = Point(3, 4) x: int = p.get_x() d: int = p.distance_to(0) return x + d ``` ```Rust struct Point { x: i32, y: i32, } impl Point { fn new(x: i32, y: i32) -> Self { Point { x, y } } fn get_x(self) -> i32 { self.x } fn distance_to(self, other: i32) -> i32 { let dx: i32 = self.x - other; let dy: i32 = self.y - 0; return dx + dy; } } fn main() -> i32 { let p: Point = Point::new(3, 4); let x: i32 = p.get_x(); let d: i32 = p.distance_to(0); return x + d; ``` -------------------------------- ### Arithmetic Grammar Left Recursion Elimination Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md An example demonstrating the elimination of left recursion from the arithmetic grammar. ```EBNF Before: After: E → E + T | T → E → T E' E' → + T E' | ε T → T * F | F → T → F T' T' → * F T' | ε F → ( E ) | id → (unchanged — no left recursion) ``` -------------------------------- ### Example Grammar for LR(0) State Construction Source: https://github.com/djmahe4/py2rust/blob/main/docs/module3_bottom_up_parsing.md A simple grammar used to demonstrate the construction of LR(0) states and the CLOSURE and GOTO operations. ```plaintext S' → S S → C C C → c C | d ``` -------------------------------- ### py2rust: IRBuilder._build_expr Source: https://github.com/djmahe4/py2rust/blob/main/docs/module4_translation_and_icg.md An example demonstrating the py2rust analogue for SDT, specifically how the IRBuilder visits an expression to synthesize an IR node. It highlights the use of inherited attributes (expected_type) and synthesized attributes (return value). ```python # py2rust/middleend/ir_builder.py def _build_expr(self, expr, expected_type=None): # 'expr' is the AST node (input) # 'expected_type' is an INHERITED attribute (passed down from parent) # The return value is the IR node (SYNTHESIZED attribute) return self._build_expr_internal(expr, expected_type) ``` -------------------------------- ### Loop Invariant Code Motion (LICM) Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module5_code_optimization_and_generation.md Demonstrates moving an invariant expression out of a loop to avoid redundant computation. ```python # Before LICM for i in range(n): x = a * b # a, b never change inside loop # After LICM x = a * b for i in range(n): pass # x is now updated without re-computation ``` -------------------------------- ### IR Assignment Node Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module4_translation_and_icg.md Example of an Intermediate Representation (IR) assignment statement node in py2rust, highlighting the inclusion of type information. ```Python # py2rust/ir/ir_nodes.py class IRAssign(IRStmt): target: str value: IRExpr target_type: IRType # This 'attribute' makes it an IR node, not just AST ``` -------------------------------- ### Common Subexpression Elimination (CSE) Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module5_code_optimization_and_generation.md Demonstrates CSE by computing an identical subexpression only once and using a temporary variable. ```python a = b * c + b * c # b * c computed twice ``` ```rust let __t0 = b * c; let a = __t0 + __t0; ``` -------------------------------- ### Python Interoperability (Numpy & OpenCV) Example Source: https://github.com/djmahe4/py2rust/blob/main/README.md Demonstrates using py2rust with external Python libraries like Numpy and OpenCV in mock mode. ```Python import numpy as np import cv2 def test_numpy() -> None: arr = np.array([1, 2, 3]) print(f"Array: {arr}") print(f"Mean: {np.mean(arr)}") def test_opencv() -> None: print(f"OpenCV Version: {cv2.__version__}") img = np.zeros((10, 10, 3)) cv2.imshow("Py2Rust OpenCV Test", img) cv2.waitKey(1) cv2.destroyAllWindows() def main() -> None: test_numpy() test_opencv() ``` -------------------------------- ### Parse Tree Representation of an Arithmetic Expression Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Visualizes the parse tree for the input '3 + 4 * 2' using the example CFG, showing operator precedence. ```plaintext Input: 3 + 4 * 2 Parse Tree (using the grammar above): E /|\ E + T | |\ T T * F | | | F F 2 | 3 ``` -------------------------------- ### Constant Folding Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/module5_code_optimization_and_generation.md Illustrates constant folding where a constant expression is evaluated at compile time. ```python # Python source x: int = 2 + 3 * 4 ``` -------------------------------- ### SemanticError Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md An example of a SemanticError indicating an undefined variable. ```text SemanticError: solver.py:5:10: Undefined variable: 'data' | print(data) | ^ ``` -------------------------------- ### The compile_file Pipeline Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md Demonstrates the six phases of the py2rust compilation process as function calls in the main script. ```python # py2rust/main.py # Phase 0: read source source = source_path.read_text() # Phase 1+2: lex + parse # (ast.parse inside, then Parser) module = parse(source, filename) ir_module = build_ir(module, filename, # Phase 3+4: semantic + IR gen source_lines, config) rust_code = generate_rust(ir_module, # Phase 5+6: optimize + codegen config=config) if config.format_output: rust_code = format_rust(rust_code) # (bonus) rustfmt post-processing output_path.write_text(rust_code) # emit target program ``` -------------------------------- ### Compiler Phases: Analysis and Synthesis Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md A table illustrating the division of compiler phases into Analysis (front-end) and Synthesis (back-end), along with their respective outputs. ```markdown | Half | Phase | Output | |------|-------|--------| | **Analysis** (front-end) | Lexical Analysis | Token stream | | | Syntax Analysis | Parse tree / AST | | | Semantic Analysis | Annotated AST | | **Synthesis** (back-end) | IR Generation | Intermediate Representation | | | Optimization | Optimized IR | | | Code Generation | Target code | ``` -------------------------------- ### TypeError Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md An example of a TypeError indicating a type mismatch when assigning a string to a variable declared as an integer. ```text TypeError: main.py:8:14: Mismatch: Cannot assign 'str' to variable declared as 'int' | val: int = "hello" | ^ ``` -------------------------------- ### UnsupportedFeatureError Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md An example of an UnsupportedFeatureError indicating the rejection of ternary expressions in Python, with a hint to use an if/else block. ```text UnsupportedFeatureError: math_utils.py:12:15: Ternary expressions (x if cond else y) are strictly rejected | val = 10 if flag else 20 | ^ hint: Replace with an explicit 'if/else' block statement ``` -------------------------------- ### Generated Rust Code Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md The Rust code generated by py2rust from the 'hello.py' example. ```rust fn greet(name: String) -> String { return format!("Hello, {}!", name); } fn main() -> i32 { let message: String = greet("World".to_string()); println!("{}", message); return 0; } ``` -------------------------------- ### Parsing a Context Manager (`with` / `async with`) Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Illustrates how `py2rust` maps `ast.With` and `ast.AsyncWith` nodes to its internal `WithStmt` AST node, recursively parsing sub-expressions and statements. ```python # py2rust/frontend/parser.py:1328-1348 def _parse_with(self, node: Union[ast.With, ast.AsyncWith]) -> WithStmt: is_async = isinstance(node, ast.AsyncWith) items = [] for item in node.items: vars_ = self._parse_expr(item.optional_vars) if item.optional_vars else None items.append( WithItem( context_expr=self._parse_expr(item.context_expr), # recurse context expression optional_vars=vars_, # recurse optional binding line=item.context_expr.lineno, col=item.context_expr.col_offset + 1, ) ) body = tuple(self._parse_stmts(node.body)) # recurse block statements return WithStmt( items=tuple(items), body=body, is_async=is_async, line=node.lineno, col=node.col_offset + 1, ) ``` -------------------------------- ### Valid Python Function Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Example of a valid Python function with mandatory type annotations. ```python # ✅ VALID def add(x: int, y: int) -> int: return x + y ``` -------------------------------- ### Invalid Python Function Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Example of an invalid Python function due to missing type annotations. ```python # ❌ INVALID def add(x, y): return x + y ``` -------------------------------- ### ast as a compiler writing tool Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md Illustrates how the `ast.parse` function from Python's standard library is used as a combined lexer and parser tool within the py2rust frontend. ```python # py2rust/frontend/parser.py:158-168 def parse(self) -> Module: try: tree = ast.parse(self.source, filename=self.filename) # except SyntaxError as e: raise ParseError( message=str(e.msg), filename=self.filename, line=e.lineno or 0, ... ) ``` -------------------------------- ### Reading Source Code in py2rust Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md Demonstrates how py2rust reads the entire source file into memory using Python's file I/O, relying on CPython and the OS for buffering. ```python # py2rust/main.py source = source_path.read_text() # OS-level buffered I/O reads whole file ``` -------------------------------- ### Suspending Coroutines Example Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Illustrates how Python generator functions with 'yield' are compiled into Rust state-machine structs implementing the Iterator trait. ```python from typing import Generator def countdown(start: int) -> Generator[int, None, None]: current: int = start while current > 0: yield current current -= 1 ``` -------------------------------- ### py2rust Project Structure Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Directory structure and key files involved in the frontend parsing and utility modules. ```tree py2rust/ ├── frontend/ │ ├── parser.py ← Recursive descent translator (the syntax analyser) │ │ ├── Parser.parse() # Start symbol dispatch │ │ ├── _parse_funcdef() # Non-terminal: FunctionDefinition │ │ ├── _parse_classdef() # Non-terminal: ClassDefinition │ │ ├── _parse_stmt() # Non-terminal: Statement (predictive table) │ │ ├── _parse_type() # Non-terminal: TypeAnnotation (left-factored) │ │ ├── _parse_expr() # Non-terminal: Expression │ │ └── _err() # Unified error reporting with caret display │ │ │ └── ast_nodes.py ← The parse tree node types (non-terminals + terminals) │ ├── IntLiteral, StrLiteral, ... # Terminal nodes (leaves) │ ├── BinOp, UnaryOp, ... # Expression non-terminal nodes │ ├── FunctionDef, ClassDef, ... # Declaration non-terminal nodes │ └── IfStmt, WhileStmt, ForRange, # Statement non-terminal nodes │ └── utils/ └── errors.py ← Error infrastructure (ParseError + UnsupportedFeatureError) ``` -------------------------------- ### py2rust Complete Phase Map Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md A Mermaid diagram visualizing the flow of a source program through the analysis and synthesis phases in the py2rust compiler. ```mermaid flowchart TD subgraph FrontEnd ["Analysis Phase (Front-end)"] direction TB A[Python Source File] -->|Lexer: CPython tokenize| B(Token Stream) B -->|Parser: frontend/parser.py| C(py2rust AST: ast_nodes.py) C -->|TypeChecker & TypeInferencer| D(Type-Annotated AST) end subgraph BackEnd ["Synthesis Phase (Back-end)"] direction TB D -->|IRBuilder: middleend/ir_builder.py| E(IR Nodes: ir_nodes.py) E -->|Mut & Hoisting Analyzers| F(Optimized IR Module) F -->|RustCodegen: backend/rust_codegen.py| G[Rust Source Code] end style FrontEnd fill:#f4f9ff,stroke:#0288d1,stroke-width:2px; style BackEnd fill:#f3fbf4,stroke:#2e7d32,stroke-width:2px; ``` -------------------------------- ### Example Record Source: https://github.com/djmahe4/py2rust/blob/main/docs/schemas/SEMANTIC_VALIDATION_SCHEMA.md An example of a record stored in the validation store. ```json { "timestamp": "2026-05-23T16:41:30.123456+00:00", "symbol_name": "calc_sum", "python_source": "def calc_sum(a, b): return a + b", "generated_rust": "fn calc_sum(a: i32, b: i32) -> i32 { a + b }", "verdict": "PASS", "confidence": 0.98, "reasoning": "Behaviorally identical.", "suggested_fix": "" } ``` -------------------------------- ### Compiler Phases Flowchart Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md A Mermaid diagram illustrating the flow from source text through lexical scanning, syntax analysis (CPython AST and py2rust AST), and semantic analysis. ```mermaid flowchart LR src[Source Text] -->|Lexical Scanning| tokens(Token Stream) tokens -->|Syntax Analysis: ast.parse| cpy_ast(CPython AST) cpy_ast -->|Translation: frontend/parser.py| custom_ast(py2rust AST) custom_ast -->|Semantic Analysis: middleend/| annotated_ast(Annotated AST / IR) style src fill:#fafafa,stroke:#333; style tokens fill:#fff3e0,stroke:#f57c00; style cpy_ast fill:#e1f5fe,stroke:#0288d1; style custom_ast fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px; style annotated_ast fill:#ede7f6,stroke:#5e35b1; ``` -------------------------------- ### Semantic Error Source: https://github.com/djmahe4/py2rust/blob/main/README.md Example of a SemanticError indicating an undefined variable. ```text SemanticError: example.py:5:10: Undefined variable: 'y' | return y | ^ ``` -------------------------------- ### Full Parsing Flow Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Diagram illustrating the two-layer parsing process from Python source string to py2rust's typed AST. ```mermaid graph TD A[Python source string] -->|ast.parse(source) ← CPython's LALR(1) parser (Layer 1)| B(ast.Module (CPython AST)) B -->|Parser.parse() ← py2rust recursive descent (Layer 2)| C(Module( functions=[FunctionDef(...), ...], classes=[ClassDef(...), ...], statements=[VarDecl(...), IfStmt(...), ...], imports=[Import(...), ...], )) ``` -------------------------------- ### py2rust Phase Map Source: https://github.com/djmahe4/py2rust/blob/main/docs/module1_intro_and_lexical_analysis.md A Mermaid diagram illustrating the complete phase map of the py2rust compiler, from Python source input to certified Rust output, including frontend, middle-end, backend, and post-processing stages. ```mermaid flowchart TD %% Base styling classDef default fill:#f9f9f9,stroke:#333,stroke-width:1px; classDef phase fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,font-weight:bold; classDef data fill:#fff3e0,stroke:#f57c00,stroke-width:1px,stroke-dasharray: 2 2; classDef check fill:#efebe9,stroke:#5d4037,stroke-width:2px; classDef validation fill:#ede7f6,stroke:#5e35b1,stroke-width:2px; %% Nodes PySrc[("Python Source File (.py)")]:::data subgraph FrontEnd ["Frontend (Lexical & Syntax Analysis)"] Parser[Parser / frontend/parser.py]:::phase AST[py2rust AST / frontend/ast_nodes.py]:::data PySrc -->|ast.parse / CPython Lexer & Parser| Parser Parser -->|_parse_stmt / _parse_expr / _parse_type| AST end subgraph MiddleEnd ["Middle-end (Semantic Analysis & Type Checking)"] ImportRes[ImportResolver / sys.path Boundary Enforcement]:::check CycleDet[Circular Dependency & Struct Cycle Detection]:::check SymTable[(CrossModuleSymbolTable)] TypeInf[TypeInferencer / type_inferencer.py]:::phase TypeChk[TypeChecker / type_checker.py]:::phase TypedAST[Type-Annotated Custom AST]:::data AST --> ImportRes ImportRes -->|Cross-Module Resolution| SymTable SymTable --> TypeInf TypeInf --> CycleDet CycleDet --> TypeChk TypeChk --> TypedAST end subgraph BackEnd ["Backend (IR Generation & Code Generation)"] IRBuilder[IRBuilder / middleend/ir_builder.py]:::phase IRNodes[IR Nodes / ir/ir_nodes.py]:::data MutTracker[Mutability & Decls Collector]:::check RustGen[RustCodegen / backend/rust_codegen.py]:::phase RawRust[("Raw Rust Source code (.rs)")]:::data TypedAST --> IRBuilder IRBuilder --> IRNodes IRNodes --> MutTracker MutTracker -->|let mut / hoisting analysis| RustGen RustGen --> RawRust end subgraph Post ["Verification & Post-Processing"] RustFmt[rustfmt Formatting]:::phase CargoChk[cargo check Compilation Validator]:::phase EquivVal[Semantic Equivalence Validator / Ollama / patterns.jsonl]:::validation RustOut[("Final Certified Rust Executable / Library (.rs)")]:::data RawRust --> RustFmt RustFmt --> CargoChk CargoChk -->|Pass| EquivVal EquivVal -->|Learn Patterns & Certify| RustOut end ``` -------------------------------- ### Unsupported Feature Error Source: https://github.com/djmahe4/py2rust/blob/main/README.md Example of an UnsupportedFeatureError indicating that keyword arguments are not supported. ```text UnsupportedFeatureError: example.py:3:1: Keyword arguments not supported | def foo(x=1) | ^ hint: Use positional arguments instead ``` -------------------------------- ### Context Managers (`with`/`as`) Grammar Rules Source: https://github.com/djmahe4/py2rust/blob/main/docs/module3_bottom_up_parsing.md Grammar rules for context managers, highlighting the optional 'as target' clause. ```text WithStmt -> 'with' WithItemList ':' Suite WithItemList -> WithItem | WithItem ',' WithItemList WithItem -> Expr | Expr 'as' Target ``` -------------------------------- ### Recursive Descent Method Inventory Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Inventory of methods in the py2rust Parser class, demonstrating recursive descent. ```python # parser.py — Recursive Descent method inventory class Parser: def parse(self) # → Module (start symbol) def _parse_funcdef(...) # → FunctionDef def _parse_classdef(...) # → ClassDef def _parse_class_body(...) # → list[stmt] def _parse_type(...) # → TypeAnnotation def _parse_stmt(...) # → Statement def _parse_for(...) # → ForRange | ForIter def _parse_expr(...) # → Expression def _parse_lambda(...) # → LambdaExpr def _parse_comprehension(.) # → Comprehension def _parse_match(...) # → MatchStmt def _parse_pattern(...) # → MatchPattern def _parse_with(...) # → WithStmt def _parse_assert(...) # → AssertStmt def _parse_global(...) # → GlobalStmt def _parse_import(...) # → Import def _parse_import_from(...) # → ImportFrom ``` -------------------------------- ### Ambiguous Arithmetic Grammar Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md A classic example of an ambiguous grammar for arithmetic expressions. ```EBNF E → E + E | E * E | id # AMBIGUOUS ``` -------------------------------- ### Python vs. Rust Condition Handling Source: https://github.com/djmahe4/py2rust/blob/main/docs/module5_code_optimization_and_generation.md Demonstrates the difference in truthiness between Python (any non-zero/non-empty is truthy) and Rust (requires explicit boolean expressions), and how py2rust handles this. ```Python # Python if x: # Any non-zero, non-empty value is truthy ... ``` ```Rust // Rust if x != 0 { # Must be explicit ... } ``` -------------------------------- ### Compile to Rust Command Source: https://github.com/djmahe4/py2rust/blob/main/docs/user_guide.md Command to compile a Python file to Rust using py2rust. ```bash py2rust hello.py -o hello.rs ``` -------------------------------- ### Early Rejection of Ternary Expressions (`ast.IfExp`) Source: https://github.com/djmahe4/py2rust/blob/main/docs/module2_syntax_analysis.md Shows how `py2rust`'s `_parse_expr` immediately raises an error when encountering an `ast.IfExp` node to enforce structured control flow, preventing further processing. ```python # py2rust/frontend/parser.py:1117-1120 if isinstance(node, ast.IfExp): raise self._err( "Ternary expressions are not supported", node, UnsupportedFeatureError ) ``` -------------------------------- ### Multi-Module Environment & Cross-Module Type Resolution Flowchart Source: https://github.com/djmahe4/py2rust/blob/main/docs/module4_translation_and_icg.md A Mermaid flowchart illustrating the process of resolving types across different modules in a multi-module environment, from project configuration to IR builder queries. ```mermaid flowchart TD %% Config & Resolver PC[ProjectConfig] -->|Defines sys.path & Entrypoints| IR[ImportResolver] IR -->|Scans imports & resolves modules| CMS[(CrossModuleSymbolTable)] %% Tables & Modules subgraph ModuleTable ["Cross-Module Symbol Table Architecture"] CMS -->|Tracks symbol scopes| M1[Module: math_utils] CMS -->|Tracks symbol scopes| M2[Module: main] M1 -->|Exports| SymF[Function: add_ints] SymF -->|Has inferred type| EType[ExternalPythonType: Fn int, int -> int] M2 -->|Imports add_ints| ImportNode[ImportRef: math_utils.add_ints] ImportNode -->|Resolves signature| EType end %% IR Builder IRBuilder[IRBuilder / ir_builder.py] -->|Queries resolved types| CMS IRBuilder -->|Constructs| TypedIR[Type-Annotated IRModule] style CMS fill:#ede7f6,stroke:#5e35b1,stroke-width:2px; style EType fill:#fff3e0,stroke:#f57c00; style TypedIR fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px; ```