I caught very strange bug(?) which took me almost whole day to find it in real application. In the code there was a elseif block which was commented out and it led to execution of code which (as I thought) could not ever be executed.
I simplified the testcase which reproduces this odd tcl behavior.
proc funnyProc {value} {
if {$value} {
return "TRUE"
# } elseif {[puts "COMMENT :)"] == ""} {
# return "COMMENT"
} else {
return "FALSE"
}
return "IT'S IMPOSSIBLE!!!"
}
puts [funnyProc false]
What do you think this program will output?
- The
putsin the comment line is executed. It’s impossible from any programming language POV. - The line after the block
if {...} {return} else {return}is executed as well. It’s impossible fromtrue/falselogic.
I know that tcl-comment behaves like a command with the name # and consumes all arguments until EOL. And tcl parser do not like unbalanced curly brackets in comments. But this case is out of my understanding.
Maybe I missed something important? How to correctly comment out such elseif blocks, so do not have these weird side-effects?
This is because
#is only a comment when Tcl is looking for the start of a command, and the first time it sees it above (when parsing theif), it’s looking for a}in order to close the earlier{. This is a consequence of the Tcl parsing rules;ifis just a command, not a special construct.The effect that Ernest noted is because it increases the nesting level of the braces on that line, which makes it part of the argument that runs from the end of the
if {$value} {line to the start of the} else {line. Then the#becomes special whenifevaluates the script. (Well, except it’s all bytecode compiled, but that’s an implementation detail: the observed semantics are the same except for some really nasty edge cases.)