1.3.4 Literals

literal boolean‑literal | integer‑literal
boolean‑literal true | false
integer‑literal digit‑sequence
digit‑sequence [ 0 - 9 ]+

The Literal rule delegates parsing of a literal to two rules: BooleanLiteral and IntegerLiteral . The rule names BooleanLiteral and IntegerLiteral in the Literal rule are examples of nonterminals .

Distinction between a token and a nonterminal is made using the : symbol separating the name of the nonterminal and the instance name of the nonterminal. It is mandatory.

// literal_parser.parser:

parser LiteralParser
{
    Literal 
        ::= BooleanLiteral:booleanLiteral
        |   IntegerLiteral:integerLiteral
        ;

    BooleanLiteral
        ::= TRUE
        |   FALSE
        ;

    IntegerLiteral 
        ::= INTEGER_LITERAL
        ;
}

The syntax tree node classes for literals contain parsed values of the literals.

// ast.ixx:

export module minilang.ast;

// ...

class BooleanLiteralNode : public Node
{
public:
    BooleanLiteralNode(bool value_);
    bool Value() const { return value; }
    // ...
private:
    bool value;
};

class IntegerLiteralNode : public Node
{
public:
    IntegerLiteralNode(int64_t value_);
    int64_t Value() const { return value; }
    // ...
private:
    int64_t value;
};

// ...

Here is the literal parser completed with semantic actions.

A parser can access the lexer it is instantiated with by using the lexer variable. The pos variable represents the position of the current token contained by the lexer. To convert the matching lexeme of a token to an integer, you can use the ToLong member function of the token class.

// literal_parser.parser:

export module minilang.parser.literal;

[implementation]import minilang.ast;
[implementation]import minilang.lexer;
[implementation]import minilang.token;

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

    Literal : minilang::ast::Node*
        ::= BooleanLiteral:booleanLiteral{ return booleanLiteral; }
        |   IntegerLiteral:integerLiteral{ return integerLiteral; }
        ;

    BooleanLiteral : minilang::ast::Node*
        ::= TRUE{ return new minilang::ast::BooleanLiteralNode(true); }
        |   FALSE{ return new minilang::ast::BooleanLiteralNode(false); }
        ;

    IntegerLiteral : minilang::ast::Node*
        ::= INTEGER_LITERAL{ auto token = lexer.GetToken(pos); return new minilang::ast::IntegerLiteralNode(token.ToLong()); }
        ;
}