def test_that_alternation_works(): ''' Tests that an alternation parser returns the parse results of either one of the composed parsers. ''' parser = str_('hello world') | str_('hello') assert parser.loads('hello') == 'hello' assert parser.loads('hello world') == 'hello world'
def test_that_recursion_works(): ''' Tests that a recursion parser can be constructed by usage of `Parser` and the `parser[...] = ...` notation. Checks if the rule `p = \'b\'|\'a\'p` works. ''' parser = Parser() parser[...] = str_('b') | str_('a') >> parser assert parser.loads('b') == 'b' assert parser.loads('ab') == ('a', 'b') assert parser.loads('aab') == ('a', ('a', 'b')) assert parser.loads('aaab') == ('a', ('a', ('a', 'b')))
def test_that_chaining_functions_work(): ''' Tests that the function chaining parser returns the result of the function call with the parse result as argument. ''' parser = str_('42')[int] assert parser.loads('42') == 42
def test_that_repetition_works(): ''' Tests that a repetition parser returns a list of parse results. ''' parser = +str_('abc') try: parser.loads('') except ParseError: assert True assert parser.loads('abc') == ['abc'] assert parser.loads('abcabc') == ['abc', 'abc'] parser = ~str_('abc') assert parser.loads('') == [] assert parser.loads('abc') == ['abc'] assert parser.loads('abcabc') == ['abc', 'abc']
def test_that_optional_works(): ''' Tests that an optional parser returns either the parse result or None. ''' parser = -str_('hello world') assert parser.loads('hello world') == 'hello world' assert parser.loads('hello') is None
def test_that_string_parser_works(): ''' Tests that a string parser constructed by `str_` accepts the argument string. ''' parser = str_("test") assert parser.loads("test") == "test" try: parser.loads("town") except ParseError: assert True
def test_that_concatenation_works(): ''' Tests that a concatenation parser should return a tuple of parse results ''' parser = str_('hello') >> str_(' ') >> str_('world') assert parser.loads('hello world') == ('hello', ' ', 'world')
''' A Json parser. ''' from aptwe import Parser, str_, char_, getitem, concat from aptwe.addons import float_, int_, space_ _parser = Parser('Json') __esc_char_ = (str_('\\') >> char_())[getitem(1)] | char_('"').inv() _string = (str_('"') >> (~__esc_char_)[concat] >> str_('"'))[getitem(1)] @ 'string' _whitespace = ~space_ _dict_key = (_whitespace >> _string >> _whitespace)[getitem(1)] @ 'dict_key' _dict_entry = (_dict_key >> str_(':') >> _parser)[getitem((0, 2))] _dict = (str_('{') >> (_dict_entry % str_(','))[dict] >> str_('}'))[getitem(1)] @ 'dict' _list = (str_('[') >> _parser % str_(',') >> str_(']'))[getitem(1)] @ 'list' _parser[...] = ( _whitespace >> (float_ | int_ | _string | _dict | _list) >> _whitespace)[getitem(1)] load = _parser.load loads = _parser.loads