This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

86 рядки
2.4 KiB

  1. #
  2. # This example demonstrates usage of the included Python grammars
  3. #
  4. import sys
  5. import os, os.path
  6. from io import open
  7. import glob, time
  8. from lark import Lark
  9. from lark.indenter import Indenter
  10. __path__ = os.path.dirname(__file__)
  11. class PythonIndenter(Indenter):
  12. NL_type = '_NEWLINE'
  13. OPEN_PAREN_types = ['__LPAR', '__LSQB', '__LBRACE']
  14. CLOSE_PAREN_types = ['__RPAR', '__RSQB', '__RBRACE']
  15. INDENT_type = '_INDENT'
  16. DEDENT_type = '_DEDENT'
  17. tab_len = 8
  18. grammar2_filename = os.path.join(__path__, 'python2.g')
  19. grammar3_filename = os.path.join(__path__, 'python3.g')
  20. with open(grammar2_filename) as f:
  21. python_parser2 = Lark(f, parser='lalr', postlex=PythonIndenter(), start='file_input')
  22. with open(grammar3_filename) as f:
  23. python_parser3 = Lark(f, parser='lalr', postlex=PythonIndenter(), start='file_input')
  24. with open(grammar2_filename) as f:
  25. python_parser2_earley = Lark(f, parser='lalr', lexer='standard', postlex=PythonIndenter(), start='file_input')
  26. def _read(fn, *args):
  27. kwargs = {'encoding': 'iso-8859-1'}
  28. with open(fn, *args, **kwargs) as f:
  29. return f.read()
  30. def _get_lib_path():
  31. if os.name == 'nt':
  32. if 'PyPy' in sys.version:
  33. return os.path.join(sys.prefix, 'lib-python', sys.winver)
  34. else:
  35. return os.path.join(sys.prefix, 'Lib')
  36. else:
  37. return [x for x in sys.path if x.endswith('%s.%s' % sys.version_info[:2])][0]
  38. def test_python_lib():
  39. path = _get_lib_path()
  40. start = time.time()
  41. files = glob.glob(path+'/*.py')
  42. for f in files:
  43. print( f )
  44. try:
  45. # print list(python_parser.lex(_read(os.path.join(path, f)) + '\n'))
  46. try:
  47. xrange
  48. except NameError:
  49. python_parser3.parse(_read(os.path.join(path, f)) + '\n')
  50. else:
  51. python_parser2.parse(_read(os.path.join(path, f)) + '\n')
  52. except:
  53. print ('At %s' % f)
  54. raise
  55. end = time.time()
  56. print( "test_python_lib (%d files), time: %s secs"%(len(files), end-start) )
  57. def test_earley_equals_lalr():
  58. path = _get_lib_path()
  59. files = glob.glob(path+'/*.py')
  60. for f in files:
  61. print( f )
  62. tree1 = python_parser2.parse(_read(os.path.join(path, f)) + '\n')
  63. tree2 = python_parser2_earley.parse(_read(os.path.join(path, f)) + '\n')
  64. assert tree1 == tree2
  65. if __name__ == '__main__':
  66. test_python_lib()
  67. # test_earley_equals_lalr()