#. First write a grammar. There are several ways to do that:
#. The canonical grammar format uses Python statements and expressions. Each rule is specified as Python function which should return a data structure that defines the rule. For example a grammar for simple calculator can be written as:
#. The canonical grammar format uses Python statements and expressions. Each rule is specified as Python function which should return a data structure that defines the rule. For example a grammar for simple calculator can be written as::
from arpeggio import Optional, ZeroOrMore, OneOrMore, EOF
from arpeggio import RegExMatch as _
...
...
@@ -53,7 +53,8 @@ Quick start
The python lists in the data structure represent ordered choices while the tuples represent sequences from the PEG.
For terminal matches use plain strings or regular expressions.
#. The same grammar could also be written using traditional textual PEG syntax like this:
#. The same grammar could also be written using traditional textual PEG syntax like this::
number <- r'\d*\.\d*|\d+'; // this is a comment
factor <- ("+" / "-")?
(number / "(" expression ")");
...
...
@@ -61,7 +62,7 @@ Quick start
expression <- term (("+" / "-") term)*;
calc <- expression+ EOF;
#. Or similar syntax but a little bit more readable like this:
#. Or similar syntax but a little bit more readable like this::
number = r'\d*\.\d*|\d+' # this is a comment
factor = ("+" / "-")?
...
...
@@ -72,14 +73,14 @@ Quick start
The second and third options are implemented using canonical first form. Feel free to implement your own grammar syntax if you don't like these (see modules :code:`arpeggio.peg` and :code:`arpeggio.cleanpeg`).
#. Instantiate a parser. Parser works as grammar interpreter. There is no code generation:
#. Instantiate a parser. Parser works as grammar interpreter. There is no code generation::
from arpeggio import ParserPython
parser = ParserPython(calc) # calc is the root rule of your grammar
# Use param debug=True for verbose debugging messages and
# grammar and parse tree visualization using graphviz and dot
In music, arpeggio is playing the chord notes one by one in sequence. I came up with the name by thinking that parsing is very similar to arpeggios in music. You take tokens one by one from an input and make sense out of it – make a chord!
Well, if you don't buy this maybe it is time to tell you the truth. I searched the dictionary for the words that contains PEG acronym and the word arpeggio was at the top of the list ;)
Well, if you don't buy this maybe it is time to tell you the truth. I searched the dictionary for the words that contain PEG acronym and the word arpeggio was at the top of the list ;)