This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

119 Zeilen
2.3 KiB

  1. """
  2. Creating an AST from the parse tree
  3. ===================================
  4. This example demonstrates how to transform a parse-tree into an AST using `lark.ast_utils`.
  5. create_transformer() collects every subclass of `Ast` subclass from the module,
  6. and creates a Lark transformer that builds the AST with no extra code.
  7. This example only works with Python 3.
  8. """
  9. import sys
  10. from typing import List
  11. from dataclasses import dataclass
  12. from lark import Lark, ast_utils, Transformer, v_args
  13. this_module = sys.modules[__name__]
  14. #
  15. # Define AST
  16. #
  17. class _Ast(ast_utils.Ast):
  18. # This will be skipped by create_transformer(), because it starts with an underscore
  19. pass
  20. class _Statement(_Ast):
  21. # This will be skipped by create_transformer(), because it starts with an underscore
  22. pass
  23. @dataclass
  24. class Value(_Ast):
  25. value: object
  26. @dataclass
  27. class Name(_Ast):
  28. name: str
  29. @dataclass
  30. class CodeBlock(_Ast, ast_utils.AsList):
  31. # Corresponds to code_block in the grammar
  32. statements: List[_Statement]
  33. @dataclass
  34. class If(_Statement):
  35. cond: Value
  36. then: CodeBlock
  37. @dataclass
  38. class SetVar(_Statement):
  39. # Corresponds to set_var in the grammar
  40. name: str
  41. value: Value
  42. @dataclass
  43. class Print(_Statement):
  44. value: Value
  45. class ToAst(Transformer):
  46. # Define extra transformation functions, for rules that don't correspond to an AST class.
  47. def STRING(self, s):
  48. # Remove quotation marks
  49. return s[1:-1]
  50. def DEC_NUMBER(self, n):
  51. return int(n)
  52. @v_args(inline=True)
  53. def start(self, x):
  54. return x
  55. #
  56. # Define Parser
  57. #
  58. parser = Lark("""
  59. start: code_block
  60. code_block: statement+
  61. ?statement: if | set_var | print
  62. if: "if" value "{" code_block "}"
  63. set_var: NAME "=" value ";"
  64. print: "print" value ";"
  65. value: name | STRING | DEC_NUMBER
  66. name: NAME
  67. %import python (NAME, STRING, DEC_NUMBER)
  68. %import common.WS
  69. %ignore WS
  70. """,
  71. parser="lalr",
  72. )
  73. transformer = ast_utils.create_transformer(this_module, ToAst())
  74. def parse(text):
  75. tree = parser.parse(text)
  76. return transformer.transform(tree)
  77. #
  78. # Test
  79. #
  80. if __name__ == '__main__':
  81. print(parse("""
  82. a = 1;
  83. if a {
  84. print "a is 1";
  85. a = 2;
  86. }
  87. """))