|
Initially found by me (after some mistake/typo in code) as possible "legal" basic construct, like "if" without body, but with "else":
if {[catch { set no error }]} else {puts "negative case only"}
or even still simple:
if 0 else {puts "negative case only"}
It is clear a mistake (but very unobvious if one just take a look at code), because "else" will be to body and the real body of "else" remains as negative case body (just because "else" operand is optional in "if"-construct).
This way it is similar to:
if 0 {...} {puts "negative case only"}
Obviously, it works this way without any problem, until expression results in true (where it will always fail, because trying execute "else" as body).
% if 0 else {puts "negative case only"}
negative case only
% if 1 else {puts "negative case only"}
invalid command name "else"
The command is implemented this way possibly since the beginning (tested and reproducible with Tcl >= 8.2.2).
Discussing the issue in tcl-chat, we've get an idea to "fix" this bizarre corner-cases without harm of current code, and improve it retaining "backwards" compatibility (for some possible obscure old code-pieces with "else"-only and expressions currently always resulting in "false", therefore still working until today.
Remain "else" as optional keyword, but if this is provided as body (as 3rd argument, without "then") it will be recognized as keyword of "if"-command.
if $cond else {foo}
would be then valid (short) replacement for empty body cases like:
if $cond {} else {foo}
if $cond then {} else {foo}
Following examples show how it may work:
% if 0 else {puts "negative case only"}
negative case only
% if 1 else {puts "negative case only"}
<none>
% proc else args {puts "else command $args"}
% if 1 then {else}
else command
% if 1 then
wrong # args: no script following "then" argument
% if 1 else
wrong # args: no script following "else" argument
There are another keywords like "elseif" which could be handled similar way (for consistency reasons).
Here is an example (provided in chat from avl42), which would call foo only if both $cond1 and $cond2 were false:
if $cond1 elseif $cond2 else {foo}
and would be then proper replacement for:
if $cond1 then {} elseif $cond2 {} else {foo}
I've a branch covering this "bug", prevents mistakes like this resp. improves the readability and consistency of (compiled and not-compiled) "if"-command in Tcl.
WiP: working on the test-cases now.
|