Search code examples
scalasyntaxcompiler-constructiongrammar

Scala Syntax Specification mismatch if-else with one line expression end by semicolon?


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:

  1. When the 1st ; after println(1) match semi before else( [[semi] ‘else’ Expr] ), how to match the 2nd '\n' after ; after println(1) ?
  2. How to match the 3rd '\n' after else ?
  3. How to match the 2nd ; and the 4th '\n' after println(2) ? Since if-else don't match any ; or '\n' at tail.

Solution

  • 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.