Course of Raku / Regexes and grammars / Grammars / Grammars, classes, and inheritance

Grammars are classes

When you write grammar, Raku creates something very close to a class. The tokens are methods on it, and the whole machinery of inheritance from the part on objects applies. So one grammar can extend another with is, just like a subclass:

grammar Base {
    token TOP      { <greeting> }
    token greeting { 'hi' }
}

grammar Loud is Base {
    token greeting { 'HI' }
}

say Loud.parse('HI').defined; # True
say Base.parse('hi').defined; # True

Loud inherits TOP from Base but provides its own greeting. When Loud parses, its TOP calls <greeting>, and the overriding token in Loud is used — exactly how an overridden method works on objects.

This makes grammars composable. You can write a general grammar for a format and then derive a specialised version that changes only the tokens that differ, without copying the rest. Inheritance, overriding, and even the Grammar base type are all the ordinary object-oriented features applied to parsing.

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

Grammars, classes, and inheritance   |   Quiz — Inheriting grammars


💪 Or jump directly to the exercises in this section.