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.

51 lines
1.8 KiB

  1. """
  2. Grammar Composition
  3. ===================
  4. This example shows how to do grammar composition in Lark, by creating a new
  5. file format that allows both CSV and JSON to co-exist.
  6. 1) We define ``storage.lark``, which imports both ``csv.lark`` and ``json.lark``,
  7. and allows them to be used one after the other.
  8. In the generated tree, each imported rule/terminal is automatically prefixed (with ``json__`` or ``csv__),
  9. which creates an implicit namespace and allows them to coexist without collisions.
  10. 2) We merge their respective transformers (unaware of each other) into a new base transformer.
  11. The resulting transformer can evaluate both JSON and CSV in the parse tree.
  12. The methods of each transformer are renamed into their appropriate namespace, using the given prefix.
  13. This approach allows full re-use: the transformers don't need to care if their grammar is used directly,
  14. or being imported, or who is doing the importing.
  15. """
  16. from pathlib import Path
  17. from lark import Lark
  18. from json import dumps
  19. from lark.visitors import Transformer, merge_transformers
  20. from eval_csv import CsvTreeToPandasDict
  21. from eval_json import JsonTreeToJson
  22. __dir__ = Path(__file__).parent
  23. class Storage(Transformer):
  24. def start(self, children):
  25. return children
  26. storage_transformer = merge_transformers(Storage(), csv=CsvTreeToPandasDict(), json=JsonTreeToJson())
  27. parser = Lark.open("storage.lark", rel_to=__file__)
  28. def main():
  29. json_tree = parser.parse(dumps({"test": "a", "dict": { "list": [1, 1.2] }}))
  30. res = storage_transformer.transform(json_tree)
  31. print("Just JSON: ", res)
  32. csv_json_tree = parser.parse(open(__dir__ / 'combined_csv_and_json.txt').read())
  33. res = storage_transformer.transform(csv_json_tree)
  34. print("JSON + CSV: ", dumps(res, indent=2))
  35. if __name__ == "__main__":
  36. main()