RL-Optimized Source to Source Compiler

Custom language → optimized Python via a 7-stage Q-learning pipeline.

Note: Deployed on Render free tier — initial run may take ~15s to wake up the server.

Source Code

Stdin

One value per line — consumed by scan() calls.

Compilation Pipeline

Ready
Stage 01

Lexical Token Stream

0 Tokens
# Token Category Lexeme Location
Run pipeline to inspect lexical token stream…
Stage 02

Abstract Syntax Tree (AST)

Hierarchical Syntax
Drag to pan • Scroll to zoom

Run pipeline to generate interactive AST tree…

Stage 03

Semantic Verification

Scoped Validation
✓

Scope & Reference Analysis

Checks variable definitions, scope boundaries, and assignment validity.

Run pipeline to run semantic validation…
Stage 04

Three-Address Code (TAC)

0 Instructions
Run pipeline to generate Three-Address Code…
Stage 05

Q-Learning Optimization Engine

0 Optimizations
Original IR 0
Optimized IR 0
Reduction 0%
Agent Actions 0
RL Agent Policy Decisions
Run pipeline to inspect agent policy actions…
Optimized Three-Address Code
Optimized IR will display here…
Stage 06

Target Python Code

Python 3.10 Target
Run pipeline to generate executable Python…
Stage 07

Execution Environment

— Ready
sandboxed-runtime :: python3.10 EXIT 0
Standard Output:
Ready. Press 'Run' (Ctrl+Enter) to compile and execute.

RL-Optimized Source to Source Compiler Overview

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.

  • Syntax Convention: C-like procedural syntax; statements terminate with semicolons (;); blocks are delimited by curly braces ({ }).
  • Dynamic Typing: Numerical literals are treated as double-precision floating point; strings are first-class immutable sequences.
  • Guaranteed Termination: Sandboxed execution engine with daemon thread isolation and a 5.0 s watchdog timer preventing CPU hangs or infinite loops.

Language Specifications & Inventory

A rigorous inventory of all primitive data types, keywords, operators, delimiters, and lexical token categories supported by the compiler:

2
Data Types
5
Keywords
17
Operators
5
Delimiters
8
Token Categories
32
Token Types

1. Data Types (2 Supported Types)

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.

2. Reserved Keywords (5 Keywords)

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.

3. Lexical Token Categories (8 Categories / 32 Token Types)

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)

Formal Grammar Specification (EBNF)

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 ")"

The 7-Stage Compilation Pipeline

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 & Scoping

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.

Basic assignment

x = 10;
name = "Alice";
print(x);
print(name);

Output

10
Alice

Compound in-place assignment

The language supports shorthand arithmetic accumulation operators (+=, -=, *=, /=):

x = 5;
x += 3;
x -= 1;
print(x);

Output

7

Expressions & Mathematics

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);

Output

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).

Control Flow

Conditional Branching: if / else

Conditional 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");
}

Output

Adult

Iteration: while loops

Loops compile into back-edge jumps with guard conditions evaluated at each cycle iteration:

i = 1;
while (i <= 5) {
    print(i);
    i += 1;
}

Output

1
2
3
4
5

Input & Output

Interactive programs can prompt and consume inputs from the user via the scan() builtin:

print("Enter a number:");
scan(n);
print(n * 2);

Output (stdin: 7)

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.

Operator Reference

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.

Reinforcement Learning Optimization Engine

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:

  • State Representation: Fingerprint of surrounding instruction opcodes within a window of position ±1, combined with variable live-range status.
  • Action Space:
    • 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 Formulation: Reward = (+10 × removed_instructions) + (+5 × folded_constants) − (20 × code_growth)
  • Exploration vs Exploitation: The agent follows an ε-greedy policy with an exponential decay schedule (×0.99 per optimization pass) to balance discovering new rewrite patterns and exploiting proven reduction paths.

Security & Sandboxing Guarantees

  • Thread & Process Isolation: Target Python execution runs inside an isolated daemon thread with a strict 5000 ms watchdog. Infinite loops and recursive lockups are terminated automatically.
  • Namespace Scrubbing: Dangerous builtins including os, subprocess, open, eval, exec, sys, and all module import mechanisms (__import__) are stripped from the sandbox execution environment.
  • Safe Division: Every division operation compiles with a non-zero guard to guarantee immunity against unhandled ZeroDivisionError crash conditions.
  • Recursion Guard: The compiler raises the system recursion limit to 10 000 during AST analysis and restores baseline defaults immediately after completion.

Keyboard Shortcuts & Pro Tips

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.