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.

83 lines
2.2 KiB

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