3 def consume_newlines(index, tokens):
4 while index < len(tokens) and tokens[index].type == 'newline':
7 return True, index, None
9 def _or_parser(*parsers):
10 def result_parser(index, tokens):
11 failure = (False, index, None)
13 for parser in parsers:
14 success, index, value = parser(index, tokens)
17 return (success, index, value)
23 def _zero_or_more_parser(formatter, parser):
24 def result_parser(index, tokens):
27 while index < len(tokens):
28 success, index, value = parser(index, tokens)
35 return (True, index, formatter(values))
39 NodeMetadata = collections.namedtuple(
47 FurIntegerLiteralExpression = collections.namedtuple(
48 'FurIntegerLiteralExpression',
54 FurStringLiteralExpression = collections.namedtuple(
55 'FurStringLiteralExpression',
61 FurSymbolExpression = collections.namedtuple(
62 'FurSymbolExpression',
68 FurNegationExpression = collections.namedtuple(
69 'FurNegationExpression',
75 FurInfixExpression = collections.namedtuple(
86 FurListLiteralExpression = collections.namedtuple(
87 'FurListLiteralExpression',
89 'item_expression_list',
93 FurIfExpression = collections.namedtuple(
96 'condition_expression',
98 'else_statement_list',
102 FurSymbolExpressionPair = collections.namedtuple(
103 'FurSymbolExpressionPair',
110 FurStructureLiteralExpression = collections.namedtuple(
111 'FurStructureLiteralExpression',
117 def _integer_literal_expression_parser(index, tokens):
118 failure = (False, index, None)
120 if tokens[index].type != 'integer_literal':
122 value = int(tokens[index].match)
125 return True, index, FurIntegerLiteralExpression(integer=value)
127 def _string_literal_expression_parser(index, tokens):
128 if tokens[index].type == 'double_quoted_string_literal':
129 return (True, index + 1, FurStringLiteralExpression(string=tokens[index].match[1:-1]))
131 if tokens[index].type == 'single_quoted_string_literal':
132 return (True, index + 1, FurStringLiteralExpression(string=tokens[index].match[1:-1]))
134 return (False, index, None)
136 def _symbol_expression_parser(index, tokens):
137 if tokens[index].type == 'symbol':
138 return (True, index + 1, FurSymbolExpression(symbol=tokens[index].match))
140 return (False, index, None)
142 def _wrapped_parser(open_token, close_token, internal_parser):
143 def result_parser(index, tokens):
144 failure = (False, index, None)
146 if tokens[index].type == open_token:
151 success, index, internal = internal_parser(index, tokens)
155 if tokens[index].type == close_token:
158 # TODO Put the actual expected character in the error message
159 raise Exception('Expected closing token on line {}, found "{}"'.format(
164 return True, index, internal
168 def _bracket_wrapped_parser(internal_parser):
169 return _wrapped_parser('open_bracket', 'close_bracket', internal_parser)
171 def _parenthese_wrapped_parser(internal_parser):
172 return _wrapped_parser('open_parenthese', 'close_parenthese', internal_parser)
174 def _parenthesized_expression_parser(index, tokens):
175 return _parenthese_wrapped_parser(_expression_parser)(index, tokens)
177 def symbol_expression_pair_parser(index, tokens):
178 failure = (False, index, None)
180 if tokens[index].type == 'symbol':
181 symbol = tokens[index].match
186 if tokens[index].type == 'colon':
191 success, index, expression = _expression_parser(index, tokens)
199 FurSymbolExpressionPair(
201 expression=expression,
205 def _structure_literal_parser(index, tokens):
206 success, index, result = _parenthese_wrapped_parser(_comma_separated_list_parser(symbol_expression_pair_parser))(index, tokens)
210 FurStructureLiteralExpression(
215 def _list_literal_expression_parser(index, tokens):
216 failure = (False, index, None)
218 success, index, item_expression_list = _bracket_wrapped_parser(_comma_separated_expression_list_parser)(index, tokens)
221 return success, index, FurListLiteralExpression(
222 item_expression_list=item_expression_list,
227 def _literal_level_expression_parser(index, tokens):
229 _list_item_expression_parser,
230 _function_call_expression_parser,
231 _parenthesized_expression_parser,
232 _integer_literal_expression_parser,
233 _string_literal_expression_parser,
234 _list_literal_expression_parser,
235 _symbol_expression_parser,
236 _structure_literal_parser,
239 def _dot_expression_parser(index, tokens):
240 return _left_recursive_infix_operator_parser(
241 lambda token: token.type == 'period',
242 _literal_level_expression_parser,
246 def _negation_expression_parser(index, tokens):
247 failure = (False, index, None)
249 if tokens[index].match != '-':
252 success, index, value = _dot_expression_parser(index + 1, tokens)
257 return (True, index, FurNegationExpression(value=value))
259 def _negation_level_expression_parser(index, tokens):
261 _dot_expression_parser,
262 _negation_expression_parser,
265 def _left_recursive_infix_operator_parser(operator_token_matcher, operand_parser, order):
266 def result_parser(index, tokens):
267 failure = (False, index, None)
269 success, index, result = operand_parser(index, tokens)
274 while success and index < len(tokens) and operator_token_matcher(tokens[index]):
277 if index + 1 < len(tokens):
278 success, try_index, value = operand_parser(index + 1, tokens)
281 result = FurInfixExpression(
282 metadata=NodeMetadata(
283 index=tokens[index].index,
284 line=tokens[index].line,
287 operator=tokens[index].match,
293 return True, index, result
297 def _multiplication_level_expression_parser(index, tokens):
298 return _left_recursive_infix_operator_parser(
299 lambda token: token.type == 'multiplication_level_operator',
300 _negation_level_expression_parser,
301 'multiplication_level',
304 def _addition_level_expression_parser(index, tokens):
305 return _left_recursive_infix_operator_parser(
306 lambda token: token.type == 'addition_level_operator',
307 _multiplication_level_expression_parser,
311 def _comparison_level_expression_parser(index, tokens):
312 return _left_recursive_infix_operator_parser(
313 lambda token: token.type == 'comparison_level_operator',
314 _addition_level_expression_parser,
318 def _and_level_expression_parser(index, tokens):
319 return _left_recursive_infix_operator_parser(
320 lambda token: token.type == 'symbol' and token.match == 'and',
321 _comparison_level_expression_parser,
325 def _or_level_expression_parser(index, tokens):
326 return _left_recursive_infix_operator_parser(
327 lambda token: token.type == 'symbol' and token.match == 'or',
328 _and_level_expression_parser,
332 def _comma_separated_list_parser(subparser):
333 def result_parser(index, tokens):
338 _, index, _ = consume_newlines(index, tokens)
340 success, index, item = subparser(index, tokens)
345 return (True, start_index, ())
347 while success and index < len(tokens) and tokens[index].type == 'comma':
351 _, index, _ = consume_newlines(index, tokens)
353 if index < len(tokens):
354 success, try_index, item = subparser(index, tokens)
360 return True, index, tuple(items)
364 def _comma_separated_expression_list_parser(index, tokens):
365 return _comma_separated_list_parser(_expression_parser)(index, tokens)
367 FurListItemExpression = collections.namedtuple(
368 'FurListItemExpression',
375 FurFunctionCallExpression = collections.namedtuple(
376 'FurFunctionCallExpression',
383 FurExpressionStatement = collections.namedtuple(
384 'FurExpressionStatement',
390 FurAssignmentStatement = collections.namedtuple(
391 'FurAssignmentStatement',
398 FurFunctionDefinitionStatement = collections.namedtuple(
399 'FurFunctionDefinitionStatement',
402 'argument_name_list',
407 FurProgram = collections.namedtuple(
414 def _list_item_expression_parser(index, tokens):
415 failure = (False, index, None)
417 # We have to be careful what expressions we add here. Otherwise expressions
418 # like "a + b[0]" become ambiguous to the parser.
419 success, index, list_expression = _or_parser(
420 _symbol_expression_parser,
421 _parenthesized_expression_parser,
427 success, index, index_expression = _bracket_wrapped_parser(_expression_parser)(
435 while success and index < len(tokens):
436 # "list_expression" is actually the full list item expression if the next parse attempt doesn't succeed
437 # We can't give this a better name without a bunch of checks, however.
438 list_expression = FurListItemExpression(
439 list_expression=list_expression,
440 index_expression=index_expression,
443 success, index, index_expression = _bracket_wrapped_parser(_expression_parser)(
448 return True, index, list_expression
450 def _function_call_expression_parser(index, tokens):
451 failure = (False, index, None)
453 # We have to be careful what expressions we add here. Otherwise expressions
454 # like "a + b()" become ambiguous to the parser.
455 success, index, function = _or_parser(
456 _symbol_expression_parser,
457 _parenthesized_expression_parser,
463 success, index, arguments = _parenthese_wrapped_parser(_comma_separated_expression_list_parser)(
471 while success and index < len(tokens):
472 # "function" is actually the full function call if the next parse attempt doesn't succeed
473 # We can't give this a better name without a bunch of checks, however.
474 function = FurFunctionCallExpression(
479 success, index, arguments = _parenthese_wrapped_parser(_comma_separated_expression_list_parser)(
484 return True, index, function
486 def _if_expression_parser(index, tokens):
487 failure = (False, index, None)
489 if tokens[index].match == 'if':
494 success, index, condition_expression = _or_level_expression_parser(index, tokens)
497 raise Exception('Expected condition after "if" on line {}'.format(tokens[index].line))
499 if tokens[index].match == 'do':
502 raise Exception('Expected "do" after "if" on line {}'.format(tokens[index].line))
505 success, index, if_statement_list = _zero_or_more_parser(tuple, _statement_parser)(index, tokens)
506 _, index, _ = consume_newlines(index, tokens)
508 if tokens[index].match == 'else':
510 success, index, else_statement_list = _zero_or_more_parser(tuple, _statement_parser)(index, tokens)
511 _, index, _ = consume_newlines(index, tokens)
513 else_statement_list = ()
515 if tokens[index].match == 'end':
518 raise Exception('Expected "end" after "if" on line {}'.format(tokens[index].line))
524 condition_expression=condition_expression,
525 if_statement_list=if_statement_list,
526 else_statement_list=else_statement_list,
530 _expression_parser = _or_parser(
531 _or_level_expression_parser,
532 _if_expression_parser, # This should always be at the top level
535 def _expression_statement_parser(index, tokens):
536 failure = (False, index, None)
538 success, index, expression = _expression_parser(index, tokens)
543 return (True, index, FurExpressionStatement(expression=expression))
545 BUILTINS = {'print', 'pow'}
547 def _assignment_statement_parser(index, tokens):
548 failure = (False, index, None)
550 if tokens[index].type == 'symbol':
551 target = tokens[index].match
552 target_assignment_line = tokens[index].line
559 if tokens[index].type == 'assignment_operator':
560 if target in BUILTINS:
562 'Trying to assign to builtin "{}" on line {}'.format(target, target_assignment_line),
564 assignment_operator_index = index
568 success, index, expression = _expression_parser(index + 1, tokens)
572 'Expected expression after assignment operator on line {}'.format(
573 tokens[assignment_operator_index].line
577 return True, index, FurAssignmentStatement(target=target, expression=expression)
579 def _function_definition_statement_parser(index, tokens):
580 failure = (False, index, None)
582 if tokens[index].type == 'keyword' and tokens[index].match == 'def':
587 if tokens[index].type == 'symbol':
588 name = tokens[index].match
591 raise Exception('Expected function name, found "{}" on line {}'.format(
596 if tokens[index].type == 'open_parenthese':
599 raise Exception('Expected "(", found "{}" on line {}'.format(
604 success, index, argument_name_list = _comma_separated_list_parser(_symbol_expression_parser)(
609 if tokens[index].type == 'close_parenthese':
612 raise Exception('Expected ")", found "{}" on line {}'.format(
617 if tokens[index].match == 'do':
622 success, index, statement_list = _zero_or_more_parser(tuple, _statement_parser)(index, tokens)
624 _, index, _ = consume_newlines(index, tokens)
626 if tokens[index].type == 'keyword' and tokens[index].match == 'end':
631 return True, index, FurFunctionDefinitionStatement(
633 argument_name_list=tuple(an.symbol for an in argument_name_list),
634 statement_list=statement_list,
637 def _statement_parser(index, tokens):
638 _, index, _ = consume_newlines(index, tokens)
640 if index == len(tokens):
641 return (False, index, None)
644 _assignment_statement_parser,
645 _expression_statement_parser,
646 _function_definition_statement_parser,
649 def _program_formatter(statement_list):
650 return FurProgram(statement_list=statement_list)
652 _program_parser = _zero_or_more_parser(_program_formatter, _statement_parser)
654 def _parse(parser, tokens):
655 success, index, result = parser(0, tokens)
657 if index < len(tokens):
658 raise Exception('Unable to parse token {}'.format(tokens[index]))
663 raise Exception('Unable to parse')
666 return _parse(_program_parser, tokens)
668 if __name__ == '__main__':
673 class FurStringLiteralExpressionParserTests(unittest.TestCase):
674 def test_parses_single_quoted_string_literal(self):
676 _string_literal_expression_parser(0, tokenization.tokenize("'Hello, world'")),
680 FurStringLiteralExpression(string='Hello, world'),
684 class FurFunctionCallExpressionParserTests(unittest.TestCase):
685 def test_parses_function_with_string_literal_argument(self):
687 _function_call_expression_parser(0, tokenization.tokenize("print('Hello, world')")),
691 FurFunctionCallExpression(
693 arguments=(FurStringLiteralExpression(string='Hello, world'),),