proxy.py (3101:6cce868ddaa6) proxy.py (3105:993f1abefd67)
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
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 __setattr__(self, attr, value):
43 if not attr.startswith('_'):
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
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 __setattr__(self, attr, value):
43 if not attr.startswith('_'):
44 raise AttributeError, 'cannot set attribute on proxy object'
44 raise AttributeError, \
45 "cannot set attribute '%s' on proxy object" % attr
45 super(BaseProxy, self).__setattr__(attr, value)
46
47 # support multiplying proxies by constants
48 def __mul__(self, other):
49 if not isinstance(other, (int, long, float)):
50 raise TypeError, "Proxy multiplier must be integer"
51 if self._multiplier == None:
52 self._multiplier = other
53 else:
54 # support chained multipliers
55 self._multiplier *= other
56 return self
57
58 __rmul__ = __mul__
59
60 def _mulcheck(self, result):
61 if self._multiplier == None:
62 return result
63 return result * self._multiplier
64
65 def unproxy(self, base):
66 obj = base
67 done = False
68
69 if self._search_self:
70 result, done = self.find(obj)
71
72 if self._search_up:
73 while not done:
74 obj = obj._parent
75 if not obj:
76 break
77 result, done = self.find(obj)
78
79 if not done:
80 raise AttributeError, \
81 "Can't resolve proxy '%s' of type '%s' from '%s'" % \
82 (self.path(), self._pdesc.ptype_str, base.path())
83
84 if isinstance(result, BaseProxy):
85 if result == self:
86 raise RuntimeError, "Cycle in unproxy"
87 result = result.unproxy(obj)
88
89 return self._mulcheck(result)
90
91 def getindex(obj, index):
92 if index == None:
93 return obj
94 try:
95 obj = obj[index]
96 except TypeError:
97 if index != 0:
98 raise
99 # if index is 0 and item is not subscriptable, just
100 # use item itself (so cpu[0] works on uniprocessors)
101 return obj
102 getindex = staticmethod(getindex)
103
104 def set_param_desc(self, pdesc):
105 self._pdesc = pdesc
106
107class AttrProxy(BaseProxy):
108 def __init__(self, search_self, search_up, attr):
109 super(AttrProxy, self).__init__(search_self, search_up)
110 self._attr = attr
111 self._modifiers = []
112
113 def __getattr__(self, attr):
114 # python uses __bases__ internally for inheritance
115 if attr.startswith('_'):
116 return super(AttrProxy, self).__getattr__(self, attr)
117 if hasattr(self, '_pdesc'):
118 raise AttributeError, "Attribute reference on bound proxy"
119 self._modifiers.append(attr)
120 return self
121
122 # support indexing on proxies (e.g., Self.cpu[0])
123 def __getitem__(self, key):
124 if not isinstance(key, int):
125 raise TypeError, "Proxy object requires integer index"
126 self._modifiers.append(key)
127 return self
128
129 def find(self, obj):
130 try:
131 val = getattr(obj, self._attr)
132 except:
133 return None, False
134 while isproxy(val):
135 val = val.unproxy(obj)
136 for m in self._modifiers:
137 if isinstance(m, str):
138 val = getattr(val, m)
139 elif isinstance(m, int):
140 val = val[m]
141 else:
142 assert("Item must be string or integer")
143 while isproxy(val):
144 val = val.unproxy(obj)
145 return val, True
146
147 def path(self):
148 p = self._attr
149 for m in self._modifiers:
150 if isinstance(m, str):
151 p += '.%s' % m
152 elif isinstance(m, int):
153 p += '[%d]' % m
154 else:
155 assert("Item must be string or integer")
156 return p
157
158class AnyProxy(BaseProxy):
159 def find(self, obj):
160 return obj.find_any(self._pdesc.ptype)
161
162 def path(self):
163 return 'any'
164
165def isproxy(obj):
166 if isinstance(obj, (BaseProxy, params.EthernetAddr)):
167 return True
168 elif isinstance(obj, (list, tuple)):
169 for v in obj:
170 if isproxy(v):
171 return True
172 return False
173
174class ProxyFactory(object):
175 def __init__(self, search_self, search_up):
176 self.search_self = search_self
177 self.search_up = search_up
178
179 def __getattr__(self, attr):
180 if attr == 'any':
181 return AnyProxy(self.search_self, self.search_up)
182 else:
183 return AttrProxy(self.search_self, self.search_up, attr)
184
185# global objects for handling proxies
186Parent = ProxyFactory(search_self = False, search_up = True)
187Self = ProxyFactory(search_self = True, search_up = False)
188
189# limit exports on 'from proxy import *'
190__all__ = ['Parent', 'Self']
191
192# see comment on imports at end of __init__.py.
193import params # for EthernetAddr
46 super(BaseProxy, self).__setattr__(attr, value)
47
48 # support multiplying proxies by constants
49 def __mul__(self, other):
50 if not isinstance(other, (int, long, float)):
51 raise TypeError, "Proxy multiplier must be integer"
52 if self._multiplier == None:
53 self._multiplier = other
54 else:
55 # support chained multipliers
56 self._multiplier *= other
57 return self
58
59 __rmul__ = __mul__
60
61 def _mulcheck(self, result):
62 if self._multiplier == None:
63 return result
64 return result * self._multiplier
65
66 def unproxy(self, base):
67 obj = base
68 done = False
69
70 if self._search_self:
71 result, done = self.find(obj)
72
73 if self._search_up:
74 while not done:
75 obj = obj._parent
76 if not obj:
77 break
78 result, done = self.find(obj)
79
80 if not done:
81 raise AttributeError, \
82 "Can't resolve proxy '%s' of type '%s' from '%s'" % \
83 (self.path(), self._pdesc.ptype_str, base.path())
84
85 if isinstance(result, BaseProxy):
86 if result == self:
87 raise RuntimeError, "Cycle in unproxy"
88 result = result.unproxy(obj)
89
90 return self._mulcheck(result)
91
92 def getindex(obj, index):
93 if index == None:
94 return obj
95 try:
96 obj = obj[index]
97 except TypeError:
98 if index != 0:
99 raise
100 # if index is 0 and item is not subscriptable, just
101 # use item itself (so cpu[0] works on uniprocessors)
102 return obj
103 getindex = staticmethod(getindex)
104
105 def set_param_desc(self, pdesc):
106 self._pdesc = pdesc
107
108class AttrProxy(BaseProxy):
109 def __init__(self, search_self, search_up, attr):
110 super(AttrProxy, self).__init__(search_self, search_up)
111 self._attr = attr
112 self._modifiers = []
113
114 def __getattr__(self, attr):
115 # python uses __bases__ internally for inheritance
116 if attr.startswith('_'):
117 return super(AttrProxy, self).__getattr__(self, attr)
118 if hasattr(self, '_pdesc'):
119 raise AttributeError, "Attribute reference on bound proxy"
120 self._modifiers.append(attr)
121 return self
122
123 # support indexing on proxies (e.g., Self.cpu[0])
124 def __getitem__(self, key):
125 if not isinstance(key, int):
126 raise TypeError, "Proxy object requires integer index"
127 self._modifiers.append(key)
128 return self
129
130 def find(self, obj):
131 try:
132 val = getattr(obj, self._attr)
133 except:
134 return None, False
135 while isproxy(val):
136 val = val.unproxy(obj)
137 for m in self._modifiers:
138 if isinstance(m, str):
139 val = getattr(val, m)
140 elif isinstance(m, int):
141 val = val[m]
142 else:
143 assert("Item must be string or integer")
144 while isproxy(val):
145 val = val.unproxy(obj)
146 return val, True
147
148 def path(self):
149 p = self._attr
150 for m in self._modifiers:
151 if isinstance(m, str):
152 p += '.%s' % m
153 elif isinstance(m, int):
154 p += '[%d]' % m
155 else:
156 assert("Item must be string or integer")
157 return p
158
159class AnyProxy(BaseProxy):
160 def find(self, obj):
161 return obj.find_any(self._pdesc.ptype)
162
163 def path(self):
164 return 'any'
165
166def isproxy(obj):
167 if isinstance(obj, (BaseProxy, params.EthernetAddr)):
168 return True
169 elif isinstance(obj, (list, tuple)):
170 for v in obj:
171 if isproxy(v):
172 return True
173 return False
174
175class ProxyFactory(object):
176 def __init__(self, search_self, search_up):
177 self.search_self = search_self
178 self.search_up = search_up
179
180 def __getattr__(self, attr):
181 if attr == 'any':
182 return AnyProxy(self.search_self, self.search_up)
183 else:
184 return AttrProxy(self.search_self, self.search_up, attr)
185
186# global objects for handling proxies
187Parent = ProxyFactory(search_self = False, search_up = True)
188Self = ProxyFactory(search_self = True, search_up = False)
189
190# limit exports on 'from proxy import *'
191__all__ = ['Parent', 'Self']
192
193# see comment on imports at end of __init__.py.
194import params # for EthernetAddr