An extension for Tcl, written in C, that lets Tcl scripts access Tcl's own parser via the parse command.
As a package, the name is parser.
The tclparser source code is available from here:
http://tclpro.cvs.sourceforge.net/tclpro/tclparser/
cvs -d:pserver:[email protected]:/cvsroot/tclpro login cvs -z3 -d:pserver:[email protected]:/cvsroot/tclpro co tclparser mkdir tclparser/build cd tclparser/build ../configure --prefix=/home/tcl --with-tcl=/home/tcl/lib make make install
Despite CVS history showing no activity since 2007, this builds cleanly against 8.6.3. That's a stable interface!
As the manual explains, it exposes one command parse $type $text $range, which returns a structure similar to tcltest's testparser, but a bit more convenient for script manipulation. Like tcltest::testparser, this is a lightweight wrapper around functions in tclParse.c .
A simple example to turn an expression into namespace evalable code:
package require parser proc expr2tcl {expr {parse ""}} { if {$parse eq ""} { set parse [parse expr $expr {0 end}] } lassign $parse type range parts lassign $range min max incr max $min incr max -1 set text [string range $expr $min $max] set result "" switch $type { subexpr { set result [join [lmap part $parts {expr2tcl $expr $part}] " "] if {[lindex $parts 0 0] eq "operator"} { return \[$result\] } else { return $result } } default { return $text } } } # % puts [expr2tcl {sin($x)+4*$x-$x**(pow($x,2))}] # [- [+ [sin $x] [* 4 $x]] [** $x [pow $x 2]]]
See also: