GrAnd
GrAnd

Reputation: 10221

Weird behavior of tcl comment inside if/else block. Is it a bug of tcl interpreter?

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?

  1. The puts in the comment line is executed. It's impossible from any programming language POV.
  2. The line after the block if {...} {return} else {return} is executed as well. It's impossible from true/false logic.

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?

Upvotes: 1

Views: 1136

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137697

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 the if), it's looking for a } in order to close the earlier {. This is a consequence of the Tcl parsing rules; if is 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 when if evaluates 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.)

Upvotes: 6

Related Questions