This post is about quirky idea to parse UPF for fun and profit. I started with writing Lark BNF, To a man with a hammer, everything looks like a nail :) But gave up on the idea as i will end up writing frontend for TCL. So, I was mentally blocked for some time.
Then it hit me, I can use full-blown TCL interpreter to parse the actual UPF and pass it back to python for processing. The problem how to do it?
Apparently, TCL can accept user-defined handler for commands called _unknown
. The idea is getting the command name and arg and create a json and send it back to python socket (not show in the snippet yet.)
# Globals passed to python
set command_name "TMP"
set command_args ""
# Handle unsupport commands
rename unknown _unknown;
proc unknown {args} {
# puts stderr "Unknown Command: $args"
# puts [llength $args]
global command_name
global command_args
set command_name [lindex [info level 0] 0]
set result ""
foreach x $args {
append result $x
}
set command_args $result
}
The easiest way to run TCL from python is using tkinter.Tcl
. The first command is calling the common error handler and then parsing TCL(UPF) and passing it to the tclsh
import tkinter
tclsh = tkinter.Tcl()
tclsh.eval("source {tcl/upf_commands.tcl}")
f = open(args.filename,"r")
lines = f.readlines()
lines = "".join(lines)
tclsh.eval(lines)
The next step is complete the interface from TCL to python to call python stuff for each UPF command.