from __future__ import division
__doc__ = r"""Parsnip: Packrat parser for attributed Parsing Expression Grammars.
(well, it will be a packrat parser eventually)
A non-context-free grammar just for fun. (a^n b^n c^n)
>>> ncf = "\n".join(['S := &(A ![ab]) "a"* B !.',
... 'A := "a" A "b" / empty',
... 'B := "b" B "c" / empty'])
>>> P = Parser(ncf)
>>> P.parse("aaabbbccc") # silently succeeds
>>> P.parse("aabbbccc")
Traceback (most recent call last):
ParseError
>>> P.parse("aaabbccc")
Traceback (most recent call last):
ParseError
>>> P.parse("aaabbbcc")
Traceback (most recent call last):
ParseError
>>> P.parse("aaaabbbccc")
Traceback (most recent call last):
ParseError
>>> P.parse("aaabbbbccc")
Traceback (most recent call last):
ParseError
>>> P.parse("aaabbbcccc")
Traceback (most recent call last):
ParseError
>>> P.parse("aaaabbbcc")
Traceback (most recent call last):
ParseError
The same grammar, attributed to count the number of repititions.
>>> ncf = "\n".join(['S := &(A ![ab]) "a"* n:B !. {n}',
... 'A := "a" A "b" / empty',
... 'B := "b" n:B "c" {n+1} / empty {0}'])
>>> Parser(ncf).parse("aaabbbccc")
3
"""
license = """Copyright (c) 2004 William Isaac Carroll
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE."""
# TODO:
# report cause of match failure
# memoize into a packrat parser
# recognize left recursion
# transform left recursion
# transform repitition
# prettyprint grammar rules (recreate PEG from data structure)
class Pattern:
def __repr__(self):
return self.__class__.__name__ + "(" + self.args + ")"
class Literal(Pattern):
"""
Match a literal string.
>>> Literal("foo").match("foo", 0)
(3, None)
>>> Literal("foo").match("bar", 0)
False
>>> Literal("bar").match("foo", 0)
False
>>> Literal("foo").match("foobar", 0)
(3, None)
>>> Literal("foo").match("foobar", 1)
False
>>> Literal("oo").match("foobar", 1)
(2, None)
"""
def __init__(self, lit):
self.lit = lit
self.args = repr(lit)
def match(self, text, pos, env=None):
if text.startswith(self.lit, pos):
return (len(self.lit), None)
else:
return False
class Range(Pattern):
"""
Match a single character from a range of characters.
>>> Range("a", "c").match("b", 0)
(1, None)
>>> Range("c", "e").match("b", 0)
False
>>> Range("a", "c").match("d", 0)
False
>>> Range("a", "c").match("c", 0)
(1, None)
>>> Range("a", "c").match("a", 0)
(1, None)
>>> Range("a", "c").match("ca", 0)
(1, None)
>>> Range("a", "c").match("cd", 0)
(1, None)
>>> Range("a", "c").match("ca", 1)
(1, None)
>>> Range("a", "c").match("cd", 1)
False
>>> Range("a", "c").match("", 0)
False
"""
def __init__(self, start, end):
self.start = start
self.end = end
self.args = ", ".join([repr(start), repr(end)])
def match(self, text, pos, env=None):
try:
char = text[pos]
except IndexError:
return False
if self.start <= char <= self.end:
return (1, None)
else:
return False
class AnyCharT(Range):
"""
Match any single character.
>>> AnyChar.match("a", 0)
(1, None)
>>> AnyChar.match("", 0)
False
"""
def __init__(self):
Range.__init__(self, chr(0), chr(127))
def __repr__(self):
return "AnyChar"
AnyChar = AnyCharT()
class Require(Pattern):
"""
Positive syntactic predicate.
>>> Require(Literal("a")).match("a", 0)
(0, None)
>>> Require(Literal("a")).match("b", 0)
False
"""
def __init__(self, pattern):
self.pattern = pattern
self.args = repr(pattern)
def match(self, text, pos, env=None):
if self.pattern.match(text, pos) == False:
return False
else:
return (0, None)
class Reject(Pattern):
"""
Negative syntactic predicate.
>>> Reject(Literal("a")).match("a", 0)
False
>>> Reject(Literal("a")).match("b", 0)
(0, None)
"""
def __init__(self, pattern):
self.pattern = pattern
self.args = repr(pattern)
def match(self, text, pos, env=None):
if self.pattern.match(text, pos) == False:
return (0, None)
else:
return False
class Labeled(Exception):
"""Not pretty, but it works."""
pass
class Label(Pattern):
"""
Assign the value of a pattern to a variable.
"""
def __init__(self, name, pattern):
self.name = name
self.pattern = pattern
self.args = ", ".join([repr(name), repr(pattern)])
def match(self, text, pos, env=None):
result = self.pattern.match(text, pos, env)
if result == False:
return False
else:
count,value = result
raise Labeled(self.name, count, value)
class Seq(Pattern):
"""
Match a sequence of patterns.
>>> Seq([Literal("a"), Literal("b")]).match("ab", 0)
(2, None)
>>> Seq([Literal("a"), Literal("c")]).match("ab", 0)
False
>>> Seq([Literal("a"), Literal("b")]).match("a", 0)
False
>>> Seq([Literal("a"), Literal("b")]).match("bab", 1)
(2, None)
>>> S = Seq([Literal("a"), Reject(Literal("b")), Range("b", "c")])
>>> S.match("ac", 0)
(2, None)
>>> S.match("ab", 0)
False
>>> Seq([]).match("abc", 0)
(0, None)
>>> Seq([Literal("a")], value="5").match("abc", 0)
(1, 5)
>>> Seq([Literal("a")], value="2+2").match("abc", 0)
(1, 4)
>>> Seq([Literal("a")], value="x", env=dict(x=5)).match("abc", 0)
(1, 5)
"""
def __init__(self, patterns, value=None, env=None):
self.patterns = patterns
self.value = value
self.env = env
if self.env is None:
self.env = {}
pats = [repr(pattern) for pattern in patterns]
if self.value is not None:
pats += ["value=" + repr(self.value)]
self.args = ", ".join(pats)
def match(self, text, startpos, env=None):
curpos = startpos
if env is None:
env = {}
else:
env = dict(env)
for pattern in self.patterns:
try:
result = pattern.match(text, curpos, env)
except Labeled, L:
name,count,value = L.args
result = (count, value)
env[name] = value
if result == False:
return False
else:
count,_ = result
curpos += count
if self.value is None:
value