3 IntegerLiteral = collections.namedtuple(
10 StringLiteral = collections.namedtuple(
17 def _integer_literal_parser(index, tokens):
18 failure = (False, index, None)
20 if tokens[index].type != 'integer_literal':
22 value = int(tokens[index].match)
25 return True, index, IntegerLiteral(value=value)
27 def _string_literal_parser(index, tokens):
28 failure = (False, index, None)
30 if tokens[index].type != 'single_quoted_string_literal':
32 value = tokens[index].match[1:-1]
35 return True, index, StringLiteral(value=value)
37 def _argument_parser(index, tokens):
38 failure = (False, index, None)
40 for parser in [_integer_literal_parser, _string_literal_parser]:
41 success, index, value = parser(index, tokens)
44 return (success, index, value)
49 FunctionCall = collections.namedtuple(
57 def _function_call_parser(index, tokens):
58 failure = (False, index, None)
60 if tokens[index].type != 'symbol':
62 name = tokens[index].match
65 if tokens[index].type != 'open_parenthese':
69 success, index, argument = _argument_parser(index, tokens)
74 if tokens[index].type != 'close_parenthese':
78 return True, index, FunctionCall(name=name, arguments=(argument,))
80 def _parse(parser, tokens):
81 success, index, result = parser(0, tokens)
86 raise Exception('Unable to parse')
90 return _parse(_function_call_parser, tokens)
92 if __name__ == '__main__':
97 class StringLiteralParserTests(unittest.TestCase):
98 def test_parses_single_quoted_string_literal(self):
100 _string_literal_parser(0, tokenization.tokenize("'Hello, world'")),
104 StringLiteral(value='Hello, world'),
108 class FunctionCallParserTests(unittest.TestCase):
109 def test_parses_function_with_string_literal_argument(self):
111 _function_call_parser(0, tokenization.tokenize("print('Hello, world')")),
117 arguments=(StringLiteral(value='Hello, world'),),