PageRenderTime 47ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/rlib/rsre/rpy.py

https://bitbucket.org/pypy/pypy/
Python | 49 lines | 41 code | 4 blank | 4 comment | 11 complexity | 5ba9972366bf8b03d75c0c93b9b2d30c MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from pypy.rlib.rsre import rsre_char
  2. from pypy.rlib.rsre.rsre_core import match
  3. def get_hacked_sre_compile(my_compile):
  4. """Return a copy of the sre_compile module for which the _sre
  5. module is a custom module that has _sre.compile == my_compile
  6. and CODESIZE == rsre_char.CODESIZE.
  7. """
  8. import sre_compile, __builtin__, new
  9. sre_hacked = new.module("_sre_hacked")
  10. sre_hacked.compile = my_compile
  11. sre_hacked.MAGIC = sre_compile.MAGIC
  12. sre_hacked.CODESIZE = rsre_char.CODESIZE
  13. sre_hacked.getlower = rsre_char.getlower
  14. def my_import(name, *args):
  15. if name == '_sre':
  16. return sre_hacked
  17. else:
  18. return default_import(name, *args)
  19. src = sre_compile.__file__
  20. if src.lower().endswith('.pyc') or src.lower().endswith('.pyo'):
  21. src = src[:-1]
  22. mod = new.module("sre_compile_hacked")
  23. default_import = __import__
  24. try:
  25. __builtin__.__import__ = my_import
  26. execfile(src, mod.__dict__)
  27. finally:
  28. __builtin__.__import__ = default_import
  29. return mod
  30. class GotIt(Exception):
  31. pass
  32. def my_compile(pattern, flags, code, *args):
  33. raise GotIt(code, flags, args)
  34. sre_compile_hacked = get_hacked_sre_compile(my_compile)
  35. def get_code(regexp, flags=0, allargs=False):
  36. try:
  37. sre_compile_hacked.compile(regexp, flags)
  38. except GotIt, e:
  39. pass
  40. else:
  41. raise ValueError("did not reach _sre.compile()!")
  42. if allargs:
  43. return e.args
  44. else:
  45. return e.args[0]