Ingy döt Net > Pegex-0.20 > Pegex::Grammar



Annotate this POD



Open  0
View/Report Bugs
Source   Latest Release: Pegex-0.63


Pegex::Grammar - Pegex Grammar Base Class


Define a Pegex grammar (for the Foo syntax):

    package Pegex::Grammar::Foo;
    use base 'Pegex::Grammar';

    use constant text => q{
    foo: <bar> <baz>
    ... rest of Foo grammar ...
    use constant receiver => 'Pegex::Receiver';

then use it to parse some Foo:

    use Pegex::Grammar::Foo;
    my $ast = Pegex::Grammar::Foo->parse('my/');


Pegex::Grammar is a base class for defining your own Pegex grammar classes. It provides a single action method, `parse()`, that invokes a Pegex parser (usually Pegex::Parser) for you, and then returns the kind of result that you want it to. In other words, subclassing Pegex::Grammar is usually all you need to do to create a parser/compiler for your language/syntax.

Pegex::Grammar classes are very simple. You just need to define a text property that returns your Pegex grammar string, or (if you don't want to incur the compilation of the grammar each time) a tree property which returns a precompiled grammar.

You also need to define the receiver class or object that will produce a result from your parse. 'Pegex::Receiver' is the easiest choice, as long as you are satisfied which its results. Otherwise you can subclass it or define something different.


There are 2 properties of a Pegex::Grammar: tree and text.


This is the data structure containing the compiled grammar for your syntax. It is usually produced by Pegex::Compiler. You can inline it in the tree method, or else the make_tree method will be called to produce it.

The make_tree method will call on Pegex::Compiler to compile the text property by default. You can define your own make_tree method to do override this behavior.

Often times you will want to generate your own Pegex::Grammar subclasses in an automated fashion. The Pegex and TestML modules do this to be performant. This also allows you to keep your grammar text in a separate file, and often in a separate repository, so it can be shared by multiple programming language's module implementations. See the src/ subdirectory in


This is simply the text of your grammar, if you define this, you should (probably) not define the tree property. This grammar text will be automatically compiled when the tree is required.


Ingy döt Net <>


Copyright (c) 2010, 2011, 2012. Ingy döt Net.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


syntax highlighting: