retep / tuke

A EDA toolkit for programmically creating hardware with Python.

This URL has Read+Write access

tuke / Tuke / id.py
100644 205 lines (159 sloc) 5.537 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# vim: tabstop=4 expandtab shiftwidth=4 fileencoding=utf8
# ### BOILERPLATE ###
# Tuke - Electrical Design Automation toolset
# Copyright (C) 2008 Peter Todd <pete@petertodd.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ### BOILERPLATE ###
 
import Tuke.context as context
import Tuke.repr_helper
 
import re
 
valid_id_re = re.compile('^([_A-Za-z][_A-Za-z0-9]*|\.|\.\.)$')
 
def normalize(self):
    r = []
 
    for i in self:
        if i == '..':
            if r and r[-1] != '..':
                r.pop()
            else:
                r.append(i)
        elif i in ('.',''):
            continue
        else:
            r.append(i)
 
    return r
 
class Id(tuple,context.wrapper.Translatable):
    """Element identifiers.
Id's are identifiers with a path. The path is relative, so for instance
../Vcc means Vcc in our parent's context, similarly foo/Vcc means Vcc in
foo, a sub-element.
"""
 
    def __new__(cls,s = ''):
        """Create a new Id from s
 
s may be a string or another Id
"""
 
        if isinstance(s,Id):
            # Skip normalization if possible.
            if cls is Id and s.__class__ is Id:
                # An Id exactly, just return s
                return s
            else:
                # Some sort of Id subclass, either cls is, or s is, recreate an
                # Id.
                return tuple.__new__(cls,tuple.__iter__(s))
 
        try:
            id = s.split('/')
        except AttributeError:
            raise TypeError, "%s is not an Id or a string: %s" % (type(s),s)
 
        id = normalize(id)
 
        # Has to be last, as '/'.split('/') == ('','')
        for p in id:
            if not valid_id_re.match(p):
                raise ValueError, "'%s' is not a valid Id" % s
 
        return tuple.__new__(cls,id)
 
    @classmethod
    def random(cls,bits = 64):
        """Create a random Id
bits - bits of randomness
"""
 
        import random
        
        s = '_' + hex(random.randint(0,2 ** bits))[2:-1].zfill(bits / 4).lower()
 
        return tuple.__new__(cls,(s,))
 
 
    def relto(self,base):
        """Returns self relative to base.
 
By that we mean assuming self and base are starting from the same point
in the tree, from the perspective of base, where is self?
 
Id('a').relto('a') == '.'
Id('a').relto('b') == '../b'
Id('a/b/c').relto('a') == 'b/c'
Id('../b/c').relto('a') == '../../b/c'
"""
        # Discard common prefixes
        i = 0
        while i < len(self) and i < len(base) and self[i] == base[i]:
            i += 1
 
        # Whatever is left in base must be turned into ../'s
        r = Id('../' * (len(base) - i))
 
        # And add on the uncommon part of what we're looking for
        return r + self[i:]
        
 
    def __add__(self,b):
        if not b:
            return self
        n = normalize(tuple.__add__(self,b))
 
        return tuple.__new__(Id,n)
 
    def __str__(self):
        if self:
            return '/'.join(tuple.__iter__(self))
        else:
            return '.'
 
    def __eq__(self,b):
        return tuple.__eq__(self,b)
 
    def __ne__(self,b):
        return not self.__eq__(b)
 
    def __gt__(self,other):
        if len(self) == len(other):
            return tuple.__gt__(self,other)
        elif len(self) > len(other):
            return True
        else:
            return False
 
    def __lt__(self,other):
        if len(self) == len(other):
            return tuple.__lt__(self,other)
        elif len(self) < len(other):
            return True
        else:
            return False
 
    def __ge__(self,other):
        if len(self) == len(other):
            return tuple.__gt__(self,other)
        elif len(self) > len(other):
            return True
        else:
            return False
 
    def __le__(self,other):
        if len(self) == len(other):
            return tuple.__lt__(self,other)
        elif len(self) < len(other):
            return True
        else:
            return False
 
    def __getslice__(self,l,u):
        return tuple.__new__(Id,
                             tuple.__getslice__(self,l,u))
 
    def __getitem__(self,i):
        r = tuple.__getitem__(self,i)
        if isinstance(r,str):
            r = (r,)
        return tuple.__new__(Id,r)
 
    def __iter__(self):
        for i in tuple.__iter__(self):
            yield tuple.__new__(Id,(i,))
 
    def _build_context(self,base,reverse):
        assert len(self) == 1
        if reverse:
            return base + Id('..')
        else:
            return base + self
 
    def _apply_context(self,elem):
        return elem.id + self
 
    def _remove_context(self,elem):
        return self.relto(elem.id)
 
    @Tuke.repr_helper.repr_helper
    def __repr__(self):
        s = str(self)
 
        return ((s,),None)
 
def rndId():
    """Alias for Id.random()"""
    return Id.random()