Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Perl 6's uncuddled else a special case for statement separation?

Tags:

raku

From the syntax doc:

A closing curly brace followed by a newline character implies a statement separator, which is why you don't need to write a semicolon after an if statement block.

if True {
    say "Hello";
}
say "world";

That's fine and what was going on with Why is this Perl 6 feed operator a “bogus statement”?.

However, how does this rule work for an uncuddled else? Is this a special case?

if True {
    say "Hello";
}
else {
    say "Something else";
}
say "world";

Or, how about the with-orwith example:

my $s = "abc";
with   $s.index("a") { say "Found a at $_" }
orwith $s.index("b") { say "Found b at $_" }
orwith $s.index("c") { say "Found c at $_" }
else                 { say "Didn't find a, b or c" }
like image 950
brian d foy Avatar asked Aug 05 '17 09:08

brian d foy


1 Answers

The documentation you found was not completely correct. The documentation has been updated and is now correct. It now reads:

Complete statements ending in bare blocks can omit the trailing semicolon, if no additional statements on the same line follow the block's closing curly brace }.

...

For a series of blocks that are part of the same if/elsif/else (or similar) construct, the implied separator rule only applies at the end of the last block of that series.


Original answer:

Looking at the grammar for if in nqp and Rakudo, it seems that an if/elsif/else set of blocks gets parsed out together as one control statement.

Rule for if in nqp

rule statement_control:sym<if> {
    <sym>\s
    <xblock>
    [ 'elsif'\s <xblock> ]*
    [ 'else'\s <else=.pblock> ]?
}

(https://github.com/perl6/nqp/blob/master/src/NQP/Grammar.nqp#L243, as of August 5, 2017)

Rule for if in Rakudo

rule statement_control:sym<if> {
    $<sym>=[if|with]<.kok> {}
    <xblock(so ~$<sym>[0] ~~ /with/)>
    [
        [
        | 'else'\h*'if' <.typed_panic: 'X::Syntax::Malformed::Elsif'>
        | 'elif' { $/.typed_panic('X::Syntax::Malformed::Elsif', what => "elif") }
        | $<sym>='elsif' <xblock>
        | $<sym>='orwith' <xblock(1)>
        ]
    ]*
    {}
    [ 'else' <else=.pblock(so ~$<sym>[-1] ~~ /with/)> ]?
}

(https://github.com/rakudo/rakudo/blob/nom/src/Perl6/Grammar.nqp#L1450 as of August 5, 2017)

like image 112
Christopher Bottoms Avatar answered Oct 02 '22 12:10

Christopher Bottoms