I'm learning Scala Syntax Specification.
Confused by the if-else
syntax:
Expr1 ::= ‘if’ ‘(’ Expr ‘)’ {nl} Expr [[semi] ‘else’ Expr]
| ...
How could it match below if-else with one line expression end by semicolon ?
if (true) // \n
println(1); //\n
else //\n
println(2); //\n
Notice there're 4 lines and each followed by a '\n'
. I have these questions:
;
after println(1)
match semi
before else
( [[semi] ‘else’ Expr]
), how to match the 2nd '\n'
after ;
after println(1)
?'\n'
after else
?;
and the 4th '\n'
after println(2)
? Since if-else
don't match any ;
or '\n'
at tail.I think you are being confused by thinking that all newlines must match the nl
token. That is not correct.
Newlines are in general simply treated as whitespace. There is a very long subsection on newlines in the Lexical Syntax chapter section 1.2 Newline characters which explains in detail, when, exactly, a newline character is an nl
token and when it isn't.
Only the first newline character in your example is an nl
token, the other three are just whitespace.