PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rlib/rsre/rpy.py

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