Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce NonConsumingExact which doesn't consume whitespace at the beginning of the string #17

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions parcon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,15 @@ def __repr__(self):
return "Exact(" + repr(self.parser) + ")"


class NonConsumingExact(Exact):
"""
Like Exact(), except that it does not use the whitespace argument of
parse_string() to consume leading whitespace.
"""
def parse(self, text, position, end, space):
return self.parser.parse(text, position, end, self.space_parser)


class Optional(_GRParser):
"""
A parser that returns whatever its underlying parser returns, except that
Expand Down
25 changes: 25 additions & 0 deletions parcon/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,31 @@ def case(): #@DuplicatedSignature
assert x.parse_string("5") == 5


@test(parcon.Exact)
def case(): #@DuplicatedSignature
ws = parcon.Word(parcon.whitespace)
x = parcon.Exact(parcon.alpha_word + ws + parcon.alpha_word)
assert x.parse_string('foo \t\r\n bar') == ('foo', ' \t\r\n ', 'bar')
x = parcon.Exact(ws + parcon.alpha_word)
assert (
x.parse_string(' \t\r\n bar', whitespace=parcon.Word(' ')) ==
('\t\r\n ', 'bar'))


@test(parcon.NonConsumingExact)
def case(): #@DuplicatedSignature
ws = parcon.Word(parcon.whitespace)
x = parcon.NonConsumingExact(ws + parcon.alpha_word)
assert x.parse_string(' \t\r\n bar') == (' \t\r\n ', 'bar')


@test(parcon.Invalid)
def case(): #@DuplicatedSignature
x = (parcon.Word(parcon.whitespace) + parcon.alpha_word)
assert (
x.parse_string(' \t bar', whitespace=parcon.Invalid()) ==
(' \t ', 'bar'))

def run_tests():
targets = set()
targets |= set(subclasses_in_module(parcon.Parser, ("parcon",)))
Expand Down