3 def _or_parser(*parsers):
4 def result_parser(index, tokens):
5 failure = (False, index, None)
8 success, index, value = parser(index, tokens)
11 return (success, index, value)
17 def _zero_or_more_parser(formatter, parser):
18 def result_parser(index, tokens):
21 while index < len(tokens):
22 success, index, value = parser(index, tokens)
29 return (True, index, formatter(values))
33 IntegerLiteral = collections.namedtuple(
40 StringLiteral = collections.namedtuple(
47 def _integer_literal_parser(index, tokens):
48 failure = (False, index, None)
50 if tokens[index].type != 'integer_literal':
52 value = int(tokens[index].match)
55 return True, index, IntegerLiteral(value=value)
57 def _string_literal_parser(index, tokens):
58 failure = (False, index, None)
60 if tokens[index].type != 'single_quoted_string_literal':
62 value = tokens[index].match[1:-1]
65 return True, index, StringLiteral(value=value)
67 _argument_parser = _or_parser(_integer_literal_parser, _string_literal_parser)
69 FunctionCall = collections.namedtuple(
77 FurProgram = collections.namedtuple(
84 def _function_call_parser(index, tokens):
85 failure = (False, index, None)
87 if tokens[index].type != 'symbol':
89 name = tokens[index].match
92 if tokens[index].type != 'open_parenthese':
96 success, index, argument = _argument_parser(index, tokens)
101 if tokens[index].type != 'close_parenthese':
105 return True, index, FunctionCall(name=name, arguments=(argument,))
107 def _program_formatter(statement_list):
108 return FurProgram(statement_list=statement_list)
110 _program_parser = _zero_or_more_parser(_program_formatter, _function_call_parser)
112 def _parse(parser, tokens):
113 success, index, result = parser(0, tokens)
115 if index < len(tokens):
116 raise Exception('Unable to parse token {}'.format(tokens[index]))
121 raise Exception('Unable to parse')
125 return _parse(_program_parser, tokens)
127 if __name__ == '__main__':
132 class StringLiteralParserTests(unittest.TestCase):
133 def test_parses_single_quoted_string_literal(self):
135 _string_literal_parser(0, tokenization.tokenize("'Hello, world'")),
139 StringLiteral(value='Hello, world'),
143 class FunctionCallParserTests(unittest.TestCase):
144 def test_parses_function_with_string_literal_argument(self):
146 _function_call_parser(0, tokenization.tokenize("print('Hello, world')")),
152 arguments=(StringLiteral(value='Hello, world'),),