This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 

82 líneas
2.2 KiB

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