PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 7ms RepoModel.GetById 34ms app.codeStats 0ms

/Lib/compiler/misc.py

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