proxy.py revision 13742
1# Copyright (c) 2018 ARM Limited
2# All rights reserved.
3#
4# The license below extends only to copyright in the software and shall
5# not be construed as granting a license to any other intellectual
6# property including but not limited to intellectual property relating
7# to a hardware implementation of the functionality of the software
8# licensed hereunder.  You may use the software subject to the license
9# terms below provided that you ensure that this notice is replicated
10# unmodified and in its entirety in all distributions of the software,
11# modified or unmodified, in source code or in binary form.
12#
13# Copyright (c) 2004-2006 The Regents of The University of Michigan
14# All rights reserved.
15#
16# Redistribution and use in source and binary forms, with or without
17# modification, are permitted provided that the following conditions are
18# met: redistributions of source code must retain the above copyright
19# notice, this list of conditions and the following disclaimer;
20# redistributions in binary form must reproduce the above copyright
21# notice, this list of conditions and the following disclaimer in the
22# documentation and/or other materials provided with the distribution;
23# neither the name of the copyright holders nor the names of its
24# contributors may be used to endorse or promote products derived from
25# this software without specific prior written permission.
26#
27# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38#
39# Authors: Steve Reinhardt
40#          Nathan Binkert
41
42#####################################################################
43#
44# Proxy object support.
45#
46#####################################################################
47
48from __future__ import print_function
49from __future__ import absolute_import
50import six
51if six.PY3:
52    long = int
53
54import copy
55
56
57class BaseProxy(object):
58    def __init__(self, search_self, search_up):
59        self._search_self = search_self
60        self._search_up = search_up
61        self._multipliers = []
62
63    def __str__(self):
64        if self._search_self and not self._search_up:
65            s = 'Self'
66        elif not self._search_self and self._search_up:
67            s = 'Parent'
68        else:
69            s = 'ConfusedProxy'
70        return s + '.' + self.path()
71
72    def __setattr__(self, attr, value):
73        if not attr.startswith('_'):
74            raise AttributeError(
75                "cannot set attribute '%s' on proxy object" % attr)
76        super(BaseProxy, self).__setattr__(attr, value)
77
78    # support for multiplying proxies by constants or other proxies to
79    # other params
80    def __mul__(self, other):
81        if not (isinstance(other, (int, long, float)) or isproxy(other)):
82            raise TypeError(
83                "Proxy multiplier must be a constant or a proxy to a param")
84        self._multipliers.append(other)
85        return self
86
87    __rmul__ = __mul__
88
89    def _mulcheck(self, result, base):
90        for multiplier in self._multipliers:
91            if isproxy(multiplier):
92                multiplier = multiplier.unproxy(base)
93                # assert that we are multiplying with a compatible
94                # param
95                if not isinstance(multiplier, params.NumericParamValue):
96                    raise TypeError(
97                        "Proxy multiplier must be a numerical param")
98                multiplier = multiplier.getValue()
99            result *= multiplier
100        return result
101
102    def unproxy(self, base):
103        obj = base
104        done = False
105
106        if self._search_self:
107            result, done = self.find(obj)
108
109        if self._search_up:
110            # Search up the tree but mark ourself
111            # as visited to avoid a self-reference
112            self._visited = True
113            obj._visited = True
114            while not done:
115                obj = obj._parent
116                if not obj:
117                    break
118                result, done = self.find(obj)
119
120            self._visited = False
121            base._visited = False
122
123        if not done:
124            raise AttributeError(
125                "Can't resolve proxy '%s' of type '%s' from '%s'" % \
126                  (self.path(), self._pdesc.ptype_str, base.path()))
127
128        if isinstance(result, BaseProxy):
129            if result == self:
130                raise RuntimeError("Cycle in unproxy")
131            result = result.unproxy(obj)
132
133        return self._mulcheck(result, base)
134
135    def getindex(obj, index):
136        if index == None:
137            return obj
138        try:
139            obj = obj[index]
140        except TypeError:
141            if index != 0:
142                raise
143            # if index is 0 and item is not subscriptable, just
144            # use item itself (so cpu[0] works on uniprocessors)
145        return obj
146    getindex = staticmethod(getindex)
147
148    # This method should be called once the proxy is assigned to a
149    # particular parameter or port to set the expected type of the
150    # resolved proxy
151    def set_param_desc(self, pdesc):
152        self._pdesc = pdesc
153
154class AttrProxy(BaseProxy):
155    def __init__(self, search_self, search_up, attr):
156        super(AttrProxy, self).__init__(search_self, search_up)
157        self._attr = attr
158        self._modifiers = []
159
160    def __getattr__(self, attr):
161        # python uses __bases__ internally for inheritance
162        if attr.startswith('_'):
163            return super(AttrProxy, self).__getattr__(self, attr)
164        if hasattr(self, '_pdesc'):
165            raise AttributeError("Attribute reference on bound proxy")
166        # Return a copy of self rather than modifying self in place
167        # since self could be an indirect reference via a variable or
168        # parameter
169        new_self = copy.deepcopy(self)
170        new_self._modifiers.append(attr)
171        return new_self
172
173    # support indexing on proxies (e.g., Self.cpu[0])
174    def __getitem__(self, key):
175        if not isinstance(key, int):
176            raise TypeError("Proxy object requires integer index")
177        if hasattr(self, '_pdesc'):
178            raise AttributeError("Index operation on bound proxy")
179        new_self = copy.deepcopy(self)
180        new_self._modifiers.append(key)
181        return new_self
182
183    def find(self, obj):
184        try:
185            val = getattr(obj, self._attr)
186            visited = False
187            if hasattr(val, '_visited'):
188                visited = getattr(val, '_visited')
189
190            if visited:
191                return None, False
192
193            if not isproxy(val):
194                # for any additional unproxying to be done, pass the
195                # current, rather than the original object so that proxy
196                # has the right context
197                obj = val
198
199        except:
200            return None, False
201        while isproxy(val):
202            val = val.unproxy(obj)
203        for m in self._modifiers:
204            if isinstance(m, str):
205                val = getattr(val, m)
206            elif isinstance(m, int):
207                val = val[m]
208            else:
209                assert("Item must be string or integer")
210            while isproxy(val):
211                val = val.unproxy(obj)
212        return val, True
213
214    def path(self):
215        p = self._attr
216        for m in self._modifiers:
217            if isinstance(m, str):
218                p += '.%s' % m
219            elif isinstance(m, int):
220                p += '[%d]' % m
221            else:
222                assert("Item must be string or integer")
223        return p
224
225class AnyProxy(BaseProxy):
226    def find(self, obj):
227        return obj.find_any(self._pdesc.ptype)
228
229    def path(self):
230        return 'any'
231
232# The AllProxy traverses the entire sub-tree (not only the children)
233# and adds all objects of a specific type
234class AllProxy(BaseProxy):
235    def find(self, obj):
236        return obj.find_all(self._pdesc.ptype)
237
238    def path(self):
239        return 'all'
240
241def isproxy(obj):
242    from . import params
243    if isinstance(obj, (BaseProxy, params.EthernetAddr)):
244        return True
245    elif isinstance(obj, (list, tuple)):
246        for v in obj:
247            if isproxy(v):
248                return True
249    return False
250
251class ProxyFactory(object):
252    def __init__(self, search_self, search_up):
253        self.search_self = search_self
254        self.search_up = search_up
255
256    def __getattr__(self, attr):
257        if attr == 'any':
258            return AnyProxy(self.search_self, self.search_up)
259        elif attr == 'all':
260            if self.search_up:
261                assert("Parant.all is not supported")
262            return AllProxy(self.search_self, self.search_up)
263        else:
264            return AttrProxy(self.search_self, self.search_up, attr)
265
266# global objects for handling proxies
267Parent = ProxyFactory(search_self = False, search_up = True)
268Self = ProxyFactory(search_self = True, search_up = False)
269
270# limit exports on 'from proxy import *'
271__all__ = ['Parent', 'Self']
272