Custom language → optimized Python via a 7-stage Q-learning pipeline.
One value per line — consumed by scan() calls.
| # | Token Category | Lexeme | Location |
|---|---|---|---|
| Run pipeline to inspect lexical token stream… | |||
Checks variable definitions, scope boundaries, and assignment validity.
Run pipeline to run semantic validation…
Run pipeline to generate Three-Address Code…
Run pipeline to inspect agent policy actions…
Optimized IR will display here…
Run pipeline to generate executable Python…
Ready. Press 'Run' (Ctrl+Enter) to compile and execute.
RL-Optimized Source to Source Compiler is an end-to-end imperative source-to-source compilation framework paired with a tabular Reinforcement Learning Q-learning agent. The compiler translates a custom C-like procedural source language into rigorously optimized Python 3 source code.
Unlike conventional optimizing compilers that depend on fragile, hardcoded heuristics or fixed phase orderings, this system uses an autonomous RL agent that inspects intermediate Three-Address Code (TAC) and applies optimal sequences of program transformations to minimize instruction count and execution latency while preserving semantic equivalence.
;); blocks are delimited by curly braces ({ }).A rigorous inventory of all primitive data types, keywords, operators, delimiters, and lexical token categories supported by the compiler:
| Data Type | Syntax / Format | Description & Behavior | Target Mapping |
|---|---|---|---|
Number |
42, -10, 3.14159 |
64-bit IEEE 754 floating point. Integers and decimal fractions are unified; integer values format cleanly without trailing decimal zeros on output. | Python float / int |
String |
"..." or '...' |
Immutable UTF-8 textual character sequences supporting standard escape characters (\n, \t, \", \', \\). |
Python str |
Boolean Representation: Logical and relational operations evaluate to numerical 1 (True) and 0 (False). Branching constructs evaluate truthiness using non-zero value semantics.
| Keyword | Category | Signature / Usage | Semantics |
|---|---|---|---|
print |
I/O Statement | print(expression); |
Serializes expression value to the standard output buffer with a trailing newline. |
scan |
I/O Statement | scan(identifier); |
Consumes a line from standard input, parses as a float, and stores into the target variable. |
while |
Control Flow | while (cond) { ... } |
Guarded pre-test iterative loop executing block while condition evaluates non-zero. |
if |
Control Flow | if (cond) { ... } |
Conditional branching construct executed when condition evaluates non-zero. |
else |
Control Flow | else { ... } |
Paired alternative branch executed when the preceding if condition evaluates to zero. |
| Token Category | Count | Enum Variants (TokenType) & Matching Patterns |
|---|---|---|
| Literals | 3 | NUMBER (decimal / integer digits), STRING (quoted text), IDENTIFIER (names matching [a-zA-Z_][a-zA-Z0-9_]*) |
| Keywords | 5 | PRINT, SCAN, WHILE, IF, ELSE |
| Arithmetic Operators | 5 | PLUS (+), MINUS (-), MULTIPLY (*), DIVIDE (/), MODULO (%) |
| Assignment Operators | 3 | ASSIGN (=), PLUS_ASSIGN (+=), MINUS_ASSIGN (-=) |
| Comparison Operators | 6 | EQUAL (==), NOT_EQUAL (!=), GREATER (>), LESS (<), GREATER_EQUAL (>=), LESS_EQUAL (<=) |
| Logical Operators | 3 | AND (&&), OR (||), NOT (!) |
| Delimiters & Punctuation | 5 | LPAREN ((), RPAREN ()), LBRACE ({), RBRACE (}), SEMICOLON (;) |
| Stream & Whitespace | 2 | NEWLINE (\n), EOF (end of input stream) |
The language syntax is formally specified below in Extended Backus-Naur Form (EBNF). The recursive descent parser processes tokens deterministically with LL(1) lookahead:
| Non-Terminal | Production Rule (EBNF) |
|---|---|
Program |
{ Statement } EOF |
Statement |
AssignStmt | IfStmt | WhileStmt | PrintStmt | ScanStmt | Block |
AssignStmt |
IDENTIFIER ( "=" | "+=" | "-=" ) Expr ";" |
IfStmt |
"if" "(" Expr ")" Block [ "else" Block ] |
WhileStmt |
"while" "(" Expr ")" Block |
PrintStmt |
"print" "(" Expr ")" ";" |
ScanStmt |
"scan" "(" IDENTIFIER ")" ";" |
Block |
"{" { Statement } "}" |
Expr |
LogicalOr |
LogicalOr |
LogicalAnd { "||" LogicalAnd } |
LogicalAnd |
Equality { "&&" Equality } |
Equality |
Relational { ( "==" | "!=" ) Relational } |
Relational |
Additive { ( "<" | "<=" | ">" | ">=" ) Additive } |
Additive |
Multiplicative { ( "+" | "-" ) Multiplicative } |
Multiplicative |
Unary { ( "*" | "/" | "%" ) Unary } |
Unary |
( "!" | "-" ) Unary | Primary |
Primary |
NUMBER | STRING | IDENTIFIER | "(" Expr ")" |
Every source program flows sequentially through 7 decoupled compilation stages, each exposing verifiable intermediate states:
| Stage | Phase Name | Responsibilities & Invariants |
|---|---|---|
Stage 01 |
Lexical Analysis | DFA tokenizer converts raw UTF-8 source into a structured token stream with precise line and column coordinate tagging. |
Stage 02 |
Syntax Parsing | Recursive descent LL(1) parser verifies formal grammar and generates an Abstract Syntax Tree (AST) with precedence climbing. |
Stage 03 |
Semantic Analysis | Validates lexical scoping hierarchies, ensures variables are initialized prior to reference, and builds symbol scope chains. |
Stage 04 |
Three-Address Code | Lowers the AST into linear quadruples with explicit control flow labels (L1..Ln) and virtual temporaries (t0..tn). |
Stage 05 |
RL Optimization | A tabular Q-learning agent iteratively rewires and simplifies the TAC stream to minimize bytecode instructions. |
Stage 06 |
Target Code Gen | Translates optimized TAC into clean, idiomatic Python code with zero-division guards and clean execution wrappers. |
Stage 07 |
Runtime Execution | Runs target code inside a secure sandboxed thread with isolated stdin pipes, watchdog killswitches, and stdout capture. |
Variables are implicitly declared upon their first assignment. The semantic analysis stage builds a scoped symbol table that verifies variables are defined before they are referenced.
x = 10; name = "Alice"; print(x); print(name);
10 Alice
The language supports shorthand arithmetic accumulation operators (+=, -=, *=, /=):
x = 5; x += 3; x -= 1; print(x);
7
Arithmetic expressions follow standard mathematical operator precedence (*, /, and % bind tighter than + and -):
a = 10; b = 3; print(a + b); print(a - b); print(a * b); print(a / b); print(a % b);
13 7 30 3.3333333333333335 1
Division & Modulo Zero-Check Protection: To eliminate fatal runtime exceptions in critical execution loops, target code wraps divisions and modulos in zero-guard ternaries: (a / b if b != 0 else 0) and (a % b if b != 0 else 0).
if / elseConditional branches evaluate boolean expressions and generate conditional jumps (IF_FALSE) in the TAC intermediate layer:
age = 20;
if (age >= 18) {
print("Adult");
} else {
print("Minor");
}
Adult
while loopsLoops compile into back-edge jumps with guard conditions evaluated at each cycle iteration:
i = 1;
while (i <= 5) {
print(i);
i += 1;
}
1 2 3 4 5
Interactive programs can prompt and consume inputs from the user via the scan() builtin:
print("Enter a number:");
scan(n);
print(n * 2);
Enter a number: 14.0
scan(var) consumes the next line from standard input and parses it as a float. Input values can be prepared in the Stdin text area on the workspace, separated by newlines.
| Category | Operators | Semantics & Precedence |
|---|---|---|
| Arithmetic | + - * / % |
Standard addition, subtraction, multiplication, floating-point division, and modulo remainder. |
| Relational | == != < > <= >= |
Evaluates to 1 (True) or 0 (False). |
| Logical | && || ! |
Short-circuit logical AND, logical OR, and logical NOT. |
| Assignment | = += -= |
Variable assignment and compound accumulation (target must be defined). |
| Delimiters | ( ) { } ; |
Expression grouping, block scope delimiters, and statement terminators. |
The optimizer models program optimization as a Markov Decision Process (MDP) over the Three-Address Code intermediate representation. At each instruction index, the tabular Q-learning agent evaluates local opcode contexts and selects transformation actions:
constant_folding: Replaces expressions of known constants with precomputed scalar values.dead_code_elimination: Prunes assignments to variables that are overwritten before being read.common_subexpression: Deduplicates identical computations and reuses previously computed temporaries.algebraic_simplification: Simplifies identity operations such as x + 0, x * 1, and x * 0.loop_invariant_motion: Hoists computations independent of loop variables outside the loop header.Reward = (+10 × removed_instructions) + (+5 × folded_constants) − (20 × code_growth)
os, subprocess, open, eval, exec, sys, and all module import mechanisms (__import__) are stripped from the sandbox execution environment.ZeroDivisionError crash conditions.| Shortcut | Action Description |
|---|---|
| Ctrl + Enter | Compile & Run: Triggers the full 7-stage compilation pipeline and executes the target binary. |
| Ctrl + / | Toggle Comment: Toggles single-line // comments on the active editor cursor line. |
| Alt + ← | Previous Stage: Steps backward to the previous compilation stage in the horizontal stepper. |
| Alt + → | Next Stage: Steps forward to the next compilation stage in the horizontal stepper. |
Focused / All Stages |
Use the top toggle in the pipeline deck to switch between focused single-stage inspection and a continuous vertical overview. |