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