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.

120 lines
2.7 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. x = l.parse('16 candles')
  38. self.assertEqual(x.children, ['16', 'candles'])
  39. def test_contextual(self):
  40. grammar = """
  41. start: a b
  42. a: "A" "B"
  43. b: "AB"
  44. """
  45. context = self._create_standalone(grammar)
  46. _Lark = context['Lark_StandAlone']
  47. l = _Lark()
  48. x = l.parse('ABAB')
  49. class T(context['Transformer']):
  50. def a(self, items):
  51. return 'a'
  52. def b(self, items):
  53. return 'b'
  54. start = list
  55. x = T().transform(x)
  56. self.assertEqual(x, ['a', 'b'])
  57. l2 = _Lark(transformer=T())
  58. x = l2.parse('ABAB')
  59. self.assertEqual(x, ['a', 'b'])
  60. def test_postlex(self):
  61. from lark.indenter import Indenter
  62. class MyIndenter(Indenter):
  63. NL_type = '_NEWLINE'
  64. OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE']
  65. CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE']
  66. INDENT_type = '_INDENT'
  67. DEDENT_type = '_DEDENT'
  68. tab_len = 8
  69. grammar = r"""
  70. start: "(" ")" _NEWLINE
  71. _NEWLINE: /\n/
  72. """
  73. # from lark import Lark
  74. # l = Lark(grammar, parser='lalr', lexer='contextual', postlex=MyIndenter())
  75. # x = l.parse('(\n)\n')
  76. # print('@@', x)
  77. context = self._create_standalone(grammar)
  78. _Lark = context['Lark_StandAlone']
  79. # l = _Lark(postlex=MyIndenter())
  80. # x = l.parse('()\n')
  81. # print(x)
  82. l = _Lark(postlex=MyIndenter())
  83. x = l.parse('(\n)\n')
  84. print(x)
  85. if __name__ == '__main__':
  86. unittest.main()