proxy.py (3109:c3956807347f) proxy.py (3179:c86dfc93984b)
1# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Steve Reinhardt
28# Nathan Binkert
29
30#####################################################################
31#
32# Proxy object support.
33#
34#####################################################################
35
1# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Steve Reinhardt
28# Nathan Binkert
29
30#####################################################################
31#
32# Proxy object support.
33#
34#####################################################################
35
36import copy
37
36class BaseProxy(object):
37 def __init__(self, search_self, search_up):
38 self._search_self = search_self
39 self._search_up = search_up
40 self._multiplier = None
41
42 def __str__(self):
43 if self._search_self and not self._search_up:
44 s = 'Self'
45 elif not self._search_self and self._search_up:
46 s = 'Parent'
47 else:
48 s = 'ConfusedProxy'
49 return s + '.' + self.path()
50
51 def __setattr__(self, attr, value):
52 if not attr.startswith('_'):
53 raise AttributeError, \
54 "cannot set attribute '%s' on proxy object" % attr
55 super(BaseProxy, self).__setattr__(attr, value)
56
57 # support multiplying proxies by constants
58 def __mul__(self, other):
59 if not isinstance(other, (int, long, float)):
60 raise TypeError, "Proxy multiplier must be integer"
61 if self._multiplier == None:
62 self._multiplier = other
63 else:
64 # support chained multipliers
65 self._multiplier *= other
66 return self
67
68 __rmul__ = __mul__
69
70 def _mulcheck(self, result):
71 if self._multiplier == None:
72 return result
73 return result * self._multiplier
74
75 def unproxy(self, base):
76 obj = base
77 done = False
78
79 if self._search_self:
80 result, done = self.find(obj)
81
82 if self._search_up:
83 while not done:
84 obj = obj._parent
85 if not obj:
86 break
87 result, done = self.find(obj)
88
89 if not done:
90 raise AttributeError, \
91 "Can't resolve proxy '%s' of type '%s' from '%s'" % \
92 (self.path(), self._pdesc.ptype_str, base.path())
93
94 if isinstance(result, BaseProxy):
95 if result == self:
96 raise RuntimeError, "Cycle in unproxy"
97 result = result.unproxy(obj)
98
99 return self._mulcheck(result)
100
101 def getindex(obj, index):
102 if index == None:
103 return obj
104 try:
105 obj = obj[index]
106 except TypeError:
107 if index != 0:
108 raise
109 # if index is 0 and item is not subscriptable, just
110 # use item itself (so cpu[0] works on uniprocessors)
111 return obj
112 getindex = staticmethod(getindex)
113
114 # This method should be called once the proxy is assigned to a
115 # particular parameter or port to set the expected type of the
116 # resolved proxy
117 def set_param_desc(self, pdesc):
118 self._pdesc = pdesc
119
120class AttrProxy(BaseProxy):
121 def __init__(self, search_self, search_up, attr):
122 super(AttrProxy, self).__init__(search_self, search_up)
123 self._attr = attr
124 self._modifiers = []
125
126 def __getattr__(self, attr):
127 # python uses __bases__ internally for inheritance
128 if attr.startswith('_'):
129 return super(AttrProxy, self).__getattr__(self, attr)
130 if hasattr(self, '_pdesc'):
131 raise AttributeError, "Attribute reference on bound proxy"
38class BaseProxy(object):
39 def __init__(self, search_self, search_up):
40 self._search_self = search_self
41 self._search_up = search_up
42 self._multiplier = None
43
44 def __str__(self):
45 if self._search_self and not self._search_up:
46 s = 'Self'
47 elif not self._search_self and self._search_up:
48 s = 'Parent'
49 else:
50 s = 'ConfusedProxy'
51 return s + '.' + self.path()
52
53 def __setattr__(self, attr, value):
54 if not attr.startswith('_'):
55 raise AttributeError, \
56 "cannot set attribute '%s' on proxy object" % attr
57 super(BaseProxy, self).__setattr__(attr, value)
58
59 # support multiplying proxies by constants
60 def __mul__(self, other):
61 if not isinstance(other, (int, long, float)):
62 raise TypeError, "Proxy multiplier must be integer"
63 if self._multiplier == None:
64 self._multiplier = other
65 else:
66 # support chained multipliers
67 self._multiplier *= other
68 return self
69
70 __rmul__ = __mul__
71
72 def _mulcheck(self, result):
73 if self._multiplier == None:
74 return result
75 return result * self._multiplier
76
77 def unproxy(self, base):
78 obj = base
79 done = False
80
81 if self._search_self:
82 result, done = self.find(obj)
83
84 if self._search_up:
85 while not done:
86 obj = obj._parent
87 if not obj:
88 break
89 result, done = self.find(obj)
90
91 if not done:
92 raise AttributeError, \
93 "Can't resolve proxy '%s' of type '%s' from '%s'" % \
94 (self.path(), self._pdesc.ptype_str, base.path())
95
96 if isinstance(result, BaseProxy):
97 if result == self:
98 raise RuntimeError, "Cycle in unproxy"
99 result = result.unproxy(obj)
100
101 return self._mulcheck(result)
102
103 def getindex(obj, index):
104 if index == None:
105 return obj
106 try:
107 obj = obj[index]
108 except TypeError:
109 if index != 0:
110 raise
111 # if index is 0 and item is not subscriptable, just
112 # use item itself (so cpu[0] works on uniprocessors)
113 return obj
114 getindex = staticmethod(getindex)
115
116 # This method should be called once the proxy is assigned to a
117 # particular parameter or port to set the expected type of the
118 # resolved proxy
119 def set_param_desc(self, pdesc):
120 self._pdesc = pdesc
121
122class AttrProxy(BaseProxy):
123 def __init__(self, search_self, search_up, attr):
124 super(AttrProxy, self).__init__(search_self, search_up)
125 self._attr = attr
126 self._modifiers = []
127
128 def __getattr__(self, attr):
129 # python uses __bases__ internally for inheritance
130 if attr.startswith('_'):
131 return super(AttrProxy, self).__getattr__(self, attr)
132 if hasattr(self, '_pdesc'):
133 raise AttributeError, "Attribute reference on bound proxy"
132 self._modifiers.append(attr)
133 return self
134 # Return a copy of self rather than modifying self in place
135 # since self could be an indirect reference via a variable or
136 # parameter
137 new_self = copy.deepcopy(self)
138 new_self._modifiers.append(attr)
139 return new_self
134
135 # support indexing on proxies (e.g., Self.cpu[0])
136 def __getitem__(self, key):
137 if not isinstance(key, int):
138 raise TypeError, "Proxy object requires integer index"
140
141 # support indexing on proxies (e.g., Self.cpu[0])
142 def __getitem__(self, key):
143 if not isinstance(key, int):
144 raise TypeError, "Proxy object requires integer index"
139 self._modifiers.append(key)
140 return self
145 if hasattr(self, '_pdesc'):
146 raise AttributeError, "Index operation on bound proxy"
147 new_self = copy.deepcopy(self)
148 new_self._modifiers.append(key)
149 return new_self
141
142 def find(self, obj):
143 try:
144 val = getattr(obj, self._attr)
145 except:
146 return None, False
147 while isproxy(val):
148 val = val.unproxy(obj)
149 for m in self._modifiers:
150 if isinstance(m, str):
151 val = getattr(val, m)
152 elif isinstance(m, int):
153 val = val[m]
154 else:
155 assert("Item must be string or integer")
156 while isproxy(val):
157 val = val.unproxy(obj)
158 return val, True
159
160 def path(self):
161 p = self._attr
162 for m in self._modifiers:
163 if isinstance(m, str):
164 p += '.%s' % m
165 elif isinstance(m, int):
166 p += '[%d]' % m
167 else:
168 assert("Item must be string or integer")
169 return p
170
171class AnyProxy(BaseProxy):
172 def find(self, obj):
173 return obj.find_any(self._pdesc.ptype)
174
175 def path(self):
176 return 'any'
177
178def isproxy(obj):
179 if isinstance(obj, (BaseProxy, params.EthernetAddr)):
180 return True
181 elif isinstance(obj, (list, tuple)):
182 for v in obj:
183 if isproxy(v):
184 return True
185 return False
186
187class ProxyFactory(object):
188 def __init__(self, search_self, search_up):
189 self.search_self = search_self
190 self.search_up = search_up
191
192 def __getattr__(self, attr):
193 if attr == 'any':
194 return AnyProxy(self.search_self, self.search_up)
195 else:
196 return AttrProxy(self.search_self, self.search_up, attr)
197
198# global objects for handling proxies
199Parent = ProxyFactory(search_self = False, search_up = True)
200Self = ProxyFactory(search_self = True, search_up = False)
201
202# limit exports on 'from proxy import *'
203__all__ = ['Parent', 'Self']
204
205# see comment on imports at end of __init__.py.
206import params # for EthernetAddr
150
151 def find(self, obj):
152 try:
153 val = getattr(obj, self._attr)
154 except:
155 return None, False
156 while isproxy(val):
157 val = val.unproxy(obj)
158 for m in self._modifiers:
159 if isinstance(m, str):
160 val = getattr(val, m)
161 elif isinstance(m, int):
162 val = val[m]
163 else:
164 assert("Item must be string or integer")
165 while isproxy(val):
166 val = val.unproxy(obj)
167 return val, True
168
169 def path(self):
170 p = self._attr
171 for m in self._modifiers:
172 if isinstance(m, str):
173 p += '.%s' % m
174 elif isinstance(m, int):
175 p += '[%d]' % m
176 else:
177 assert("Item must be string or integer")
178 return p
179
180class AnyProxy(BaseProxy):
181 def find(self, obj):
182 return obj.find_any(self._pdesc.ptype)
183
184 def path(self):
185 return 'any'
186
187def isproxy(obj):
188 if isinstance(obj, (BaseProxy, params.EthernetAddr)):
189 return True
190 elif isinstance(obj, (list, tuple)):
191 for v in obj:
192 if isproxy(v):
193 return True
194 return False
195
196class ProxyFactory(object):
197 def __init__(self, search_self, search_up):
198 self.search_self = search_self
199 self.search_up = search_up
200
201 def __getattr__(self, attr):
202 if attr == 'any':
203 return AnyProxy(self.search_self, self.search_up)
204 else:
205 return AttrProxy(self.search_self, self.search_up, attr)
206
207# global objects for handling proxies
208Parent = ProxyFactory(search_self = False, search_up = True)
209Self = ProxyFactory(search_self = True, search_up = False)
210
211# limit exports on 'from proxy import *'
212__all__ = ['Parent', 'Self']
213
214# see comment on imports at end of __init__.py.
215import params # for EthernetAddr