/Modules/make_cpickle_opcodes.py

http://unladen-swallow.googlecode.com/ · Python · 41 lines · 31 code · 6 blank · 4 comment · 7 complexity · 876f017c163edf4c2f89a98b697058dd MD5 · raw file

  1. #! /usr/bin/env python
  2. """Generate C code for the jump table of the cPickle unpickling interpreter
  3. (for compilers supporting computed gotos or "labels-as-values", such as gcc).
  4. This needs to be run when you change the pickle protocol, which you shouldn't
  5. be doing.
  6. """
  7. import imp
  8. import os
  9. import sys
  10. def find_module(modname):
  11. """Finds and returns a module in the local dist/checkout."""
  12. modpath = os.path.join(
  13. os.path.dirname(os.path.dirname(__file__)), "Lib")
  14. return imp.load_module(modname, *imp.find_module(modname, [modpath]))
  15. def write_contents(f):
  16. """Write C code contents to the target file object."""
  17. pickletools = find_module("pickletools")
  18. targets = ['TARGET_NULLBYTE'] + (['_unknown_opcode'] * 255)
  19. for opcode in pickletools.opcodes:
  20. targets[ord(opcode.code)] = "TARGET_%s" % opcode.name
  21. f.write("static void *opcode_targets[256] = {\n")
  22. f.write(",\n".join("\t&&%s" % s for s in targets))
  23. f.write("\n};\n")
  24. if __name__ == "__main__":
  25. assert len(sys.argv) < 3, "Too many arguments"
  26. if len(sys.argv) == 2:
  27. target = sys.argv[1]
  28. else:
  29. target = "Modules/cPickle_opcodes.h"
  30. f = open(target, "w")
  31. try:
  32. write_contents(f)
  33. finally:
  34. f.close()