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.

80 lines
2.2 KiB

  1. """
  2. Example-Driven Error Reporting
  3. ==============================
  4. A demonstration of example-driven error reporting with the LALR parser
  5. """
  6. from lark import Lark, UnexpectedInput
  7. from _json_parser import json_grammar # Using the grammar from the json_parser example
  8. json_parser = Lark(json_grammar, parser='lalr')
  9. class JsonSyntaxError(SyntaxError):
  10. def __str__(self):
  11. context, line, column = self.args
  12. return '%s at line %s, column %s.\n\n%s' % (self.label, line, column, context)
  13. class JsonMissingValue(JsonSyntaxError):
  14. label = 'Missing Value'
  15. class JsonMissingOpening(JsonSyntaxError):
  16. label = 'Missing Opening'
  17. class JsonMissingClosing(JsonSyntaxError):
  18. label = 'Missing Closing'
  19. class JsonMissingComma(JsonSyntaxError):
  20. label = 'Missing Comma'
  21. class JsonTrailingComma(JsonSyntaxError):
  22. label = 'Trailing Comma'
  23. def parse(json_text):
  24. try:
  25. j = json_parser.parse(json_text)
  26. except UnexpectedInput as u:
  27. exc_class = u.match_examples(json_parser.parse, {
  28. JsonMissingOpening: ['{"foo": ]}',
  29. '{"foor": }}',
  30. '{"foo": }'],
  31. JsonMissingClosing: ['{"foo": [}',
  32. '{',
  33. '{"a": 1',
  34. '[1'],
  35. JsonMissingComma: ['[1 2]',
  36. '[false 1]',
  37. '["b" 1]',
  38. '{"a":true 1:4}',
  39. '{"a":1 1:4}',
  40. '{"a":"b" 1:4}'],
  41. JsonTrailingComma: ['[,]',
  42. '[1,]',
  43. '[1,2,]',
  44. '{"foo":1,}',
  45. '{"foo":false,"bar":true,}']
  46. }, use_accepts=True)
  47. if not exc_class:
  48. raise
  49. raise exc_class(u.get_context(json_text), u.line, u.column)
  50. def test():
  51. try:
  52. parse('{"example1": "value"')
  53. except JsonMissingClosing as e:
  54. print(e)
  55. try:
  56. parse('{"example2": ] ')
  57. except JsonMissingOpening as e:
  58. print(e)
  59. if __name__ == '__main__':
  60. test()