Simple Parser
How to easily write parsers in Python
Introduction and tutorial
Introduction
SP (Simple Parser) is a Python[^1] parser generator. It is aimed at easy
usage rather than performance. SP produces
Top-Down Recursive
descent parsers.
SP also uses memoization to
optimize parsers' speed when dealing with ambiguous grammars.
License
SP is available under the GNU Lesser General Public:
Simple Parser: A Python parser generator
Copyright (C) 2009-2026 Christophe Delord
Simple Parser is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Simple Parser is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Simple Parser. If not, see <http://www.gnu.org/licenses/>.
Structure of the document
Introduction and tutorial
: starts smoothly with a gentle tutorial as an introduction. I think this
tutorial may be sufficient to start with SP.
SP reference
: is a reference documentation. It will detail SP as much as possible.
Some examples to illustrate SP
: gives the reader some examples to illustrate SP.
Installation
Getting SP
SP is freely available on its web page (https://codeberg.org/cdsoft/sp).
Requirements
SP is a pure Python package. It may run on any platform supported by
Python. The only requirement of SP is Python 2.6, Python 3.1 or
newer[^2]. Python can be downloaded at http://www.python.org.
Tutorial
Introduction
This short tutorial presents how to make a simple calculator. The
calculator will compute basic mathematical expressions (+, -, *,
/) possibly nested in parenthesis. We assume the reader is familiar
with regular expressions.
Defining the grammar
Expressions are defined with a grammar. For example an expression is a
sum of terms and a term is a product of factors. A factor is either a
number or a complete expression in parenthesis.
We describe such grammars with rules. A rule describes the composition
of an item of the language. In our grammar we have 3 items (expr, term,
factor). We will call these items symbols or non terminal symbols.
The decomposition of a symbol is symbolized with ->.
Grammar for expressions:
| Grammar rule |
Description |
| `expr -> term (('+' |
'-') term)*` |
| `term -> fact (('*' |
'/') fact)*` |
| `fact -> ('+' |
'-') fact |
We have defined here the grammar rules (i.e. the sentences of the
language). We now need to describe the lexical items (i.e. the words of
the language). These words - also called terminal symbols - are
described using regular expressions. In the rules we have written some
of these terminal symbols (+, -, *, /, (, )). We have to
define number. For sake of simplicity numbers are integers composed of
digits (the corresponding regular expression can be [0-9]+). To
simplify the grammar and then the Python script we define two terminal
symbols to group the operators (additive and multiplicative operators).
We can also define a special symbol that is ignored by SP. This symbol
is used as a separator. This is generally useful for white spaces and
comments.
Terminal symbol definition for expressions:
| Terminal symbol |
Regular expression |
Comment |
number |
[0-9]+ or \d+ |
One or more digits |
addop |
[+-] |
a + or a - |
mulop |
[*/] |
a * or a / |
spaces |
\s+ |
One or more spaces |
This is sufficient to define our parser with SP.
Grammar of the expression recognizer:
def Calc():
number = R(r'[0-9]+')
addop = R('[+-]')
mulop = R('[*/]')
with Separator(r'\s+'):
expr = Rule()
fact = Rule()
fact |= addop & fact
fact |= '(' & expr & ')'
fact |= number
term = fact & ( mulop & fact )[:]
expr |= term & ( addop & term )[:]
return expr
Calc is the name of the Python function that returns a parser. This
function returns expr which is the axiom[^3] of the grammar.
expr and fact are recursive rules. They are first declared as empty
rules (expr = Rule()) and alternatives are later added
(expr |= ...).
Slices are used to implement repetitions. foo[:] parses foo zero or
more times, which is equivalent to foo* in a classical grammar
notation.
The grammar can also be defined with the mini grammar language provided
by SP:
def Calc():
return compile("""
number = r'[0-9]+' ;
addop = r'[+-]' ;
mulop = r'[*/]' ;
separator: r'\s+' ;
!expr = term (addop term)* ;
term = fact (mulop fact)* ;
fact = addop fact ;
fact = '(' expr ')' ;
fact = number ;
""")
Here the axiom[^4] is identified by !.
With this small grammar we can only recognize a correct expression. We
will see in the next sections how to read the actual expression and to
compute its value.
Reading the input and returning values
The input of the grammar is a string. To do something useful we need to
read this string in order to transform it into an expected result.
This string can be read by catching the return value of terminal
symbols. By default any terminal symbol returns a string containing the
current token. So the token '(' always returns the string '('. For
some tokens it may be useful to compute a Python object from the token.
For example number should return an integer instead of a string,
addop and mulop, followed by a number, should return a function
corresponding to the operator. That's why we will add a function to the
token and rule definitions. So we associate int to number and op1
and op2 to unary and binary operators.
int is a Python function converting objects to integers and op1 and
op2 are user defined functions.
op1 and op2 functions:
op1 = lambda f,x: {'+':pos, '-':neg}[f](x)
op2 = lambda f,y: lambda x: {'+': add, '-': sub, '*': mul, '/': div}[f](x,y)
# red applyies functions to a number
def red(x, fs):
for f in fs: x = f(x)
return x
To associate a function to a token or a rule it must be applied using / or * operators:
/ applies a function to an object returned by a (sub)parser.
* applies a function to an tuple of objects returned by a sequence
of (sub) parsers.
Token and rule definitions with functions:
number = R(r'[0-9]+') / int
fact |= (addop & fact) * op1
term = (fact & ( (mulop & fact) * op2 )[:]) * red
# R(r'[0-9]+') applyed on "42" will return "42".
# R(r'[0-9]+') / int will return int("42")
# addop & fact applyied on "+ 42" will return ('+', 42)
# (addop & fact) * op1 will return op1(*('+', 42)), i.e. op1('+', 42)
# so (addop & fact) * op1 returns +42
# (addop & fact) * op2 will return op2(*('+', 42)), i.e. op2('+', 42)
# so (addop & fact) * op2 returns lambda x: add(x, 42)
# fact & ( (mulop & fact) * op2 )[:] returns a number and a list of functions
# for instance (42, [(lambda x:mul(x, 43)), (lambda x:mul(x, 44))])
# so (fact & ( (mulop & fact) * op2 )[:]) * red applyied on "42*43*44"
# will return red(42, [(lambda x:mul(x, 43)), (lambda x:mul(x, 44))])
# i.e. 42*43*44
And with the SP language:
number = r'[0-9]+' : `int` ;
addop = r'[+-]' ;
mulop = r'[*/]' ;
fact = addop fact :: `op1` ;
term = fact (mulop fact :: `op2`)* :: `red` ;
# r'[0-9]+' applyed on "42" will return "42".
# r'[0-9]+' : `int` will return int("42")
# "addop fact" applyied on "+ 42" will return ('+', 42)
# "addop fact :: `op1`" will return op1(*('+', 42)), i.e. op1('+', 42)
# so "addop fact :: `op1`" returns +42
# "addop fact :: `op2`" will return op2(*('+', 42)), i.e. op2('+', 42)
# so "addop fact :: `op2`" returns lambda x: add(x, 42)
# "fact (mulop fact :: `op2`)*" returns a number and a list of functions
# for instance (42, [(lambda x:mul(x, 43)), (lambda x:mul(x, 44))])
# so "fact (mulop fact :: `op2`)* :: `red`" applyied on "42*43*44"
# will return red(42, [(lambda x:mul(x, 43)), (lambda x:mul(x, 44))])
# i.e. 42*43*44
In the SP language, : (as /) applies a Python function (more
generally a callable object) to a value returned by a sequence and ::
(as *) applies a Python function to several values returned by a
sequence.
Here is finally the complete parser.
Expression recognizer and evaluator:
from sp import *
def Calc():
from operator import pos, neg, add, sub, mul, truediv as div
op1 = lambda f,x: {'+':pos, '-':neg}[f](x)
op2 = lambda f,y: lambda x: {'+': add, '-': sub, '*': mul, '/': div}[f](x,y)
def red(x, fs):
for f in fs: x = f(x)
return x
number = R(r'[0-9]+') / int
addop = R('[+-]')
mulop = R('[*/]')
with Separator(r'\s+'):
expr = Rule()
fact = Rule()
fact |= (addop & fact) * op1
fact |= '(' & expr & ')'
fact |= number
term = (fact & ( (mulop & fact) * op2 )[:]) * red
expr |= (term & ( (addop & term) * op2 )[:]) * red
return expr
Or with SP language:
from sp import *
def Calc():
from operator import pos, neg, add, sub, mul, truediv as div
op1 = lambda f,x: {'+':pos, '-':neg}[f](x)
op2 = lambda f,y: lambda x: {'+': add, '-': sub, '*': mul, '/': div}[f](x,y)
def red(x, fs):
for f in fs: x = f(x)
return x
return compile("""
number = r'[0-9]+' : `int` ;
addop = r'[+-]' ;
mulop = r'[*/]' ;
separator: r'\s+' ;
!expr = term (addop term :: `op2`)* :: `red` ;
term = fact (mulop fact :: `op2`)* :: `red` ;
fact = addop fact :: `op1` ;
fact = '(' expr ')' ;
fact = number ;
""")
Embedding the parser in a script
A parser is a simple Python object. This example show how to write a
function that returns a parser. The parser can be applied to strings by
simply calling the parser.
Writing SP grammars in Python:
from sp import *
def MyParser():
parser = ...
return parser
# You can instanciate your parser here
my_parser = MyParser()
# and use it
parsed_object = my_parser(string_to_be_parsed)
To use this parser you now just need to instantiate an object.
Complete Python script with expression parser:
from sp import *
def Calc():
...
calc = Calc()
while True:
expr = input('Enter an expression: ')
try: print(expr, '=', calc(expr))
except Exception as e: print("%s:"%e.__class__.__name__, e)
Conclusion
This tutorial shows some of the possibilities of SP. If you have read it
carefully you may be able to start with SP. The next chapters present SP
more precisely. They contain more examples to illustrate all the
features of SP.
Happy SP'ing!
SP reference
Usage
SP is a package which main function is to provide basic objects to build
a complete parser.
The grammar is a Python object.
Grammar embedding example:
def Foo():
bar = R('bar')
return bar
Then you can use the new generated parser. The parser is simply a Python
object.
Parser usage example:
test = "bar"
my_parser = Foo()
x = my_parser(test) # Parses "bar"
print x
Grammar structure
SP grammars are Python objects. SP grammars may contain two parts:
Tokens
are built by the R or K keywords.
Rules
are described after tokens in a Separator context.
Example of SP grammar structure:
def Foo():
# Tokens
number = R(r'\d+') / int
# Rules
with Separator(r'\s+'):
S = number[:]
return S
foo = Foo()
result = foo("42 43 44") # return [42, 43, 44]
Lexer
Regular expression syntax
The lexer is based on the re[^5] module. SP profits from the power of
Python regular expressions. This document assumes the reader is familiar
with regular expressions.
You can use the syntax of regular expressions as expected by the
re[^6] module.
Predefined tokens
Tokens can be explicitly defined by the R, K and Separator
keywords.
| Expression |
Usage |
R |
defines a regular token. The token is defined with a regular expression and returns a string (or a tuple of strings if the regular expression defines groups). |
K |
defines a token that returns nothing (useful for keywords for instance). The keyword is defined by an identifier (in this case word boundaries are expected around the keyword) or another string (in this case the pattern is not considered as a regular expression). The token just recognizes a keyword and returns nothing. |