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.

118 lines
2.6 KiB

  1. from __future__ import absolute_import
  2. import sys
  3. import unittest
  4. from unittest import TestCase
  5. from lark.tree import Tree
  6. from lark.tools import standalone
  7. try:
  8. from StringIO import StringIO
  9. except ImportError:
  10. from io import StringIO
  11. class TestStandalone(TestCase):
  12. def setUp(self):
  13. pass
  14. def _create_standalone(self, grammar):
  15. code_buf = StringIO()
  16. temp = sys.stdout
  17. sys.stdout = code_buf
  18. standalone.main(StringIO(grammar), 'start')
  19. sys.stdout = temp
  20. code = code_buf.getvalue()
  21. context = {}
  22. exec(code, context)
  23. return context
  24. def test_simple(self):
  25. grammar = """
  26. start: NUMBER WORD
  27. %import common.NUMBER
  28. %import common.WORD
  29. %import common.WS
  30. %ignore WS
  31. """
  32. context = self._create_standalone(grammar)
  33. _Lark = context['Lark_StandAlone']
  34. l = _Lark()
  35. x = l.parse('12 elephants')
  36. self.assertEqual(x.children, ['12', 'elephants'])
  37. def test_contextual(self):
  38. grammar = """
  39. start: a b
  40. a: "A" "B"
  41. b: "AB"
  42. """
  43. context = self._create_standalone(grammar)
  44. _Lark = context['Lark_StandAlone']
  45. l = _Lark()
  46. x = l.parse('ABAB')
  47. class T(context['Transformer']):
  48. def a(self, items):
  49. return 'a'
  50. def b(self, items):
  51. return 'b'
  52. start = list
  53. x = T().transform(x)
  54. self.assertEqual(x, ['a', 'b'])
  55. l2 = _Lark(transformer=T())
  56. x = l2.parse('ABAB')
  57. self.assertEqual(x, ['a', 'b'])
  58. def test_postlex(self):
  59. from lark.indenter import Indenter
  60. class MyIndenter(Indenter):
  61. NL_type = '_NEWLINE'
  62. OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE']
  63. CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE']
  64. INDENT_type = '_INDENT'
  65. DEDENT_type = '_DEDENT'
  66. tab_len = 8
  67. grammar = r"""
  68. start: "(" ")" _NEWLINE
  69. _NEWLINE: /\n/
  70. """
  71. # from lark import Lark
  72. # l = Lark(grammar, parser='lalr', lexer='contextual', postlex=MyIndenter())
  73. # x = l.parse('(\n)\n')
  74. # print('@@', x)
  75. context = self._create_standalone(grammar)
  76. _Lark = context['Lark_StandAlone']
  77. # l = _Lark(postlex=MyIndenter())
  78. # x = l.parse('()\n')
  79. # print(x)
  80. l = _Lark(postlex=MyIndenter())
  81. x = l.parse('(\n)\n')
  82. print(x)
  83. if __name__ == '__main__':
  84. unittest.main()