Course of Raku / Regexes and grammars / Grammars / Grammars, classes, and inheritance / Proto tokens and alternation

Quiz — Grammar inheritance

What does the following program print?

grammar Base {
    token TOP  { <word> }
    token word { 'cat' }
}

grammar Pet is Base {
    token word { 'dog' }
}

say Pet.parse('dog').defined;
1True
0False
0「cat」
0「dog」

Pet inherits TOP from Base but overrides the word token to match dog. When Pet parses 'dog', its own word is used, so the parse succeeds and .defined is True.

Course navigation

Proto tokens and alternation   |   Inherit a grammar