Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
691 changes: 691 additions & 0 deletions ChironCore/BallLarus/ballLarus.py

Large diffs are not rendered by default.

162 changes: 162 additions & 0 deletions ChironCore/BallLarus/bl_interpreter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
from interpreter import ConcreteInterpreter, Interpreter, ProgramContext, addContext
from ChironAST import ChironAST
from ChironHooks import Chironhooks
import os

class BallLarusInterpreter(ConcreteInterpreter):
"""
A specialized interpreter that extends ConcreteInterpreter with Ball-Larus path profiling.
It preserves all original functionality while adding support for PrintCommand, IncrementCommand,
and DumpCommand instructions.
"""

def __init__(self, irHandler, params,predictor_hashMap = {}, is_bl_op = False, is_training=False):
super().__init__(irHandler, params)
# Initialize the hashMap for path register tracking
self.hashMap = {}
self.predictor = predictor_hashMap
self.bl_op = is_bl_op
self.isTraining = is_training
self.total_cnt = 0
self.correct_cnt = 0
def interpret(self):
"""
Executes one instruction at the current program counter. Returns True when the program finishes,
False otherwise.
"""
print("Program counter : ", self.pc)
stmt, tgt = self.ir[self.pc]
print(stmt, stmt.__class__.__name__, tgt)

self.sanityCheck(self.ir[self.pc])

if isinstance(stmt, ChironAST.AssignmentCommand):
ntgt = self.handleAssignment(stmt, tgt)
elif isinstance(stmt, ChironAST.ConditionCommand):
if self.bl_op:
ntgt = self.handleCondition_bl(stmt, tgt)
else:
ntgt = self.handleCondition(stmt, tgt)
elif isinstance(stmt, ChironAST.MoveCommand):
ntgt = self.handleMove(stmt, tgt)
elif isinstance(stmt, ChironAST.PenCommand):
ntgt = self.handlePen(stmt, tgt)
elif isinstance(stmt, ChironAST.GotoCommand):
ntgt = self.handleGotoCommand(stmt, tgt)
elif isinstance(stmt, ChironAST.NoOpCommand):
ntgt = self.handleNoOpCommand(stmt, tgt)
elif isinstance(stmt, ChironAST.PrintCommand):
ntgt = self.handlePrintCommand(stmt, tgt)
elif isinstance(stmt, ChironAST.IncrementCommand):
ntgt = self.handleIncrementCommand(stmt, tgt)
elif isinstance(stmt, ChironAST.DumpCommand):
ntgt = self.handleDumpCommand(stmt, tgt)
else:
raise NotImplementedError("Unknown instruction: %s, %s." % (type(stmt), stmt))

self.pc += ntgt

if self.pc >= len(self.ir):
# This is the ending of the interpreter.
if self.bl_op and self.isTraining == False:
with open("predictor_accuracy.txt", "a") as f:
f.write(f"Total Count: {self.total_cnt}\n")
f.write(f"Correct Count: {self.correct_cnt}\n")
f.write(f"Accuracy: {self.correct_cnt / self.total_cnt if self.total_cnt > 0 else 0}\n")
f.write("-----------------------\n")

with open("predictions_pc.txt", "a") as f:
f.write("-------------------------\n")
f.write("\n")

self.trtl.write("End, Press ESC", font=("Arial", 15, "bold"))
if self.args is not None and self.args.hooks:
self.chironhook.ChironEndHook(self)
return True
else:
return False

def handleCondition_bl(self, stmt, tgt):
print(" Branch Instruction")
condstr = addContext(stmt)
exec("self.cond_eval = %s" % (condstr))
exprStr = addContext(":blPathRegister")
path_reg_val = eval(exprStr)
if(self.isTraining):
if self.cond_eval:
self.predictor[(path_reg_val, self.pc)] = self.predictor.get((path_reg_val, self.pc), 0) + 1
else:
self.predictor[(path_reg_val, self.pc)] = self.predictor.get((path_reg_val, self.pc), 0) - 1
else:
self.total_cnt += 1
predictor_val = self.predictor.get((path_reg_val, self.pc), 0)
prediction = "Taken" if predictor_val >= 0 else "Not Taken"
actual = "Taken" if self.cond_eval else "Not Taken"
is_correct = False
if predictor_val >= 0 and self.cond_eval:
self.correct_cnt += 1
is_correct = True
elif predictor_val < 0 and not self.cond_eval:
self.correct_cnt += 1
is_correct = True
with open("predictions_pc.txt","a") as f:
f.write(f"PC: {self.pc}, Prediction: {prediction}, Actual: {actual}, Correct: {is_correct}\n")
return 1 if self.cond_eval else tgt

def handlePrintCommand(self, stmt, tgt):
"""
Handles a PrintCommand by evaluating the expression and writing the result to print_output.txt.
"""
print(" PrintCommand")
# Convert the expression to a string that can be evaluated
exprStr = addContext(stmt.expr)
# Evaluate the expression in the current program context
result = eval(exprStr)
# Dump the result to a file instead of printing to the console
with open("print_output.txt", "a") as f:
f.write(str(exprStr) + " = " + str(result) + "\n")
return 1

def handleIncrementCommand(self, stmt, tgt):
"""
Handles an IncrementCommand by incrementing the value for the specified key in the hashMap.
"""
print(" IncrementCommand")
exprStr = addContext(stmt.var)
key = eval(exprStr)
current_value = self.hashMap.get(key, 0)
self.hashMap[key] = current_value + 1
return 1

def handleDumpCommand(self, stmt, tgt):
"""
Merge current self.hashMap into hash_dump.txt:
- For keys already in the file, add the new count.
- For new keys, append them.
"""
print(" DumpCommand")
dump_file = "hash_dump.txt"

# 1) Load existing counts from disk (if the file exists)
existing = {}

if os.path.exists(dump_file):
with open(dump_file, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
# Expect lines like "key: value"
key, val = line.split(":", 1)
existing[key.strip()] = existing.get(key.strip(), 0) + int(val.strip())

# 2) Merge in-memory hashMap counts
for k, v in self.hashMap.items():
existing[str(k)] = existing.get(str(k), 0) + v

# 3) Write the merged result back out
with open(dump_file, "w") as f:
for key, val in existing.items():
f.write(f"{key}: {val}\n")

return 1
34 changes: 34 additions & 0 deletions ChironCore/BallLarus/generate_inputs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import json
import random
import argparse


# Usage - python generate_inputs.py -n 20 -o inputs.txt --min 1 --max 50 -v :x :y :z :p
# Generates 20 random input lines for exampl1.tl
def main():
p = argparse.ArgumentParser(
description="Generate N random input‐dict lines for Ball‑Larus profiling"
)
p.add_argument("-n", "--num", type=int, default=10,
help="Number of input lines to generate")
p.add_argument("-o", "--out", default="inputs.txt",
help="Output filename")
p.add_argument("--min", type=int, default=0,
help="Minimum random value (inclusive)")
p.add_argument("--max", type=int, default=100,
help="Maximum random value (inclusive)")
p.add_argument("-v", "--vars", nargs="+",
default=[":x", ":y", ":z", ":p"],
help="List of variable names (include leading colon)")
args = p.parse_args()

with open(args.out, "w") as f:
for _ in range(args.num):
data = {var: random.randint(args.min, args.max) for var in args.vars}
json.dump(data, f)
f.write("\n")

print(f"Wrote {args.num} random inputs to {args.out}")

if __name__ == "__main__":
main()
10 changes: 10 additions & 0 deletions ChironCore/BallLarus/inputs.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{":x": 34, ":y": 2, ":z": 40, ":p": 23}
{":x": 32, ":y": 17, ":z": 49, ":p": 18}
{":x": 34, ":y": 26, ":z": 46, ":p": 18}
{":x": 16, ":y": 24, ":z": 50, ":p": 45}
{":x": 28, ":y": 26, ":z": 34, ":p": 4}
{":x": 34, ":y": 19, ":z": 20, ":p": 3}
{":x": 7, ":y": 32, ":z": 28, ":p": 36}
{":x": 39, ":y": 34, ":z": 38, ":p": 40}
{":x": 33, ":y": 1, ":z": 7, ":p": 22}
{":x": 39, ":y": 1, ":z": 8, ":p": 10}
18 changes: 18 additions & 0 deletions ChironCore/ChironAST/ChironAST.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@ def __init__(self):
def __str__(self):
return "pause"

class PrintCommand(Instruction):
def __init__(self, expr):
self.expr = expr

def __str__(self):
return f"PrintCommand({self.expr})"

class IncrementCommand(Instruction):
def __init__(self, var):
self.var = var # e.g. ":__path_register_var"
def __str__(self):
return f"IncrementCommand({self.var})"


class DumpCommand(Instruction):
def __str__(self):
return "DumpCommand()"

class Expression(AST):
pass

Expand Down
11 changes: 11 additions & 0 deletions ChironCore/ChironAST/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,14 @@ def visitMoveCommand(self, ctx:tlangParser.MoveCommandContext):

def visitPenCommand(self, ctx:tlangParser.PenCommandContext):
return [(ChironAST.PenCommand(ctx.getText()), 1)]

def visitPrintCommand(self, ctx:tlangParser.PrintCommandContext):
expr = self.visit(ctx.expression())
return [(ChironAST.PrintCommand(expr), 1)]

def visitIncrementCommand(self, ctx:tlangParser.IncrementCommandContext):
var = ctx.VAR().getText()
return [(ChironAST.IncrementCommand(var), 1)]

def visitDumpCommand(self, ctx:tlangParser.DumpCommandContext):
return [(ChironAST.DumpCommand(), 1)]
Binary file added ChironCore/acyclic_cfg.dot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
30 changes: 30 additions & 0 deletions ChironCore/chiron.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,21 @@ def stopTurtle():
type=bool,
)

cmdparser.add_argument(
"-bl",
"--ballLarus",
action="store_true",
help="Run Ball-Larus path profiling on a Chiron program",
)

cmdparser.add_argument(
"-bl_op",
"--ballLarus_op",
metavar="INPUTS_FILE",
type=str,
help="File containing multiple input parameter sets (one JSON dict per line) for Ball-Larus path profiling",
)

args = cmdparser.parse_args()
ir = ""

Expand Down Expand Up @@ -392,3 +407,18 @@ def stopTurtle():
writer = csv.writer(file)
writer.writerows(spectrum)
print("DONE..")

if args.ballLarus:
cfg = cfgB.buildCFG(ir, "control_flow_graph")
irHandler.setCFG(cfg)
cfgB.dumpCFG(cfg, "control_flow_graph")
import BallLarus.ballLarus as bl
bl.run_ball_larus_profiling(irHandler, args)

if args.ballLarus_op:
cfg = cfgB.buildCFG(ir, "control_flow_graph")
irHandler.setCFG(cfg)
cfgB.dumpCFG(cfg, "control_flow_graph")
import BallLarus.ballLarus as bl
print(args)
bl.run_ball_larus_profiling(irHandler, args)
Binary file added ChironCore/control_flow_graph.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions ChironCore/hash_dump.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
1: 5
3: 1
2: 1
0: 3
2 changes: 1 addition & 1 deletion ChironCore/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,4 @@ def handleGotoCommand(self, stmt, tgt):
xcor = addContext(stmt.xcor)
ycor = addContext(stmt.ycor)
exec("self.trtl.goto(%s, %s)" % (xcor, ycor))
return 1
return 1
4 changes: 4 additions & 0 deletions ChironCore/path_profile_data.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
['START', '2', '7', '11', '13', 'END']: 5
['START', '5', '7', '11', '13', 'END']: 1
['START', '5', '7', '8', '13', 'END']: 1
['START', '2', '7', '8', '13', 'END']: 3
Binary file added ChironCore/path_profiling_op_tests/cfg6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions ChironCore/path_profiling_op_tests/testcase1.tl
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pendown

repeat 3 [

if (:x > :y) [
penup
goto (:x, :y)
pendown
repeat 4 [
forward :x
left 90
]
] else [
penup
goto (:y, :x)
pendown
repeat 5 [
forward :p
left 72
]
]

if (:z >= :p) [
penup
goto (:p, :x + :z)
pendown
repeat 6 [
backward :x
left 60
]
]

:x = :x + 10
:y = :y + 10
:z = :z + 10
]

penup
19 changes: 19 additions & 0 deletions ChironCore/path_profiling_op_tests/testcase2.tl
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
pendown

repeat 2 [
if (:x > :y) [
repeat 3 [
forward :p
right 120
]
] else [
repeat 4 [
forward :z
left 90
]
]
:x = :x - 5
:z = :z + 5
]

penup
21 changes: 21 additions & 0 deletions ChironCore/path_profiling_op_tests/testcase3.tl
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pendown

if (:x < :z) [
penup
goto (:x, :z)
pendown
repeat 4 [
forward :y
right 90
]
] else [
penup
goto (:z, :x)
pendown
repeat 5 [
forward :p
left 72
]
]

penup
Loading