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.

102 lines
2.4 KiB

  1. Transformers & Visitors
  2. =======================
  3. Transformers & Visitors provide a convenient interface to process the
  4. parse-trees that Lark returns.
  5. They are used by inheriting from the correct class (visitor or transformer),
  6. and implementing methods corresponding to the rule you wish to process. Each
  7. method accepts the children as an argument. That can be modified using the
  8. ``v_args`` decorator, which allows to inline the arguments (akin to ``*args``),
  9. or add the tree ``meta`` property as an argument.
  10. See: `visitors.py`_
  11. .. _visitors.py: https://github.com/lark-parser/lark/blob/master/lark/visitors.py
  12. Visitor
  13. -------
  14. Visitors visit each node of the tree, and run the appropriate method on it according to the node's data.
  15. They work bottom-up, starting with the leaves and ending at the root of the tree.
  16. There are two classes that implement the visitor interface:
  17. - ``Visitor``: Visit every node (without recursion)
  18. - ``Visitor_Recursive``: Visit every node using recursion. Slightly faster.
  19. Example:
  20. ::
  21. class IncreaseAllNumbers(Visitor):
  22. def number(self, tree):
  23. assert tree.data == "number"
  24. tree.children[0] += 1
  25. IncreaseAllNumbers().visit(parse_tree)
  26. .. autoclass:: lark.visitors.Visitor
  27. .. autoclass:: lark.visitors.Visitor_Recursive
  28. Interpreter
  29. -----------
  30. .. autoclass:: lark.visitors.Interpreter
  31. Example:
  32. ::
  33. class IncreaseSomeOfTheNumbers(Interpreter):
  34. def number(self, tree):
  35. tree.children[0] += 1
  36. def skip(self, tree):
  37. # skip this subtree. don't change any number node inside it.
  38. pass
  39. IncreaseSomeOfTheNumbers().visit(parse_tree)
  40. Transformer
  41. -----------
  42. .. autoclass:: lark.visitors.Transformer
  43. :members: __default__, __default_token__
  44. Example:
  45. ::
  46. from lark import Tree, Transformer
  47. class EvalExpressions(Transformer):
  48. def expr(self, args):
  49. return eval(args[0])
  50. t = Tree('a', [Tree('expr', ['1+2'])])
  51. print(EvalExpressions().transform( t ))
  52. # Prints: Tree(a, [3])
  53. Example:
  54. ::
  55. class T(Transformer):
  56. INT = int
  57. NUMBER = float
  58. def NAME(self, name):
  59. return lookup_dict.get(name, name)
  60. T(visit_tokens=True).transform(tree)
  61. v_args
  62. ------
  63. .. autofunction:: lark.visitors.v_args
  64. Discard
  65. -------
  66. .. autoclass:: lark.visitors.Discard