rakitzis/rc

`If not` inconsistency with p9p rc

aksr opened this issue · 9 comments

aksr commented

This is legal in p9p rc, but not in this rc implementation:

#!/usr/bin/rc
if (~ $1 1) {
  echo 1
}
if not {
  echo 2
}

(Execute it with 1 as argument.)

syntax error near not

aksr commented

I'm not sure I understand you...

that's the error output of the script. I'm pretty sure else is much more respectable than if not, i've even heard the rumors that if not actually was a mistake

We just recently implemented if not. It's not in any release yet, but if you checkout the development version you'll find that script works as expected.

Tom Duff who originally designed and implemented the Plan 9 rc does say that if not is an “admittedly feeble solution” to the problem. The problem being that the else part of an if statement is optional, so if you're running interactively and you've just read a complete if statement, you don't know whether you should execute it, or carry on reading in case there's an else clause.

@rakitzis devised a different solution: insist that else occurs on the same line as the if statement, or part of it such as its closing brace. Thus, in this rc you must always write } else ... you cannot start the else clause on a new line. I think this is neater than if not, but still contains that trap for the unwary.

Now we implement both else and if not. Not ideal, but the goal was to allow a script written for the Plan 9 rc to run under this one.

I'll point out ironically that my rc "else" trick anticipates exactly (by some ~20 years) the same solution adopted by Golang.

@rakitzis devised a different solution: insist that else occurs on the same line as the if statement, or part of it such as its closing brace.

else on the same line does not seem to work without {}. else (and everything after it) is considered additional arguments to the true subcmd of if() rather than a keyword.

; if (true) echo yes else echo no
yes else echo no
; if (true) echo yes; else echo no
rc: syntax error
; if (true) { echo yes } else echo no
yes
aksr commented

@TobyGoodwin: Thank you. It's fixed now with this commit.

@borkovic Yes, you're quite right, the braces are compulsory around the true branch if you want to follow it with an else clause.

That's different from C, but consistent with how other keywords are handled, and with other shells:

; echo for in else
for in else

$ echo for in done case
for in done case

@TobyGoodwin: That's different from C, but consistent with how other keywords are handled, and with other shells:

Agreed on all points. To echo your comment, I think if (test) { cmdT } else cmdF is a much better solution than if not cmdF.