This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB

  1. """
  2. Extend the Python Grammar
  3. ==============================
  4. This example demonstrates how to use the `%extend` statement,
  5. to add new syntax to the example Python grammar.
  6. """
  7. from lark.lark import Lark
  8. from python_parser import PythonIndenter
  9. GRAMMAR = r"""
  10. %import .python3 (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
  11. %extend compound_stmt: match_stmt
  12. match_stmt: "match" test ":" cases
  13. cases: _NEWLINE _INDENT case+ _DEDENT
  14. case: "case" test ":" suite // test is not quite correct.
  15. %ignore /[\t \f]+/ // WS
  16. %ignore /\\[\t \f]*\r?\n/ // LINE_CONT
  17. %ignore COMMENT
  18. """
  19. parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
  20. tree = parser.parse(r"""
  21. def name(n):
  22. match n:
  23. case 1:
  24. print("one")
  25. case 2:
  26. print("two")
  27. case _:
  28. print("number is too big")
  29. """, start='file_input')
  30. # Remove the 'python3__' prefix that was add to the implicitely imported rules.
  31. for t in tree.iter_subtrees():
  32. t.data = t.data.rsplit('__', 1)[-1]
  33. print(tree.pretty())