tcl: proc body in quotes instead of curly brackets - tcl

Is there any problem (e.g. a performance penalty) if the body of a proc is provided in quotes rather than curly brackets?
My code generates procs (as OOP-like methods) inside of other procs, e.g.
proc dataObject {name someData} {
# more stuff
proc ${name}.getData {args} \
"checkArgs \$args 0; return $someData"
# more stuff
}
and for simplity, I use quotes to enable variable substitution. It works, but I'm just worried that the code may not be precompiled or something.
Thanks for your help!

I'm just worried that the code may not be precompiled or something.
This is not to worry about, besides, there is no precompilation or similar in Tcl. Once executed for the first time, the generated proc's body will be byte-compiled (however the body script was assembled).
However, your proc generator is not robust. Variable substitution under quotes will break your body script when someData contains a string which renders the body script or one of its commands incomplete, e.g.:
dataObject test "do it"
will fail because it translates into
return do it;
There are several ways to assemble a script (command-sequence string) in a robust manner, one is using list protection:
proc dataObject {name someData} {
set procName ${name}.getData
append body {checkArgs $args 0} \;
append body [list return $someData] \;
proc $procName {args} $body
return [namespace which -command $procName]
}
As pointed out by Donal in another answer, nesting proc calls one in another is not necessarily leading to what you expect. In your case, though, as a generator, it might be acceptable. Still, you might want consider using a Tcl lambda or a proper (well, data) object?

It is difficult to do completely reliable code generation, but not impossible and using double quotes around a procedure body is entirely legal. I advise constraining the space of inserted words to non-empty alphanumeric prior to doing the codegen; that stops almost all mischief dead; other values need to be quoted (the list command can do exactly the right quoting you need with a little encouragement). It's often easier to generate an alias that curries some extra arguments onto a call of a non-varying procedure. Here's a very simple example of what I mean:
proc saySomething {a b} {
puts -nonewline $a
puts $b
}
proc makeSpeaker {cmd prefix} {
interp alias {} $cmd {} saySomething "[string trimright $prefix] "
}
makeSpeaker hello "Hello to"
hello Ralf
# ==> Hello to Ralf
As you can see, we've “generated” code that includes a word with a space in it without having to do complex quoting. It can't do everything, but it can do a lot.
And don't make your own pseudo-OO code. Not these days. Tcl from 8.6 onwards comes with an OO system core that makes doing that stuff much faster and more reliable.
oo::class create Speaker {
variable Prefix
constructor {prefix} {
set Prefix "[string trimright $prefix] "
}
method say {suffix} {
puts -nonewline $Prefix
puts $suffix
}
}
Speaker create greeting "Hello to"
greeting say Ralf
Of course, you can mix these two together to get some truly powerful approaches, but then the example's getting a bit long for quick comprehension...

Related

Why curly braces allow variable substitution?

Tcl manuals say that curly braces do not allow variable substitution.
However this works only with some commands but not with others.
What is the difference and how to identify the cases where the substitution will occur and the cases where it won't occur?
% set x 3
3
% puts {$x}
$x
% expr {$x}
3
Referring to the list of standard commands: any command that takes a "body" or "script" argument will eventually evaluate that body as code. With no guarantees about exhaustiveness:
after, apply, catch, eval, expr, fileevent (and chan event), for, foreach, if, interp eval, lmap, some namespace subcommands, some oo::* commands, proc, subst, switch, try, uplevel, while
This is truly one of Tcl's greatest strengths. It gives you the power to easily write your own control structures. For example, Tcl does not provide a do-while loop, but you can do this:
proc do {body while condition} {
if {$while ni {while until}} {
error "some message about usage..."
}
while true {
uplevel 1 $body
set status [uplevel 1 [list expr $condition]]
if {$while eq "while" && !$status} then break
if {$while eq "until" && $status} then break
}
}
so that
% set i 0; while {[incr i] < 3} {puts "$i"}
1
2
% set i 0; do {puts "$i"} while {[incr i] < 3}
0
1
2
% set i 0; do {puts "$i"} until {[incr i] == 3}
0
1
2
Some commands are explicitly described as treating an argument or arguments as a script or an expression; when evaluation of the script or expression happens (which might be immediately, or might be later, depending on the command) the substitutions described inside that string that is a script or expression are performed. (The subst command is a special case that can only apply a selected subset of substitutions.)
How do you know which is which? It depends on the command. Literally. Go and read the documentation. For example, in the documentation for catch we see:
SYNOPSIS
catch script ?resultVarName? ?optionsVarName?
DESCRIPTION
The catch command may be used to prevent errors from aborting command interpretation. The catch command calls the Tcl interpreter recursively to execute script, and always returns without raising an error, regardless of any errors that might occur while executing script. […]
In this case, we see that the first argument is always evaluated (immediately) as a Tcl script by calling the Tcl interpreter (or rather it's actually bytecode compiled in most cases, but that's an implementation detail).
Similarly, in the documentation for proc we see:
SYNOPSIS
proc name args body
DESCRIPTION
The proc command creates a new Tcl procedure named name, replacing any existing command or procedure there may have been by that name. Whenever the new command is invoked, the contents of body will be executed by the Tcl interpreter. […]
In this case, it's the body that is going to be evaluated as a script (“by the Tcl interpreter” is a form of language that means that) but later, when the procedure is called. (catch said nothing about that; by implication, it acts immediately.)
A third case is the documentation for while:
SYNOPSIS
while test body
DESCRIPTION
The while command evaluates test as an expression (in the same way that expr evaluates its argument). The value of the expression must a proper boolean value; if it is a true value then body is executed by passing it to the Tcl interpreter. […]
From this, we can see that the test argument is an expression (which uses expression rules) and body is a script.
If you want to create a substitution-free single-command script where you can use arbitrary values for everything (this perfect for setting up a callback) use the list command as that is defined to produce lists in canonical form, which happens (by design) to be exactly the form that single commands without substitution-surprises can take:
set xyz "123 456"
set callback [list puts $xyz]
set xyz {[crash bang wallop]}
puts "READY..."
eval $callback

How to write tcl proc for numbers

I want to create a tcl proc/ command like
[1] should return 1
[2] should return 2
.
.
[18999] should return 18999
How i should write one proc to handle all the number commands
This is very much not recommended! Also, you can't really make a single command to do all of this. However, the easiest method is to update the unknown procedure to create the commands you need on demand. Patching unknown needs a little care.
proc unknown args [concat {
if {[llength $args] == 1 && [string is entier -strict [lindex $args 0]]} {
set TheNumber [lindex $args 0]
proc ::$TheNumber {} [list return $TheNumber]
return $TheNumber
# The semicolon on the next line is required because of the [concat]
};
} [info body unknown]]
This will make trivial procedures on demand as long as their names look exactly like (full, extended) integers. (Supporting floats as well isn't too hard; it'd just be a matter of writing a slightly more complex test that also uses string is double.)
But be aware that unknown command handling is a slow way to do this; it's the mechanism that Tcl invokes immediately before it would otherwise have to throw an error because a command doesn't exist. We could have made it just return the value directly without creating the procedure, but then every time you called this you'd have the overhead of the unsuccessful search; making the procedures speeds things up.
Not using numbers as commands at all will speed your code up even more.

how to get specific parameters in a square bracket and store it in to a specific variable in tcl

set_dont_use [get_lib_cells */*CKGT*0P*] -power
set_dont_use [get_lib_cells */*CKTT*0P*] -setup
The above is a text file.
I Want to store */CKGTOP* and */CKTTOP* in to a variable this is the programme which a person helped me with
set f [open theScript.tcl]
# Even with 10 million lines, modern computers will chew through it rapidly
set lines [split [read $f] "\n"]
close $f
# This RE will match the sample lines you've told us about; it might need tuning
# for other inputs (and knowing what's best is part of the art of RE writing)
set RE {^set_dont_use \[get_lib_cells ([\w*/]+)\] -\w+$}
foreach line $lines {
if {[regexp $RE $line -> term]} {
# At this point, the part you want is assigned to $term
puts "FOUND: $term"
}
}
My question is if more than one cells like for example
set_dont_use [get_lib_cells */*CKGT*0P* */*CKOU*TR* /*....] -power
set_dont_use [get_lib_cells */*CKGT*WP* */*CKOU*LR* /*....] -setup
then the above script isn't helping me to store the these "n" number cells in the variable known as term
Could any of u people help me
Thanking you ahead in time
I would go with
proc get_lib_cells args {
global term
lappend term {*}$args
}
proc unknown args {}
and then just
source theScript.tcl
in a shell that doesn't have the module you are using loaded, and thus doesn't know any of these non-standard commands.
By setting unknown to do nothing, other commands in the script will just be passed over.
Note that redefining unknownimpairs Tcl's ability to automatically load some processes, so don't keep using that interpreter after this.
Documentation:
global,
lappend,
proc,
unknown,
{*} (syntax)
Your coding seems like the Synopsys syntax, meaning - it shouldn't work the way you wrote it, I'd expect curly braces:
set_dont_use [get_lib_cells {*/*CKGT*0P* */*CKOU*TR* /*....}] -power
moreover, the \w doesn't catch the *,/ (see this).
If I were you, I'd go for set RE {^set_dont_use \[get_lib_cells \{?([\S*]+ )+\}?\] -\w+$} and treat the resulting pattern match as a list.
Edit:
see this:
% regexp {^set_dont_use [get_lib_cells {?(\S+) ?}?]} $line -> match
1
% echo $match
*/*CKGT*0P*
If you have more than one item in your line, add another parentheses inside the curly braces:
regexp {^set_dont_use \[get_lib_cells \{?(\S+) ?(\S+)?\}?\]} $l -> m1 m2
ect.
Another Edit
take a look at this, just in case you want multiple matches with the same single pattern, but than, instead of \S+, you should try something that looks like this: [A-Za-z\/\*]

Can proc argument be variable

I just tried the following in tclsh:
proc pp {$ag} { puts hi}
pp whatever
To my surprise, this works fine! I had expected a syntax error because the proc argument is a variable. But it seems tcl takes it fine.
Then I experimented:
proc pp {$ag} { puts "hi $ag"}
pp whatever
and
proc pp {$ag} { puts "hi ${$ag}"}
pp whatever
I got error, can't read "ag": no such variable.
This makes me wondering, can proc argument be variable? If not, why not error out in the first script?
The first case works because you never use the parameter to pp.
When you invoke the proc command, the text of the invocation is evaluated just like in any other command invocation. In all the above cases, the third argument (which will become the argument list of the pp command) is is wrapped in braces, which means it won't be evaluated as a variable but as a string of three characters: "$ag" (i.e. the dollar sign is just a regular character here). This is not an error, and does work, just not the way you seem to expect it to.
It's a bit tricky to get the value of the parameter $ag, though. This works:
proc pp {$ag} {puts "hi [set {$ag}]"}
The dollar notation is actually just syntactic sugar for the unary set command. Sometimes the dollar notation won't work, and you need to fall back to an explicit set.
This does work too, though:
proc pp {$ag} {puts "hi ${$ag}"}
So, in your invocations, the third argument to proc isn't really a variable evaluation, it just looks like one. You can of course use an actual variable evaluation in the invocation of proc:
set foo {bar baz}
proc qux $foo {puts $bar ; puts $baz}
qux abc def
# => abc
# => def
What the Tcl interpreter really sees here is:
proc qux {bar baz} {puts $bar ; puts $baz}
Or you can go really crazy:
set foa {proc qux}
set fob {bar}
lappend fob baz
set foc {puts $bar}
set fod "puts \$baz"
{*}$foa $fob [join [list $foc $fod] { ; }]
Which amounts to the same thing as the previous invocation of proc. (If you don't believe me, try list {*}$foa $fob [join [list $foc $fod] { ; }])
This example just looks (and is) weird, but many times it's actually useful to construct new commands within your program, and in those cases it's really nice that the text used in the invocation of proc, like with any other command, is simply text that the evaluation rules of Tcl can be applied to. You can use any kinds of string or list operations on it and join up pieces of text from various sources, even user input (if you can trust it).
Documentation: Tcl evaluation rules including $ and {*}, join, lappend, list, proc, puts, set

Procedure tracking in log with proc renaiming

I have a custom test tool written in tcl and bash (mainly in tcl, some initial config and check were done by bash). It isn't have an exact starting point, the outside bash (and sometimes the application which is tested) call specific functions which they find with a "tclIndex" file, created by auto_mkindex.
This tool create a log file, with many "puts" function, which is directed to the file location.
Most of the functions have a "trackBegin" function call at the beginning, and one "trackEnd" function at the end of it. These two get the functions name as parameter. This help us to track where is the problem.
Sadly, this tracker was forgotten in some modification in the near past, and its not even too reliable because its not going to track if there is any abnormal exit in the function. Now, i tried to remove all of them, and create a renamed _proc to override the original and place this two tracker before and after the execution of the function itself.
But i have a lots of error (some i solved, but i dont know its the best way, some are not solved at all, so i'm stuck), these are the main ones:
Because there is no exact entry point, where should i define and how, this overrided proc, to work on all of the procedures in this execution? Some of my files had to be manually modified to _proc to work (mostly the ones where there are code outside the procedures and these files as scripts were called, not functions through the tclIndex, the function called ones are all in a utils folder, and only there, maybe it can help).
In the tracker line i placed a "clock" with format, and its always cause abnormal exit.
I had problems with the returned values (if there was one, and some time when there isn't). Even when that was a return, or Exit.
So my question is in short:
How can i solve an overrided proc function, which will write into a logfile a "begin" and "end" block before and after the procedure itself (The log file location was gained from the bash side of this tool), when there is no clear entry point in this tool for the tcl side, and use an auto_mkindex generated procedure index file?
Thanks,
Roland.
Untested
Assuming your bash script does something like
tclsh file.tcl
You could do
tclsh instrumented.tcl file.tcl
where instrumented.tcl would contain
proc trackBegin {name} {...}
proc trackEnd {name output info} {...}
rename proc _proc
_proc proc {name args body} {
set new_body [format {
trackBegin %s
catch {%s} output info
trackEnd %s $output $info
} $name $body $name]
_proc $name $args $new_body
}
source [lindex $argv 0]
See the return and catch pages for what to do with the info dictionary.
You'll have to show us some of your code to provide more specific help, particularly for your clock error.
I'd be tempted to use execution tracing for this, with the addition of the execution tracing being done in an execution trace on proc (after all, it's just a regular Tcl command). In particular, we can do this:
proc addTracking {cmd args} {
set procName [lindex $cmd 1]
uplevel 1 [list trace add execution $procName enter [list trackBegin $procName]]
uplevel 1 [list trace add execution $procName leave [list trackEnd $procName]]
}
proc trackBegin {name arguments operation} {
# ignore operation, arguments might be interesting
...
}
proc trackEnd {name arguments code output operation} {
# ignore operation, arguments might be interesting
...
}
trace add execution proc leave addTracking
It doesn't give you quite the same information, but it does allow you to staple code around the outside non-invasively.