DKF: Have you ever wanted to find out just what a Tcl script is doing? Used to how you can use bash's set -x and miss it in Tcl? Then read on!
This wrapper script (which requires Tcl 8.5) works just like a normal tclsh, but prints out each command that is executed during the processing of the script! This it does through the magical power of execution traces, with a just little help from uplevel.
#!/usr/local/bin/tclsh8.5 namespace eval ::tracer { variable count 0 proc callback {command dummy} { variable count if {[incr count] > 0} { puts TRACE-$count:$command } } proc source args { uplevel 2 [list source {*}$args] } proc tracedSource args { variable count -3 trace add execution ::tracer::source enterstep ::tracer::callback catch {source {*}$args} msg opts trace remove execution ::tracer::source enterstep ::tracer::callback return -options $opts $msg } proc tracedScript {} { global argv argc argv0 set argv0 [lindex $argv 0] set argv [lrange $argv 1 end] incr argc -1 uplevel 1 [list ::tracer::tracedSource $argv0] } } tracer::tracedScript
With the demo script (derived from something posted on comp.lang.tcl which in turn inspired me to write the tracing script above) below I get the trace of execution posted below that:
proc story { char story } { return [format $story $char ] } proc example {} { story {Story} "Once upon a time there was a %s about a [ story {really contrived example program} {%s of a horrendous sort} ]." } puts [example]
$ ~/Desktop/tracer.tcl ~/Desktop/demo.tcl TRACE-1:proc story { char story } { return [format $story $char ] } TRACE-2:proc example {} { story {Story} "Once upon a time there was a %s about a [ story {really contrived example program} {%s of a horrendous sort} ]." } TRACE-3:example TRACE-4:story {really contrived example program} {%s of a horrendous sort} TRACE-5:format {%s of a horrendous sort} {really contrived example program} TRACE-6:return {really contrived example program of a horrendous sort} TRACE-7:story Story {Once upon a time there was a %s about a really contrived example program of a horrendous sort.} TRACE-8:format {Once upon a time there was a %s about a really contrived example program of a horrendous sort.} Story TRACE-9:return {Once upon a time there was a Story about a really contrived example program of a horrendous sort.} TRACE-10:puts {Once upon a time there was a Story about a really contrived example program of a horrendous sort.} Once upon a time there was a Story about a really contrived example program of a horrendous sort.