Skip to main content

Another language grammar parser. Inspired by modgrammar and pyparsing

Project description


I needed a language grammar parser for the plywood_ project, and modgrammar_
looked like it would be perfect, except I couldn't get the simplest of grammars
to work. pyparsing_ is excellent, but doesn't give me objects back, only lists
and strings - I need more than that. I would recommend pyparsing_ for *your*
project. Unless you really want objects, or if you are doing a language
(chomsky_ has lots of built-in stuff for making programming language grammars).

Besides, I like writing parsers, and I know how I want this one to work, so
screw it, I'll do it myself!



$ pip install chomsky



``Matcher`` objects are the most basic building blocks. They are not smart,
they return only strings and lists, and they make no assumptions about what you
might be trying to build. For instance, the ``Word`` Matcher does not assume
that you want to consume whitespace.

``Matcher`` objects are great for building a small parsing language for
consistent data, where ``Grammar`` objects are not needed. But for building a
language parser, you will probably use the more heavy-duty Grammar building


Matches a single letter from a string of accepted letters. There are lots of
built-in strings in the `string module`_.



matcher = Letter('abcde')
matcher('a') => 'a'
matcher('bcd') => 'b'
matcher('f') => raise ParseException
# shorthand:
matcher = A('abcde')

import string
matcher = A(string.letters + string.digits + '_')


Matches one or more letters from string of accepted letters.

You can also set ``min`` and ``max`` options. ``min`` will raise a
``ParseException`` if the matched word is not long enough. Default is ``1``.
``max`` will stop matching once ``max`` characters are matched.


matcher = Word('abcde')
matcher('a') => 'a'
matcher('bcd') => 'bcd'
matcher('defg') => 'defg'
matcher('fghi') => ParseException

# max
matcher = Word('abcde', max=2)
matcher('bcd') => 'bc'

# min
matcher = Word('abcde', min=3)
matcher('ab') => ParseException


Matches a literal string.


matcher = Literal('abcde')
matcher('a') => 'a'
matcher('bcd') => 'bcd'
matcher('defg') => 'defg'
matcher('fghi') => ParseException



matcher = Whitespace() # default is " \t"
matcher(" ") => " "
matcher(" \t\n ") => " \t"
matcher = Whitespace(" \t\n")
matcher(" \t\n ") => " \t\n "


These have two options: ``group`` and ``advance``.

``group`` says which group or groups to return. Default is ``0`` (the entire
match). A list or tuple of groups will return a list of results. ``advance``
indicates what group to advance *past*. Default is ``0`` (the entire match).
This is a quick way to build a matching system that can parse consistently
formatted data, for example.


matcher = Regex("([a-zA-Z_][0-9])")
matcher('a1') => 'a1'

# group
matcher = Regex("([a-zA-Z_][0-9])", group=1)
matcher('a1') => 'a'

# to demonstrate `advance`, I will have to add two regex Matchers, which
# returns a list
matcher = Regex("([a-zA-Z_][0-9])", group=1, advance=1) + Regex("([0-9])", group=1)
matcher('a1') => ['a', '1']


There are two flavors of ``Sequence``. One you can declare yourself, called
``Sequence``, the other is created automatically when you add or multiply
Matcher objects. Don't worry about that one, it "just works" (we saw it above
in the ``Regex`` example).


matcher = Sequence(Literal('Hello '), Literal('World'), Letter('!.'))
matcher('Hello World!') => ['Hello ', 'World', '!']
matcher('Hello World.') => ['Hello ', 'World', '.']
matcher('Hello, World.') => ParseException

The automatic ``Sequence`` type is created whenever you use addition or
multiplication to repeat a series of ``Matcher``s.


matcher = Literal('Hello ') + Literal('World') + Letter('!.')
matcher('Hello World!') => ['Hello ', 'World', '!']
matcher('Hello World.') => ['Hello ', 'World', '.']
matcher('Hello, World.') => ParseException


import string
matcher = (Word(string.letters) + Literal(' ')) * 3
matcher('why hello there ') => [['why', ' '], ['hello', ' '], ['there', ' ']]
matcher('not enough spaces') => ParseException


``NMatches`` is not an intuitively named class, but its child classes are, and
you'll probably use them a lot.


matcher = ZeroOrMore(Literal('hi'))
matcher('') => []
matcher('hi') => ['hi']
matcher('hihi') => ['hi', 'hi']


matcher = OneOrMore(Literal('hi'))
matcher('hi') => ['hi']
matcher('hihi') => ['hi', 'hi']
matcher('') => ParseException


matcher = Literal('Hello') + Optional(Literal(',')) + Literal(' ') + Literal('World')
matcher('Hello World') => ['Hello', [], ' ', 'World']
matcher('Hello, World') => ['Hello', [','], ' ', 'World']
matcher('Hello, Bozo') => ParseException


matcher = NMatches(Literal('hi'), min=2, max=3)
matcher('hi') => ParseException
matcher('hihi') => ['hi', 'hi']
matcher('hihihi') => ['hi', 'hi', 'hi']
matcher('hihihihi') => ['hi', 'hi', 'hi'] # only 3 matches


Given a list of Matchers, any of them can match (tested in order left-to-right).
The first to match is returned.


matcher = Any(Literal('Joey'), Literal('Bob'), Literal('Bill'))
matcher('Bob') => 'Bob'
matcher('Jane') => ParseException

Look-ahead and Behind

Looking-ahead is simple and low-cost. The ``NextIs`` matcher makes sure that
the ``Matcher`` *would* pass, but then rolls back the cursor and does not return
a Result. If the ``Matcher`` fails, an exception is raised.

Looking behind is much more expensive, because the number of characters to look
at is not known before hand. A "best guess" can be made by ``PrevIs`` by using
```minimum_length``` and ```maximum_length``` methods that the ``Matcher``
classes all implement (the base class returns ``0`` and ``float('inf')``). A
``Literal``, for example, has a definite length that must be present - no more,
and no less characters. The other classes also provide this min/max length
calculation. But this provides only a modest performance increase.

The ``Prev`` matcher does not require that the previous token be an instance of
the specified matcher, only that the buffer previous to the current location
match. The buffer is rolled back until a match is found, or until the beginning
of the buffer is reached.


matcher = '-' + NextIs(Word('123456789')) + Word('1234567890')
matcher('1') => [[], '1']
matcher('-1') => [['-'], '1']
matcher('-123') => [['-'], '123']
matcher('-0') => ParseException


matcher = '-' + NextIsNot('0') + Word('1234567890')
matcher('1') => [[], '1']
matcher('-1') => [['-'], '1']
matcher('-123') => [['-'], '123']
matcher('-0') => ParseException

**language building blocks**::

QuotedString, Number, Integer, Float, Hexadecimal, Octal, Binary
LineComment, BlockComment, Block, IndentedBlock


NextIs, PreviousWas, NextIsNot, PreviousWasNot
WordStart, WordEnd, LineStart, LineEnd,
StringStart, StringEnd



$ pip install pytest
$ py.test


:Author: Colin Thomas-Arnold
:Copyright: 2012 Colin Thomas-Arnold <>

Copyright (c) 2012, Colin Thomas-Arnold
All rights reserved.

See LICENSE_ for more details (it's a simplified BSD license).

.. _modgrammar:
.. _pyparsing:
.. _plywood:
.. _string module:

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for chomsky, version v0.0.4
Filename, size File type Python version Upload date Hashes
Filename, size chomsky-v0.0.4.tar.gz (9.4 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page