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.

115 lines
2.6 KiB

  1. import json
  2. import unittest
  3. from unittest import TestCase
  4. from lark import Lark
  5. from lark.reconstruct import Reconstructor
  6. common = """
  7. %import common (WS_INLINE, NUMBER, WORD)
  8. %ignore WS_INLINE
  9. """
  10. class TestReconstructor(TestCase):
  11. def reconstruct(self, grammar, code):
  12. parser = Lark(grammar, parser='lalr')
  13. tree = parser.parse(code)
  14. new = Reconstructor(parser).reconstruct(tree)
  15. self.assertEqual(code.replace(' ', ''), new.replace(' ', ''))
  16. def test_starred_rule(self):
  17. g = """
  18. start: item*
  19. item: NL
  20. | rule
  21. rule: WORD ":" NUMBER
  22. NL: /(\\r?\\n)+\s*/
  23. """ + common
  24. code = """
  25. Elephants: 12
  26. """
  27. self.reconstruct(g, code)
  28. def test_starred_group(self):
  29. g = """
  30. start: (rule | _NL)*
  31. rule: WORD ":" NUMBER
  32. _NL: /(\\r?\\n)+\s*/
  33. """ + common
  34. code = """
  35. Elephants: 12
  36. """
  37. self.reconstruct(g, code)
  38. def test_alias(self):
  39. g = """
  40. start: line*
  41. line: NL
  42. | rule
  43. | "hello" -> hi
  44. rule: WORD ":" NUMBER
  45. NL: /(\\r?\\n)+\s*/
  46. """ + common
  47. code = """
  48. Elephants: 12
  49. hello
  50. """
  51. self.reconstruct(g, code)
  52. def test_json_example(self):
  53. test_json = '''
  54. {
  55. "empty_object" : {},
  56. "empty_array" : [],
  57. "booleans" : { "YES" : true, "NO" : false },
  58. "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ],
  59. "strings" : [ "This", [ "And" , "That", "And a \\"b" ] ],
  60. "nothing" : null
  61. }
  62. '''
  63. json_grammar = r"""
  64. ?start: value
  65. ?value: object
  66. | array
  67. | string
  68. | SIGNED_NUMBER -> number
  69. | "true" -> true
  70. | "false" -> false
  71. | "null" -> null
  72. array : "[" [value ("," value)*] "]"
  73. object : "{" [pair ("," pair)*] "}"
  74. pair : string ":" value
  75. string : ESCAPED_STRING
  76. %import common.ESCAPED_STRING
  77. %import common.SIGNED_NUMBER
  78. %import common.WS
  79. %ignore WS
  80. """
  81. json_parser = Lark(json_grammar, parser='lalr')
  82. tree = json_parser.parse(test_json)
  83. new_json = Reconstructor(json_parser).reconstruct(tree)
  84. self.assertEqual(json.loads(new_json), json.loads(test_json))
  85. if __name__ == '__main__':
  86. unittest.main()