1.3.7 Statements

The rules for minilang statements contain sequential, optional and repeating elements.

statement if‑statement | while‑statement | return‑statement | compound‑statement | construction‑statement | assignment‑statement
if‑statement if ( expression ) statement ( else statement )?
while‑statement while ( expression ) statement
return‑statement return expression ?
compound‑statement { statement * }
construction‑statement type identifier = expression ;
assignment‑statement identifier = expression ;

The Statement rule delegates parsing to other rules.

export module minilang.parser.statement;

[implementation]import minilang.ast;
[implementation]import minilang.lexer;
[implementation]import minilang.token;
[implementation]import minilang.parser.expression;
[implementation]import minilang.parser.type;
[implementation]import minilang.parser.identifier;

parser StatementParser
{
    lexer minilang::lexer::MinilangLexer<char32_t>;

    using ExpressionParser.Expression;
    using TypeParser.Type;
    using IdentifierParser.Identifier;

    Statement : minilang::ast::Node*
        ::= IfStatement:ifS{ return ifS; }
        |   WhileStatement:whileS{ return whileS; }
        |   ReturnStatement:returnS{ return returnS; }
        |   CompoundStatement:compoundS{ return compoundS; }
        |   ConstructionStatement:constructionS{ return constructionS; }
        |   AssignmentStatement:assignmentS{ return assignmentS; }
        ;
    ...
}

In the IfStatement rule there are elements with a postfix ! operator. They are elements that are mandatory, in other words are expected to be present unconditionally after seeing the if token. If not, an immediate error is generated for them.

The else -part of the if -statement is optional. This denoted by the question mark.

    ...
    
    IfStatement : minilang::ast::Node*
        ::= 
        (
            IF LPAREN! Expression:condition! RPAREN! Statement:thenS! (ELSE Statement:elseS!)?
        )
        {
            return new minilang::ast::IfStatementNode(condition, thenS, elseS);
        }
        ;

    ...
}

The var keyword is used for declaring local variables for a rule.

Zero or more occurrences of an expression is denoted by the kleene-star symbol * .

    ...
    CompoundStatement(var std::unique_ptr<minilang::ast::CompoundStatementNode> compoundStatement) : minilang::ast::CompoundStatementNode*
        ::= 
        (
            LBRACE{ compoundStatement.reset(new minilang::ast::CompoundStatementNode()); } 
            (
                Statement:statement{ compoundStatement->AddStatement(statement); }
            )* 
            RBRACE!
        )
        {
            return compoundStatement.release();
        }
        ;
    ...