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.

38 lines
1010 B

  1. """
  2. Error handling with a puppet
  3. ==================================
  4. This example demonstrates error handling using a parsing puppet in LALR
  5. When the parser encounters an UnexpectedToken exception, it creates a
  6. parsing puppet with the current parse-state, and lets you control how
  7. to proceed step-by-step. When you've achieved the correct parse-state,
  8. you can resume the run by returning True.
  9. """
  10. from lark import Token
  11. from _json_parser import json_parser
  12. def ignore_errors(e):
  13. if e.token.type == 'COMMA':
  14. # Skip comma
  15. return True
  16. elif e.token.type == 'SIGNED_NUMBER':
  17. # Try to feed a comma and retry the number
  18. e.puppet.feed_token(Token('COMMA', ','))
  19. e.puppet.feed_token(e.token)
  20. return True
  21. # Unhandled error. Will stop parse and raise exception
  22. return False
  23. def main():
  24. s = "[0 1, 2,, 3,,, 4, 5 6 ]"
  25. res = json_parser.parse(s, on_error=ignore_errors)
  26. print(res) # prints [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
  27. main()