Skip to content

Commit

Permalink
Optional pattern.
Browse files Browse the repository at this point in the history
  • Loading branch information
eerimoq committed Jul 22, 2018
1 parent 41f7aeb commit 5d149e5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
33 changes: 33 additions & 0 deletions tests/test_textparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from textparser import Any
from textparser import Inline
from textparser import Forward
from textparser import Optional


def tokenize(items):
Expand Down Expand Up @@ -301,6 +302,38 @@ def test_forward(self):
tree = grammar.parse(tokenize(tokens + [('__EOF__', '')]))
self.assertEqual(tree, expected_tree)

def test_optional(self):
grammar = Grammar(Sequence(Optional('WORD'),
Optional('WORD'),
Optional('NUMBER')))

datas = [
(
[],
[[], [], []]
),
(
[('WORD', 'a')],
[['a'], [], []]
),
(
[('NUMBER', 'c')],
[[], [], ['c']]
),
(
[('WORD', 'a'), ('NUMBER', 'c')],
[['a'], [], ['c']]
),
(
[('WORD', 'a'), ('WORD', 'b'), ('NUMBER', 'c')],
[['a'], ['b'], ['c']]
)
]

for tokens, expected_tree in datas:
tree = grammar.parse(tokenize(tokens + [('__EOF__', '')]))
self.assertEqual(tree, expected_tree)


if __name__ == '__main__':
unittest.main()
17 changes: 17 additions & 0 deletions textparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,23 @@ def match(self, tokens):
return self._element.match(tokens)


class Optional(object):
"""Matches a pattern zero or one times.
"""

def __init__(self, element):
self._element = _wrap_string(element)

def match(self, tokens):
mo = self._element.match(tokens)

if mo is None:
return []
else:
return [mo]


class Forward(object):

def __init__(self):
Expand Down

0 comments on commit 5d149e5

Please sign in to comment.