py33compat.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import dis
  2. import array
  3. import collections
  4. try:
  5. import html
  6. except ImportError:
  7. html = None
  8. from setuptools.extern import six
  9. from setuptools.extern.six.moves import html_parser
  10. OpArg = collections.namedtuple('OpArg', 'opcode arg')
  11. class Bytecode_compat(object):
  12. def __init__(self, code):
  13. self.code = code
  14. def __iter__(self):
  15. """Yield '(op,arg)' pair for each operation in code object 'code'"""
  16. bytes = array.array('b', self.code.co_code)
  17. eof = len(self.code.co_code)
  18. ptr = 0
  19. extended_arg = 0
  20. while ptr < eof:
  21. op = bytes[ptr]
  22. if op >= dis.HAVE_ARGUMENT:
  23. arg = bytes[ptr + 1] + bytes[ptr + 2] * 256 + extended_arg
  24. ptr += 3
  25. if op == dis.EXTENDED_ARG:
  26. long_type = six.integer_types[-1]
  27. extended_arg = arg * long_type(65536)
  28. continue
  29. else:
  30. arg = None
  31. ptr += 1
  32. yield OpArg(op, arg)
  33. Bytecode = getattr(dis, 'Bytecode', Bytecode_compat)
  34. unescape = getattr(html, 'unescape', html_parser.HTMLParser().unescape)