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.

60 lines
1.3 KiB

  1. from pathlib import Path
  2. from lark.indenter import Indenter
  3. from lark.lark import Lark
  4. from lark.load_grammar import GrammarBuilder
  5. MATCH_GRAMMAR = ('match', """
  6. %extend compound_stmt: match_stmt
  7. match_stmt: "match" test ":" cases
  8. cases: _NEWLINE _INDENT case+ _DEDENT
  9. case: "case" test ":" suite // test is not quite correct.
  10. """, ('compound_stmt', 'test', 'suite', '_DEDENT', '_INDENT', '_NEWLINE'))
  11. EXTENSIONS = (MATCH_GRAMMAR,)
  12. builder = GrammarBuilder()
  13. builder.load_grammar((Path(__file__).with_name('python3.lark')).read_text(), 'python3')
  14. for name, ext_grammar, needed_names in EXTENSIONS:
  15. mangle = builder.get_mangle(name, dict(zip(needed_names, needed_names)))
  16. builder.load_grammar(ext_grammar, name, mangle)
  17. grammar = builder.build()
  18. class PythonIndenter(Indenter):
  19. NL_type = '_NEWLINE'
  20. OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE']
  21. CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE']
  22. INDENT_type = '_INDENT'
  23. DEDENT_type = '_DEDENT'
  24. tab_len = 8
  25. parser = Lark(grammar, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
  26. tree = parser.parse(r"""
  27. a = 5
  28. def name(n):
  29. match n:
  30. case 1:
  31. print("one")
  32. case 2:
  33. print("two")
  34. case _:
  35. print("number is to big")
  36. name(a)
  37. """, start='file_input')
  38. print(tree.pretty())