|
|
|
 |
Tmac - Introduction
|
|
|
|
What is it?
Tmac is a text preprocessor for Tcl written in Tcl. Tmac scans source code before it is seen by the Tcl parser. During scanning
macro definitions are discovered and removed. Then macro substitutions are performed based on defined macros and configured options. Available styles of macro "expansion" (which can also accomplish deletions!) include:
Potential Benefits
- Reduce code duplication without the overhead of a proc call
- Able to code more quickly with more concise constructs
- Possibly reduce errors and debugging time due to missing braces, brackets, etc
- Code can be more comprehensible and easier to read
- True read-only constants without setting traces
- Customized control structures or built-ins without runtime overhead.
- Put macro-type comments anywhere they are needed like inside large array set arguments
- Trial usage of proposed Tcl command enhancements (eg. to switch, foreach, etc.)
- Oh, and you can also make a big mess (but you don't need macros to do that ;^)
Points to Keep in mind
- tmac runs before the Tcl parser sees the code.
- There is no run-time penalty for the macro feature.
- There will be extra time taken to startup the application while macros are processed
- When macros are being defined and expanded the program's normal variable values are not availabe because the program isn't running yet! (Yes, this is obvious but oh so easy to forget!)
- Neither macro definitions nor macro invocations follow the same rules as Tcl procs. They are never seen by the Tcl parser.
- Tmac provides flexibility. Macro processing can be called for whole files, individual procedures, or arbitrary strings. The string
need not be valid Tcl code. Macro output can be automatically executed or provided as a string. For example, a large scale
macro might be used once to produce an application template and the output saved as a separate source file.
Short Example
Get app.tcl preprocess and sent to the Tcl interpreter (eval'd)
package require tmac
# Preprocess and eval all the text in app.tcl tmac::tmsource app.tcl ~~~~~~~
Define and invoke some macros in app.tcl
# In app.tcl a macro definition like the following can appear anywhere # a blank line could appear in Tcl source MAC-BLOCK m1 text var1 var2 {puts stderr "@text: $@var1,$@var2"}
#Invoke the m1 parameter substitution macro set x 101 set y 202 <:m1 hereIS x y:>
...emits as last line:
puts stderr "hereIS: $x,$y"
Things to notice
- m1 is the macro name.
- The dollar signs came from the macro body and thus weren't needed in the invocation.
- "text", "var1", and "var2" are the formal parameters
- @ character marks insertion points for parameters
- There are other methods to define and expand macros.
See the usage man page for details and additional features.
|