py-common: make bt_py_common_format_exception accept an arbitrary exception
[babeltrace.git] / src / bindings / python / bt2 / bt2 / field.py
CommitLineData
81447b5b
PP
1# The MIT License (MIT)
2#
811644b8 3# Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
81447b5b
PP
4#
5# Permission is hereby granted, free of charge, to any person obtaining a copy
6# of this software and associated documentation files (the "Software"), to deal
7# in the Software without restriction, including without limitation the rights
8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9# copies of the Software, and to permit persons to whom the Software is
10# furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice shall be included in
13# all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21# THE SOFTWARE.
22
23from bt2 import native_bt, object, utils
b4f45851 24import bt2.field_class
81447b5b
PP
25import collections.abc
26import functools
27import numbers
28import math
81447b5b
PP
29import bt2
30
31
2ae9f48c
SM
32def _create_field_from_ptr(ptr, owner_ptr, owner_get_ref, owner_put_ref):
33 field_class_ptr = native_bt.field_borrow_class_const(ptr)
34 utils._handle_ptr(field_class_ptr, "cannot get field object's class")
35 typeid = native_bt.field_class_get_type(field_class_ptr)
36 field = _TYPE_ID_TO_OBJ[typeid]._create_from_ptr_and_get_ref(
cfbd7cf3
FD
37 ptr, owner_ptr, owner_get_ref, owner_put_ref
38 )
81447b5b
PP
39 return field
40
41
1eccc498
SM
42# Get the "effective" field of `field`. If `field` is a variant, return the
43# currently selected field. If `field` is of any other type, return `field`
44# directly.
81447b5b 45
cfbd7cf3 46
1eccc498
SM
47def _get_leaf_field(field):
48 if not isinstance(field, _VariantField):
49 return field
50
51 return _get_leaf_field(field.selected_option)
81447b5b 52
e1c6bebd 53
1eccc498
SM
54class _Field(object._UniqueObject):
55 def __eq__(self, other):
e1c6bebd
JG
56 other = _get_leaf_field(other)
57 return self._spec_eq(other)
58
81447b5b 59 @property
b4f45851 60 def field_class(self):
838a5a52
SM
61 field_class_ptr = native_bt.field_borrow_class_const(self._ptr)
62 assert field_class_ptr is not None
63 return bt2.field_class._create_field_class_from_ptr_and_get_ref(field_class_ptr)
81447b5b 64
12bf0d88
JG
65 def _repr(self):
66 raise NotImplementedError
67
68 def __repr__(self):
1eccc498 69 return self._repr()
12bf0d88 70
81447b5b
PP
71
72@functools.total_ordering
73class _NumericField(_Field):
74 @staticmethod
75 def _extract_value(other):
f11ed062 76 if isinstance(other, bool):
81447b5b
PP
77 return other
78
79 if isinstance(other, numbers.Integral):
80 return int(other)
81
82 if isinstance(other, numbers.Real):
83 return float(other)
84
85 if isinstance(other, numbers.Complex):
86 return complex(other)
87
cfbd7cf3
FD
88 raise TypeError(
89 "'{}' object is not a number object".format(other.__class__.__name__)
90 )
81447b5b
PP
91
92 def __int__(self):
e1c6bebd 93 return int(self._value)
81447b5b
PP
94
95 def __float__(self):
e1c6bebd 96 return float(self._value)
81447b5b 97
12bf0d88 98 def _repr(self):
5abb9e33 99 return repr(self._value)
81447b5b
PP
100
101 def __lt__(self, other):
102 if not isinstance(other, numbers.Number):
cfbd7cf3
FD
103 raise TypeError(
104 'unorderable types: {}() < {}()'.format(
105 self.__class__.__name__, other.__class__.__name__
106 )
107 )
81447b5b 108
09a926c1 109 return self._value < self._extract_value(other)
81447b5b 110
e1c6bebd 111 def _spec_eq(self, other):
f11ed062
PP
112 try:
113 return self._value == self._extract_value(other)
114 except:
115 return False
81447b5b
PP
116
117 def __rmod__(self, other):
e1c6bebd 118 return self._extract_value(other) % self._value
81447b5b
PP
119
120 def __mod__(self, other):
e1c6bebd 121 return self._value % self._extract_value(other)
81447b5b
PP
122
123 def __rfloordiv__(self, other):
e1c6bebd 124 return self._extract_value(other) // self._value
81447b5b
PP
125
126 def __floordiv__(self, other):
e1c6bebd 127 return self._value // self._extract_value(other)
81447b5b
PP
128
129 def __round__(self, ndigits=None):
130 if ndigits is None:
e1c6bebd 131 return round(self._value)
81447b5b 132 else:
e1c6bebd 133 return round(self._value, ndigits)
81447b5b
PP
134
135 def __ceil__(self):
e1c6bebd 136 return math.ceil(self._value)
81447b5b
PP
137
138 def __floor__(self):
e1c6bebd 139 return math.floor(self._value)
81447b5b
PP
140
141 def __trunc__(self):
e1c6bebd 142 return int(self._value)
81447b5b
PP
143
144 def __abs__(self):
e1c6bebd 145 return abs(self._value)
81447b5b
PP
146
147 def __add__(self, other):
e1c6bebd 148 return self._value + self._extract_value(other)
81447b5b
PP
149
150 def __radd__(self, other):
151 return self.__add__(other)
152
153 def __neg__(self):
e1c6bebd 154 return -self._value
81447b5b
PP
155
156 def __pos__(self):
e1c6bebd 157 return +self._value
81447b5b
PP
158
159 def __mul__(self, other):
e1c6bebd 160 return self._value * self._extract_value(other)
81447b5b
PP
161
162 def __rmul__(self, other):
163 return self.__mul__(other)
164
165 def __truediv__(self, other):
e1c6bebd 166 return self._value / self._extract_value(other)
81447b5b
PP
167
168 def __rtruediv__(self, other):
e1c6bebd 169 return self._extract_value(other) / self._value
81447b5b
PP
170
171 def __pow__(self, exponent):
e1c6bebd 172 return self._value ** self._extract_value(exponent)
81447b5b
PP
173
174 def __rpow__(self, base):
e1c6bebd 175 return self._extract_value(base) ** self._value
81447b5b 176
81447b5b
PP
177
178class _IntegralField(_NumericField, numbers.Integral):
179 def __lshift__(self, other):
e1c6bebd 180 return self._value << self._extract_value(other)
81447b5b
PP
181
182 def __rlshift__(self, other):
e1c6bebd 183 return self._extract_value(other) << self._value
81447b5b
PP
184
185 def __rshift__(self, other):
e1c6bebd 186 return self._value >> self._extract_value(other)
81447b5b
PP
187
188 def __rrshift__(self, other):
e1c6bebd 189 return self._extract_value(other) >> self._value
81447b5b
PP
190
191 def __and__(self, other):
e1c6bebd 192 return self._value & self._extract_value(other)
81447b5b
PP
193
194 def __rand__(self, other):
e1c6bebd 195 return self._extract_value(other) & self._value
81447b5b
PP
196
197 def __xor__(self, other):
e1c6bebd 198 return self._value ^ self._extract_value(other)
81447b5b
PP
199
200 def __rxor__(self, other):
e1c6bebd 201 return self._extract_value(other) ^ self._value
81447b5b
PP
202
203 def __or__(self, other):
e1c6bebd 204 return self._value | self._extract_value(other)
81447b5b
PP
205
206 def __ror__(self, other):
e1c6bebd 207 return self._extract_value(other) | self._value
81447b5b
PP
208
209 def __invert__(self):
e1c6bebd 210 return ~self._value
81447b5b 211
81447b5b 212
2ae9f48c 213class _IntegerField(_IntegralField, _Field):
81447b5b
PP
214 pass
215
216
2ae9f48c
SM
217class _UnsignedIntegerField(_IntegerField, _Field):
218 _NAME = 'Unsigned integer'
1eccc498 219
81447b5b 220 def _value_to_int(self, value):
25bb9bab
PP
221 if not isinstance(value, numbers.Integral):
222 raise TypeError('expecting an integral number object')
81447b5b
PP
223
224 value = int(value)
2ae9f48c 225 utils._check_uint64(value)
81447b5b
PP
226
227 return value
228
229 @property
e1c6bebd 230 def _value(self):
9c08c816 231 return native_bt.field_integer_unsigned_get_value(self._ptr)
81447b5b 232
2ae9f48c
SM
233 def _set_value(self, value):
234 value = self._value_to_int(value)
9c08c816 235 native_bt.field_integer_unsigned_set_value(self._ptr, value)
2ae9f48c
SM
236
237 value = property(fset=_set_value)
238
239
240class _SignedIntegerField(_IntegerField, _Field):
241 _NAME = 'Signed integer'
1eccc498 242
2ae9f48c 243 def _value_to_int(self, value):
25bb9bab
PP
244 if not isinstance(value, numbers.Integral):
245 raise TypeError('expecting an integral number object')
e1c6bebd 246
2ae9f48c
SM
247 value = int(value)
248 utils._check_int64(value)
811644b8 249
81447b5b
PP
250 return value
251
2ae9f48c
SM
252 @property
253 def _value(self):
9c08c816 254 return native_bt.field_integer_signed_get_value(self._ptr)
2ae9f48c 255
e1c6bebd 256 def _set_value(self, value):
81447b5b 257 value = self._value_to_int(value)
9c08c816 258 native_bt.field_integer_signed_set_value(self._ptr, value)
81447b5b 259
e1c6bebd 260 value = property(fset=_set_value)
81447b5b 261
0b03f63e 262
2ae9f48c
SM
263class _RealField(_NumericField, numbers.Real):
264 _NAME = 'Real'
81447b5b
PP
265
266 def _value_to_float(self, value):
267 if not isinstance(value, numbers.Real):
268 raise TypeError("expecting a real number object")
269
270 return float(value)
271
272 @property
e1c6bebd 273 def _value(self):
2ae9f48c 274 return native_bt.field_real_get_value(self._ptr)
81447b5b 275
e1c6bebd 276 def _set_value(self, value):
81447b5b 277 value = self._value_to_float(value)
2ae9f48c 278 native_bt.field_real_set_value(self._ptr, value)
81447b5b 279
e1c6bebd 280 value = property(fset=_set_value)
81447b5b 281
0b03f63e 282
81447b5b 283class _EnumerationField(_IntegerField):
1eccc498
SM
284 def _repr(self):
285 return '{} ({})'.format(self._value, ', '.join(self.labels))
81447b5b
PP
286
287 @property
1eccc498 288 def labels(self):
d24d5663 289 status, labels = self._get_mapping_labels(self._ptr)
cfbd7cf3 290 utils._handle_func_status(status, "cannot get label for enumeration field")
81447b5b 291
1eccc498
SM
292 assert labels is not None
293 return labels
81447b5b 294
4addd228 295
1eccc498
SM
296class _UnsignedEnumerationField(_EnumerationField, _UnsignedIntegerField):
297 _NAME = 'Unsigned Enumeration'
cfbd7cf3 298 _get_mapping_labels = staticmethod(
9c08c816 299 native_bt.field_enumeration_unsigned_get_mapping_labels
cfbd7cf3 300 )
e1c6bebd 301
e1c6bebd 302
1eccc498
SM
303class _SignedEnumerationField(_EnumerationField, _SignedIntegerField):
304 _NAME = 'Signed Enumeration'
cfbd7cf3 305 _get_mapping_labels = staticmethod(
9c08c816 306 native_bt.field_enumeration_signed_get_mapping_labels
cfbd7cf3 307 )
81447b5b
PP
308
309
310@functools.total_ordering
1eccc498 311class _StringField(_Field):
81447b5b
PP
312 _NAME = 'String'
313
314 def _value_to_str(self, value):
315 if isinstance(value, self.__class__):
e1c6bebd 316 value = value._value
81447b5b
PP
317
318 if not isinstance(value, str):
319 raise TypeError("expecting a 'str' object")
320
321 return value
322
323 @property
e1c6bebd 324 def _value(self):
1eccc498 325 return native_bt.field_string_get_value(self._ptr)
81447b5b 326
e1c6bebd 327 def _set_value(self, value):
81447b5b 328 value = self._value_to_str(value)
1eccc498 329 native_bt.field_string_set_value(self._ptr, value)
81447b5b 330
e1c6bebd
JG
331 value = property(fset=_set_value)
332
333 def _spec_eq(self, other):
81447b5b 334 try:
f11ed062
PP
335 return self._value == self._value_to_str(other)
336 except:
81447b5b
PP
337 return False
338
81447b5b 339 def __lt__(self, other):
e1c6bebd 340 return self._value < self._value_to_str(other)
81447b5b
PP
341
342 def __bool__(self):
e1c6bebd 343 return bool(self._value)
81447b5b 344
12bf0d88 345 def _repr(self):
d623d2e9
JG
346 return repr(self._value)
347
81447b5b 348 def __str__(self):
1eccc498 349 return str(self._value)
81447b5b
PP
350
351 def __getitem__(self, index):
e1c6bebd 352 return self._value[index]
81447b5b
PP
353
354 def __len__(self):
1eccc498 355 return native_bt.field_string_get_length(self._ptr)
81447b5b
PP
356
357 def __iadd__(self, value):
358 value = self._value_to_str(value)
d24d5663 359 status = native_bt.field_string_append(self._ptr, value)
cfbd7cf3
FD
360 utils._handle_func_status(
361 status, "cannot append to string field object's value"
362 )
81447b5b
PP
363 return self
364
365
366class _ContainerField(_Field):
367 def __bool__(self):
368 return len(self) != 0
369
370 def __len__(self):
371 count = self._count()
1eccc498 372 assert count >= 0
81447b5b
PP
373 return count
374
375 def __delitem__(self, index):
376 raise NotImplementedError
377
378
379class _StructureField(_ContainerField, collections.abc.MutableMapping):
380 _NAME = 'Structure'
381
382 def _count(self):
b4f45851 383 return len(self.field_class)
81447b5b 384
81447b5b 385 def __setitem__(self, key, value):
236355c2 386 # raises if key is somehow invalid
81447b5b
PP
387 field = self[key]
388
81447b5b
PP
389 # the field's property does the appropriate conversion or raises
390 # the appropriate exception
391 field.value = value
392
81447b5b
PP
393 def __iter__(self):
394 # same name iterator
b4f45851 395 return iter(self.field_class)
81447b5b 396
e1c6bebd 397 def _spec_eq(self, other):
f11ed062
PP
398 if not isinstance(other, collections.abc.Mapping):
399 return False
81447b5b 400
f11ed062
PP
401 if len(self) != len(other):
402 # early mismatch
403 return False
81447b5b 404
f11ed062
PP
405 for self_key in self:
406 if self_key not in other:
407 return False
81447b5b 408
f11ed062
PP
409 if self[self_key] != other[self_key]:
410 return False
e1c6bebd 411
f11ed062 412 return True
81447b5b 413
e1c6bebd 414 def _set_value(self, values):
e1c6bebd
JG
415 try:
416 for key, value in values.items():
417 self[key].value = value
1eccc498 418 except Exception:
e1c6bebd 419 raise
7c54e2e7 420
e1c6bebd 421 value = property(fset=_set_value)
81447b5b 422
12bf0d88 423 def _repr(self):
ac7e2dc6
JG
424 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
425 return '{{{}}}'.format(', '.join(items))
426
1eccc498
SM
427 def __getitem__(self, key):
428 utils._check_str(key)
cfbd7cf3
FD
429 field_ptr = native_bt.field_structure_borrow_member_field_by_name(
430 self._ptr, key
431 )
0b03f63e 432
1eccc498
SM
433 if field_ptr is None:
434 raise KeyError(key)
81447b5b 435
cfbd7cf3
FD
436 return _create_field_from_ptr(
437 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
438 )
811644b8 439
1eccc498
SM
440 def member_at_index(self, index):
441 utils._check_uint64(index)
811644b8 442
1eccc498
SM
443 if index >= len(self):
444 raise IndexError
445
cfbd7cf3
FD
446 field_ptr = native_bt.field_structure_borrow_member_field_by_index(
447 self._ptr, index
448 )
1eccc498 449 assert field_ptr is not None
cfbd7cf3
FD
450 return _create_field_from_ptr(
451 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
452 )
1eccc498
SM
453
454
455class _VariantField(_ContainerField, _Field):
456 _NAME = 'Variant'
81447b5b
PP
457
458 @property
1eccc498
SM
459 def selected_option_index(self):
460 return native_bt.field_variant_get_selected_option_field_index(self._ptr)
81447b5b 461
1eccc498
SM
462 @selected_option_index.setter
463 def selected_option_index(self, index):
45c51519 464 native_bt.field_variant_select_option_field_by_index(self._ptr, index)
811644b8 465
1eccc498
SM
466 @property
467 def selected_option(self):
468 field_ptr = native_bt.field_variant_borrow_selected_option_field(self._ptr)
469 utils._handle_ptr(field_ptr, "cannot get variant field's selected option")
81447b5b 470
cfbd7cf3
FD
471 return _create_field_from_ptr(
472 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
473 )
81447b5b 474
e1c6bebd 475 def _spec_eq(self, other):
f11ed062 476 return _get_leaf_field(self) == other
811644b8
PP
477
478 def __bool__(self):
1eccc498 479 raise NotImplementedError
81447b5b 480
12bf0d88 481 def __str__(self):
1eccc498 482 return str(self.selected_option)
12bf0d88
JG
483
484 def _repr(self):
1eccc498 485 return repr(self.selected_option)
e1c6bebd
JG
486
487 def _set_value(self, value):
1eccc498 488 self.selected_option.value = value
e1c6bebd
JG
489
490 value = property(fset=_set_value)
81447b5b 491
0b03f63e 492
c2ea62f5 493class _ArrayField(_ContainerField, _Field, collections.abc.MutableSequence):
1eccc498
SM
494 def _get_length(self):
495 return native_bt.field_array_get_length(self._ptr)
496
497 length = property(fget=_get_length)
498
81447b5b
PP
499 def __getitem__(self, index):
500 if not isinstance(index, numbers.Integral):
cfbd7cf3
FD
501 raise TypeError(
502 "'{}' is not an integral number object: invalid index".format(
503 index.__class__.__name__
504 )
505 )
81447b5b
PP
506
507 index = int(index)
508
509 if index < 0 or index >= len(self):
510 raise IndexError('{} field object index is out of range'.format(self._NAME))
511
cfbd7cf3
FD
512 field_ptr = native_bt.field_array_borrow_element_field_by_index(
513 self._ptr, index
514 )
515 assert field_ptr
516 return _create_field_from_ptr(
517 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
518 )
81447b5b
PP
519
520 def __setitem__(self, index, value):
81447b5b
PP
521 # raises if index is somehow invalid
522 field = self[index]
523
524 if not isinstance(field, (_NumericField, _StringField)):
525 raise TypeError('can only set the value of a number or string field')
526
527 # the field's property does the appropriate conversion or raises
528 # the appropriate exception
529 field.value = value
530
531 def insert(self, index, value):
532 raise NotImplementedError
533
e1c6bebd 534 def _spec_eq(self, other):
f11ed062
PP
535 if not isinstance(other, collections.abc.Sequence):
536 return False
7c54e2e7 537
f11ed062
PP
538 if len(self) != len(other):
539 # early mismatch
e1c6bebd 540 return False
7c54e2e7 541
f11ed062
PP
542 for self_elem, other_elem in zip(self, other):
543 if self_elem != other_elem:
544 return False
545
546 return True
547
12bf0d88 548 def _repr(self):
2bc21382
JG
549 return '[{}]'.format(', '.join([repr(v) for v in self]))
550
81447b5b 551
1eccc498
SM
552class _StaticArrayField(_ArrayField, _Field):
553 _NAME = 'Static array'
81447b5b
PP
554
555 def _count(self):
1eccc498 556 return native_bt.field_array_get_length(self._ptr)
81447b5b 557
e1c6bebd
JG
558 def _set_value(self, values):
559 if len(self) != len(values):
cfbd7cf3 560 raise ValueError('expected length of value and array field to match')
e1c6bebd 561
1eccc498
SM
562 for index, value in enumerate(values):
563 if value is not None:
564 self[index].value = value
e1c6bebd
JG
565
566 value = property(fset=_set_value)
567
81447b5b 568
1eccc498
SM
569class _DynamicArrayField(_ArrayField, _Field):
570 _NAME = 'Dynamic array'
81447b5b
PP
571
572 def _count(self):
1eccc498 573 return self.length
81447b5b 574
1eccc498
SM
575 def _set_length(self, length):
576 utils._check_uint64(length)
9c08c816 577 status = native_bt.field_array_dynamic_set_length(self._ptr, length)
d24d5663 578 utils._handle_func_status(status, "cannot set dynamic array length")
81447b5b 579
1eccc498 580 length = property(fget=_ArrayField._get_length, fset=_set_length)
81447b5b 581
e1c6bebd 582 def _set_value(self, values):
1eccc498
SM
583 if len(values) != self.length:
584 self.length = len(values)
e1c6bebd 585
1eccc498
SM
586 for index, value in enumerate(values):
587 if value is not None:
588 self[index].value = value
e1c6bebd
JG
589
590 value = property(fset=_set_value)
81447b5b 591
0b03f63e 592
81447b5b 593_TYPE_ID_TO_OBJ = {
2ae9f48c
SM
594 native_bt.FIELD_CLASS_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerField,
595 native_bt.FIELD_CLASS_TYPE_SIGNED_INTEGER: _SignedIntegerField,
596 native_bt.FIELD_CLASS_TYPE_REAL: _RealField,
1eccc498
SM
597 native_bt.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION: _UnsignedEnumerationField,
598 native_bt.FIELD_CLASS_TYPE_SIGNED_ENUMERATION: _SignedEnumerationField,
2ae9f48c
SM
599 native_bt.FIELD_CLASS_TYPE_STRING: _StringField,
600 native_bt.FIELD_CLASS_TYPE_STRUCTURE: _StructureField,
1eccc498
SM
601 native_bt.FIELD_CLASS_TYPE_STATIC_ARRAY: _StaticArrayField,
602 native_bt.FIELD_CLASS_TYPE_DYNAMIC_ARRAY: _DynamicArrayField,
45c51519
PP
603 native_bt.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR: _VariantField,
604 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR: _VariantField,
605 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR: _VariantField,
81447b5b 606}
This page took 0.077898 seconds and 4 git commands to generate.