import dis
import types
import time
import sys
from enum import Enum, auto
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set, Tuple
# ==========================================
# 1. The DSL Definition (AST)
# ==========================================
class NodeType(Enum):
Number = auto()
String = auto()
Variable = auto()
BinOp = auto()
Call = auto()
Function = auto()
Return = auto()
Block = auto()
@dataclass
class Node:
type: NodeType
value: Any = None
children: List['Node'] = field(default_factory=list)
name: str = "" # Used for Variable names and Function names
# ==========================================
# 2. Runtime System & Profiling
# ==========================================
class DeoptException(Exception):
"""Thrown when optimized code invalidates assumptions."""
def __init__(self, pc, stack_state):
self.pc = pc
self.stack_state = stack_state
class TypeFeedback:
"""Accumulates types seen during interpretation."""
def __init__(self):
self.types_seen: Set[type] = set()
def record(self, val):
self.types_seen.add(type(val))
def is_stable(self) -> bool:
return len(self.types_seen) == 1
def get_monotype(self) -> Optional[type]:
if self.is_stable():
return list(self.types_seen)[0]
return None
class DebugHook:
@staticmethod
def on_tier_change(tier, node):
print(f"[DEBUG] Transitioning to {tier} for function '{node.name}'")
# ==========================================
# 3. The Interpreter (Tier 0)
# ==========================================
class Interpreter:
def __init__(self):
self.global_functions: Dict[str, Node] = {}
self.call_stack = []
# Profiling data: Key = (function_name, var_name/node_id)
self.type_feedback: Dict[str, TypeFeedback] = {}
def run(self, node: Node, local_env: dict) -> Any:
# 1. Execute
result = self._eval(node, local_env)
# 2. Profile
# We profile the result of expressions.
# In a real JIT, we'd profile locals/operands specifically.
# Here we map it to the node's name or ID for simplicity.
return result
def _eval(self, node: Node, env: dict) -> Any:
if node.type == NodeType.Number:
return node.value
elif node.type == NodeType.String:
return node.value
elif node.type == NodeType.Variable:
val = env.get(node.name, 0)
# Record type usage
if node.name not in self.type_feedback:
self.type_feedback[node.name] = TypeFeedback()
self.type_feedback[node.name].record(val)
return val
elif node.type == NodeType.BinOp:
left = self._eval(node.children[0], env)
right = self._eval(node.children[1], env)
# Profile operands
op_key = f"op_{id(node)}"
if op_key not in self.type_feedback:
self.type_feedback[op_key] = TypeFeedback()
self.type_feedback[op_key].record(left)
self.type_feedback[op_key].record(right)
if node.value == '+':
return left + right
elif node.value == '*':
return left * right
elif node.type == NodeType.Call:
# Function Lookup
func_name = node.name
args = [self._eval(arg, env) for arg in node.children]
# Call Count for Heuristics
key = f"call_{func_name}"
if key not in self.type_feedback:
self.type_feedback[key] = TypeFeedback() # Abuse TypeFeedback as a counter
# Reusing the set to count calls isn't clean but works for demo
# Real JITs use integer counters.
func_def = self.global_functions[func_name]
new_env = {}
for i, param in enumerate(func_def.children[0].children): # children[0] is params
new_env[param.name] = args[i]
return self._eval(func_def.children[1], new_env) # children[1] is body
elif node.type == NodeType.Return:
return self._eval(node.children[0], env)
elif node.type == NodeType.Block:
res = None
for child in node.children:
res = self._eval(child, env)
return res
return None
# ==========================================
# 4. JIT Compiler (Tier 1 & 2)
# ==========================================
class JITCompiler:
def __init__(self, interpreter):
self.interpreter = interpreter
self.compiled_functions = {} # Map name -> (callable, tier)
self.tier_thresholds = {
'baseline': 10,
'optimized': 100
}
self.call_counts = {} # Specific counter for calls
def get_callable(self, func_node: Node):
name = func_node.name
# Update Call Count
self.call_counts[name] = self.call_counts.get(name, 0) + 1
count = self.call_counts[name]
# Check Tiers
if name in self.compiled_functions:
code, tier = self.compiled_functions[name]
# If already optimized, just return
if tier == 'OPTIMIZED': return code
# Promote Baseline -> Optimized
if tier == 'BASELINE' and count > self.tier_thresholds['optimized']:
DebugHook.on_tier_change("TIER 2 (Optimized)", func_node)
opt_code = self._compile_optimized(func_node)
self.compiled_functions[name] = (opt_code, 'OPTIMIZED')
return opt_code
# Compile Baseline (Tier 1)
if count > self.tier_thresholds['baseline'] and name not in self.compiled_functions:
DebugHook.on_tier_change("TIER 1 (Baseline)", func_node)
code = self._compile_baseline(func_node)
self.compiled_functions[name] = (code, 'BASELINE')
return code
# Fallback to Interpreter
return None
# --- TIER 1: Naive Compilation (Generic Python Bytecode) ---
def _compile_baseline(self, func_node: Node):
# This simulates generating unoptimized native code.
# We generate a generic Python function that handles all types.
# Extract parameter names
params = [p.name for p in func_node.children[0].children]
# We compile the logic into a recursive structure that mimics the AST
# but without the overhead of the Interpreter dispatch loop.
def generated_func(*args):
env = dict(zip(params, args))
return self._run_ast(func_node.children[1], env)
return generated_func
def _run_ast(self, node, env):
# A direct AST walker, faster than the full Interpreter class dispatch
if node.type == NodeType.Number: return node.value
if node.type == NodeType.String: return node.value
if node.type == NodeType.Variable: return env[node.name]
if node.type == NodeType.Return: return self._run_ast(node.children[0], env)
if node.type == NodeType.BinOp:
l = self._run_ast(node.children[0], env)
r = self._run_ast(node.children[1], env)
if node.value == '+': return l + r
if node.value == '*': return l * r
if node.type == NodeType.Call:
args = [self._run_ast(c, env) for c in node.children]
# Recursive call into JIT infrastructure
target = self.interpreter.global_functions[node.name]
callable_fn = self.get_callable(target)
if callable_fn: return callable_fn(*args)
return self.interpreter.run(target, dict(zip([p.name for p in target.children[0].children], args)))
if node.type == NodeType.Block:
res = None
for c in node.children: res = self._run_ast(c, env)
return res
# --- TIER 2: Optimized Compilation (Speculative) ---
def _compile_optimized(self, func_node: Node):
# 1. Analyze Profiling Data
feedback = self.interpreter.type_feedback
assumptions = {}
# Heuristic: If variable usage was stable, assume types.
for var_name, fb in feedback.items():
if fb.is_stable():
assumptions[var_name] = fb.get_monotype()
# 2. Inlining Heuristic
# If a function is small and called often, inline it.
# (Simplified here: We just generate code that assumes specific types)
params = [p.name for p in func_node.children[0].children]
# Generate specialized code
def optimized_func(*args):
env = dict(zip(params, args))
# Deoptimization Check (Guards)
# We check if the arguments match the types seen during profiling.
# Note: In a real JIT, we'd check *every* variable usage and result.
for param_name, val in env.items():
key = param_name
if key in assumptions:
expected_type = assumptions[key]
if not isinstance(val, expected_type):
# DEOPTIMIZATION!
# We failed the assumption. Return a special marker
# or throw an exception to be caught by the trampoline.
print(f"[JIT] DEOPT: Assumption failed for {param_name}. Expected {expected_type}, got {type(val)}")
raise DeoptException(pc=0, stack_state=env)
# Execute optimized logic (Type Specialized)
# Here we use the generic runner for brevity, but in a real compiler
# we would generate assembly using only integer ADD instructions
# (no type checks inside the loop).
return self._run_optimized_ast(func_node.children[1], env, assumptions)
return optimized_func
def _run_optimized_ast(self, node, env, assumptions):
# In a real compiler, this would be raw assembly or LLVM IR.
# We simulate the speed by removing type checks (conceptually).
# We still use Python logic here, but assume types are stable.
if node.type == NodeType.Number: return node.value
if node.type == NodeType.Variable: return env[node.name]
if node.type == NodeType.Return: return self._run_optimized_ast(node.children[0], env, assumptions)
if node.type == NodeType.BinOp:
l = self._run_optimized_ast(node.children[0], env, assumptions)
r = self._run_optimized_ast(node.children[1], env, assumptions)
# Optimized logic: Fast path for Integers
# (Simulating direct CPU addition)
op_key = f"op_{id(node)}"
if op_key in assumptions and assumptions[op_key] == int:
# In a real JIT: add rax, rbx
return l + r
else:
# Fallback generic path
if node.value == '+': return l + r
if node.value == '*': return l * r
# ... (Handling other nodes omitted for brevity)
return self._run_ast(node, env) # Fallback for unhandled nodes in optimized path
# ==========================================
# 5. Execution Wrapper
# ==========================================
class System:
def __init__(self):
self.interpreter = Interpreter()
self.jit = JITCompiler(self.interpreter)
def execute(self, func_node: Node, args: list):
# Register function
self.interpreter.global_functions[func_node.name] = func_node
# Run Loop
result = None
count = 0
print(f"--- Starting execution of {func_node.name} ---")
while count < 200:
# 1. Try JIT
jit_code = self.jit.get_callable(func_node)
if jit_code:
try:
result = jit_code(*args)
except DeoptException as e:
# Deoptimization Logic
# We drop the compiled code and fallback to interpreter
print("[System] Reverting to Interpreter (Deoptimizing)...")
if func_node.name in self.jit.compiled_functions:
del self.jit.compiled_functions[func_node.name]
# Recover state from exception
# In a real system, we remap e.stack_state to interpreter frames
result = self.interpreter.run(func_node, e.stack_state)
else:
# Fallback to Interpreter
param_names = [p.name for p in func_node.children[0].children]
local_env = dict(zip(param_names, args))
result = self.interpreter.run(func_node, local_env)
count += 1
if count % 50 == 0: print(f"Executed {count} iterations...")
print(f"Final Result: {result}")
return result
# ==========================================
# 6. Test Program
# ==========================================
# def add(a, b) { return a + b; }
param_a = Node(NodeType.Variable, name="a")
param_b = Node(NodeType.Variable, name="b")
params_node = Node(NodeType.Block, children=[param_a, param_b])
# return a + b;
body_expr = Node(NodeType.BinOp, value='+', children=[
Node(NodeType.Variable, name="a"),
Node(NodeType.Variable, name="b")
])
return_stmt = Node(NodeType.Return, children=[body_expr])
body_node = Node(NodeType.Block, children=[return_stmt])
add_func = Node(NodeType.Function, name="add", children=[params_node, body_node])
# ==========================================
# 7. Run Scenarios
# ==========================================
system = System()
print("\nSCENARIO 1: Stable Types (Integer Arithmetic)")
# Run 200 times with integers.
# Should Tier up to Optimized and stay there.
system.execute(add_func, [10, 20])
print("\nSCENARIO 2: Type Instability (Triggering Deopt)")
# We reset the system to simulate a new runtime
system = System()
# Run a mix. This usually stays in interpreter or baseline unless we reset counters.
# To force deopt, we first train it with ints, then send a string.
# Train with Integers
for _ in range(120):
system.execute(add_func, [5, 5]) # Triggers Optimized
# Violate Assumption
print("\n[TEST] Sending String to Optimized Code...")
system.execute(add_func, ["Hello ", "World"])