-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathcpp_const.py
280 lines (227 loc) · 8.56 KB
/
cpp_const.py
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""
Enables a semi-transparent layer of C++ const-honoring Python proxies.
"""
import inspect
from types import MethodType
from pydrake.third_party.wrapt import ObjectProxy
# TODO(eric.cousineau): Add mechanism for enabling / disabling const-proxying.
# TODO(eric.cousineau): Determine if propagation for `const` attributes and
# methods is ever useful in pure Python, for things such as `__iter__`,
# `__getitem__`, `__getslice__`, etc.
class ConstError(TypeError):
"""Indicates `const` access violations."""
pass
class _ConstClassMeta(object):
# Provides metadata for a given class.
def __init__(self, cls, owned_properties=None, mutable_methods=None):
self._cls = cls
self._owned_properties = set(owned_properties or set())
self.mutable_methods = set(mutable_methods or set())
# Add any decorated mutable methods.
methods = inspect.getmembers(cls, predicate=inspect.ismethod)
for name, method in methods:
# TODO(eric.cousineau): Warn if there is a mix of mutable and
# immutable methods with the same name.
if getattr(method, '_is_mutable_method', False):
self.mutable_methods.add(name)
# Handle inheritance.
for base_cls in self._cls.__bases__:
base_meta = _const_metas.get(base_cls) # Minor cyclic dependency.
self._owned_properties.update(base_meta._owned_properties)
self.mutable_methods.update(base_meta.mutable_methods)
def is_owned_property(self, name):
# Determines if a property is owned, and if the returned value should
# be `const`.
return name in self._owned_properties
def is_mutable_method(self, name):
# Determines if a method is mutable by name.
# N.B. This would not handle overloads (e.g. differing between
# `T& get()` and `const T& get() const`).
# However, if using `pybind11`, the method signatures should play well
# with custom `type_caster`s that will permit the overloads to
# organically prevent `const` violations.
return name in self.mutable_methods
class _ConstClassMetaMap(object):
# Provides mapping from class to metadata.
def __init__(self):
self._meta_map = {}
def emplace(self, cls, owned_properties=None, mutable_methods=None):
# Constructs metadata and reigstered it.
meta = _ConstClassMeta(cls, owned_properties, mutable_methods)
return self._add(cls, meta)
def _add(self, cls, meta):
assert cls not in self._meta_map
self._meta_map[cls] = meta
return meta
def get(self, cls):
# Retrieves metadata for a class.
# Assumes class has not changed if it's already registered.
meta = self._meta_map.get(cls, None)
if meta:
return meta
else:
# Construct default.
return self._add(cls, _ConstClassMeta(cls))
_const_metas = _ConstClassMetaMap()
# Register common mutators.
# N.B. All methods registered will respect inheritance.
# N.B. For `object`, see `_install_object_mutable_methods`.
_const_metas.emplace(object, mutable_methods={
"__setattr__",
"__delattr__",
"__setitem__",
"__delitem__",
"__setslice__",
"__iadd__",
"__isub__",
"__imul__",
"__idiv__",
"__itruediv__",
"__ifloordiv__",
"__imod__",
"__ipow__",
"__ilshift__",
"__irshift__",
"__iand__",
"__ixor__",
"__ior__",
"__enter__",
"__exit__",
})
_const_metas.emplace(list, mutable_methods={
"append",
"clear",
"extend",
"insert",
"pop",
"remove",
"reverse",
"sort",
})
_const_metas.emplace(dict, mutable_methods={
"clear",
"pop",
"popitem",
"setdefault",
"update",
})
class _Const(ObjectProxy):
# Wraps an object, restricting access to non-mutable methods and
# properties.
def __init__(self, wrapped):
ObjectProxy.__init__(self, wrapped)
def __getattr__(self, name):
# Intercepts access to mutable methods, general methods, and owned
# properties.
wrapped = object.__getattribute__(self, '__wrapped__')
meta = _const_metas.get(type(wrapped))
value = getattr(wrapped, name)
if meta.is_mutable_method(name):
# If decorated as a mutable method, raise an error. Do not allow
# access to the bound method, because the only way this method
# *should* become usable is to rebind it.
_raise_mutable_method_error(self, name)
elif _is_method_of(value, wrapped):
# Rebind method to const `self` recursively catch basic violations.
return _rebind_method(value, self)
elif meta.is_owned_property(name):
# References (pointer-like things) should not be const, but
# internal values should.
return to_const(value)
else:
return value
def __dict_custom__(self):
return to_const(self.__wrapped__.__dict__)
def __repr__(self):
out = self.__wrapped__.__repr__()
if (len(out) >= 2 and out[0] == '<' and out[-1] == '>'):
return '<const ' + out[1:]
else:
return out
def _install_object_mutable_methods():
# Installs methods to `_Const` that will always raise an error.
# N.B. The methods for `object` actually have to be overridden in `_Const`,
# since neither `__getattr__` nor `__getattribute__` will capture them.
for name in _const_metas.get(object).mutable_methods:
def _capture(name):
def _no_mutable(self, *args, **kwargs):
_raise_mutable_method_error(self, name)
_no_mutable.__name__ = name
setattr(_Const, name, _no_mutable)
_capture(name)
_install_object_mutable_methods()
def _is_immutable(obj):
# Detects if a type is a immutable (or literal) type.
literal_types = [int, float, str, unicode, tuple, type(None)]
if type(obj) in literal_types:
return True
else:
return False
def _is_method_of(func, obj):
# Detects if `func` is a function bound to a given instance `obj`.
return inspect.ismethod(func) and func.im_self is obj
def _rebind_method(bound, new_self):
# Rebinds `bound.im_self` to `new_self`.
# https://stackoverflow.com/a/14574713/7829525
return MethodType(bound.__func__, new_self, bound.im_class)
def to_const(obj):
"""Converts an object to a const proxy.
Accepts any object type. If object is immutable or already const, it will
be passed through.
"""
if is_const_or_immutable(obj):
return obj
else:
return _Const(obj)
def to_mutable(obj, force=False):
"""Converts to a mutable (non-const proxied) object.
If `force` is False, will throw an error if `obj` is const.
"""
if is_const(obj):
if not force:
raise ConstError(
"Cannot cast const {} to mutable instance"
.format(type_extract(obj)))
return obj.__wrapped__
else:
return obj
def is_const(obj):
"""Determines if `obj` is const-proxied.
WARNING: Do NOT use this for branching in production code unless
const-proxying is guaranteed to be enabled or the branching is designed
not to fail in this case.
"""
if isinstance(obj, _Const):
return True
else:
return False
def is_const_or_immutable(obj):
"""Determines if `obj` is const-proxied or immutable.
WARNING: Do NOT use this for branching in production code unless
const-proxying is guaranteed to be enabled or the branching is designed
not to fail in this case.
"""
return is_const(obj) or _is_immutable(obj)
def type_extract(obj):
"""Extracts type from an object if it's const-proxied; otherwise returns
direct type.
"""
if is_const(obj):
return type(obj.__wrapped__)
else:
return type(obj)
def _raise_mutable_method_error(obj, name):
raise ConstError(
("'{}' is a mutable method that cannot be called on a " +
"const {}.").format(name, type_extract(obj)))
def mutable_method(func):
"""Returns a function decorated as mutable."""
func._is_mutable_method = True
return func
def _add_const_meta(cls, owned_properties=None, mutable_methods=None):
# Adds const-proxy metadata to a class.
_const_metas.emplace(cls, owned_properties, mutable_methods)
return cls
def const_decorated(owned_properties=None, mutable_methods=None):
"""Returns a class decorated with const-proxy metadata."""
return lambda cls: _add_const_meta(cls, owned_properties, mutable_methods)