misc.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. def flatten(tup):
  2. elts = []
  3. for elt in tup:
  4. if isinstance(elt, tuple):
  5. elts = elts + flatten(elt)
  6. else:
  7. elts.append(elt)
  8. return elts
  9. class Set:
  10. def __init__(self):
  11. self.elts = {}
  12. def __len__(self):
  13. return len(self.elts)
  14. def __contains__(self, elt):
  15. return elt in self.elts
  16. def add(self, elt):
  17. self.elts[elt] = elt
  18. def elements(self):
  19. return self.elts.keys()
  20. def has_elt(self, elt):
  21. return elt in self.elts
  22. def remove(self, elt):
  23. del self.elts[elt]
  24. def copy(self):
  25. c = Set()
  26. c.elts.update(self.elts)
  27. return c
  28. class Stack:
  29. def __init__(self):
  30. self.stack = []
  31. self.pop = self.stack.pop
  32. def __len__(self):
  33. return len(self.stack)
  34. def push(self, elt):
  35. self.stack.append(elt)
  36. def top(self):
  37. return self.stack[-1]
  38. def __getitem__(self, index): # needed by visitContinue()
  39. return self.stack[index]
  40. MANGLE_LEN = 256 # magic constant from compile.c
  41. def mangle(name, klass):
  42. if not name.startswith('__'):
  43. return name
  44. if len(name) + 2 >= MANGLE_LEN:
  45. return name
  46. if name.endswith('__'):
  47. return name
  48. try:
  49. i = 0
  50. while klass[i] == '_':
  51. i = i + 1
  52. except IndexError:
  53. return name
  54. klass = klass[i:]
  55. tlen = len(klass) + len(name)
  56. if tlen > MANGLE_LEN:
  57. klass = klass[:MANGLE_LEN-tlen]
  58. return "_%s%s" % (klass, name)
  59. def set_filename(filename, tree):
  60. """Set the filename attribute to filename on every node in tree"""
  61. worklist = [tree]
  62. while worklist:
  63. node = worklist.pop(0)
  64. node.filename = filename
  65. worklist.extend(node.getChildNodes())