python: fix all "do not use bare 'except'" warnings
[babeltrace.git] / src / bindings / python / bt2 / bt2 / field.py
1 # The MIT License (MIT)
2 #
3 # Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
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
23 from bt2 import native_bt, object, utils
24 from bt2 import field_class as bt2_field_class
25 import collections.abc
26 import functools
27 import numbers
28 import math
29
30
31 def _create_field_from_ptr(ptr, owner_ptr, owner_get_ref, owner_put_ref):
32 field_class_ptr = native_bt.field_borrow_class_const(ptr)
33 typeid = native_bt.field_class_get_type(field_class_ptr)
34 field = _TYPE_ID_TO_OBJ[typeid]._create_from_ptr_and_get_ref(
35 ptr, owner_ptr, owner_get_ref, owner_put_ref
36 )
37 return field
38
39
40 # Get the "effective" field of `field`. If `field` is a variant, return
41 # the currently selected field. If `field` is an option, return the
42 # content field. If `field` is of any other type, return `field`
43 # directly.
44
45
46 def _get_leaf_field(field):
47 if isinstance(field, _VariantField):
48 return _get_leaf_field(field.selected_option)
49
50 if isinstance(field, _OptionField):
51 return _get_leaf_field(field.field)
52
53 return field
54
55
56 class _Field(object._UniqueObject):
57 def __eq__(self, other):
58 other = _get_leaf_field(other)
59 return self._spec_eq(other)
60
61 @property
62 def cls(self):
63 field_class_ptr = native_bt.field_borrow_class_const(self._ptr)
64 assert field_class_ptr is not None
65 return bt2_field_class._create_field_class_from_ptr_and_get_ref(field_class_ptr)
66
67 def _repr(self):
68 raise NotImplementedError
69
70 def __repr__(self):
71 return self._repr()
72
73
74 class _BitArrayField(_Field):
75 _NAME = 'Bit array'
76
77 @property
78 def value_as_integer(self):
79 return native_bt.field_bit_array_get_value_as_integer(self._ptr)
80
81 @value_as_integer.setter
82 def value_as_integer(self, value):
83 utils._check_uint64(value)
84 native_bt.field_bit_array_set_value_as_integer(self._ptr, value)
85
86 def _spec_eq(self, other):
87 if type(other) is not type(self):
88 return False
89
90 return self.value_as_integer == other.value_as_integer
91
92 def _repr(self):
93 return repr(self.value_as_integer)
94
95 def __str__(self):
96 return str(self.value_as_integer)
97
98 def __len__(self):
99 return self.cls.length
100
101
102 @functools.total_ordering
103 class _NumericField(_Field):
104 @staticmethod
105 def _extract_value(other):
106 if isinstance(other, _BoolField) or isinstance(other, bool):
107 return bool(other)
108
109 if isinstance(other, numbers.Integral):
110 return int(other)
111
112 if isinstance(other, numbers.Real):
113 return float(other)
114
115 if isinstance(other, numbers.Complex):
116 return complex(other)
117
118 raise TypeError(
119 "'{}' object is not a number object".format(other.__class__.__name__)
120 )
121
122 def __int__(self):
123 return int(self._value)
124
125 def __float__(self):
126 return float(self._value)
127
128 def _repr(self):
129 return repr(self._value)
130
131 def __lt__(self, other):
132 if not isinstance(other, numbers.Number):
133 raise TypeError(
134 'unorderable types: {}() < {}()'.format(
135 self.__class__.__name__, other.__class__.__name__
136 )
137 )
138
139 return self._value < self._extract_value(other)
140
141 def _spec_eq(self, other):
142 try:
143 return self._value == self._extract_value(other)
144 except Exception:
145 return False
146
147 def __rmod__(self, other):
148 return self._extract_value(other) % self._value
149
150 def __mod__(self, other):
151 return self._value % self._extract_value(other)
152
153 def __rfloordiv__(self, other):
154 return self._extract_value(other) // self._value
155
156 def __floordiv__(self, other):
157 return self._value // self._extract_value(other)
158
159 def __round__(self, ndigits=None):
160 if ndigits is None:
161 return round(self._value)
162 else:
163 return round(self._value, ndigits)
164
165 def __ceil__(self):
166 return math.ceil(self._value)
167
168 def __floor__(self):
169 return math.floor(self._value)
170
171 def __trunc__(self):
172 return int(self._value)
173
174 def __abs__(self):
175 return abs(self._value)
176
177 def __add__(self, other):
178 return self._value + self._extract_value(other)
179
180 def __radd__(self, other):
181 return self.__add__(other)
182
183 def __neg__(self):
184 return -self._value
185
186 def __pos__(self):
187 return +self._value
188
189 def __mul__(self, other):
190 return self._value * self._extract_value(other)
191
192 def __rmul__(self, other):
193 return self.__mul__(other)
194
195 def __truediv__(self, other):
196 return self._value / self._extract_value(other)
197
198 def __rtruediv__(self, other):
199 return self._extract_value(other) / self._value
200
201 def __pow__(self, exponent):
202 return self._value ** self._extract_value(exponent)
203
204 def __rpow__(self, base):
205 return self._extract_value(base) ** self._value
206
207
208 class _IntegralField(_NumericField, numbers.Integral):
209 def __lshift__(self, other):
210 return self._value << self._extract_value(other)
211
212 def __rlshift__(self, other):
213 return self._extract_value(other) << self._value
214
215 def __rshift__(self, other):
216 return self._value >> self._extract_value(other)
217
218 def __rrshift__(self, other):
219 return self._extract_value(other) >> self._value
220
221 def __and__(self, other):
222 return self._value & self._extract_value(other)
223
224 def __rand__(self, other):
225 return self._extract_value(other) & self._value
226
227 def __xor__(self, other):
228 return self._value ^ self._extract_value(other)
229
230 def __rxor__(self, other):
231 return self._extract_value(other) ^ self._value
232
233 def __or__(self, other):
234 return self._value | self._extract_value(other)
235
236 def __ror__(self, other):
237 return self._extract_value(other) | self._value
238
239 def __invert__(self):
240 return ~self._value
241
242
243 class _BoolField(_IntegralField, _Field):
244 _NAME = 'Boolean'
245
246 def __bool__(self):
247 return self._value
248
249 def _value_to_bool(self, value):
250 if isinstance(value, _BoolField):
251 value = value._value
252
253 if not isinstance(value, bool):
254 raise TypeError(
255 "'{}' object is not a 'bool' or '_BoolField' object".format(
256 value.__class__
257 )
258 )
259
260 return value
261
262 @property
263 def _value(self):
264 return bool(native_bt.field_bool_get_value(self._ptr))
265
266 def _set_value(self, value):
267 value = self._value_to_bool(value)
268 native_bt.field_bool_set_value(self._ptr, value)
269
270 value = property(fset=_set_value)
271
272
273 class _IntegerField(_IntegralField, _Field):
274 pass
275
276
277 class _UnsignedIntegerField(_IntegerField, _Field):
278 _NAME = 'Unsigned integer'
279
280 def _value_to_int(self, value):
281 if not isinstance(value, numbers.Integral):
282 raise TypeError('expecting an integral number object')
283
284 value = int(value)
285 utils._check_uint64(value)
286
287 return value
288
289 @property
290 def _value(self):
291 return native_bt.field_integer_unsigned_get_value(self._ptr)
292
293 def _set_value(self, value):
294 value = self._value_to_int(value)
295 native_bt.field_integer_unsigned_set_value(self._ptr, value)
296
297 value = property(fset=_set_value)
298
299
300 class _SignedIntegerField(_IntegerField, _Field):
301 _NAME = 'Signed integer'
302
303 def _value_to_int(self, value):
304 if not isinstance(value, numbers.Integral):
305 raise TypeError('expecting an integral number object')
306
307 value = int(value)
308 utils._check_int64(value)
309
310 return value
311
312 @property
313 def _value(self):
314 return native_bt.field_integer_signed_get_value(self._ptr)
315
316 def _set_value(self, value):
317 value = self._value_to_int(value)
318 native_bt.field_integer_signed_set_value(self._ptr, value)
319
320 value = property(fset=_set_value)
321
322
323 class _RealField(_NumericField, numbers.Real):
324 _NAME = 'Real'
325
326 def _value_to_float(self, value):
327 if not isinstance(value, numbers.Real):
328 raise TypeError("expecting a real number object")
329
330 return float(value)
331
332 @property
333 def _value(self):
334 return native_bt.field_real_get_value(self._ptr)
335
336 def _set_value(self, value):
337 value = self._value_to_float(value)
338 native_bt.field_real_set_value(self._ptr, value)
339
340 value = property(fset=_set_value)
341
342
343 class _EnumerationField(_IntegerField):
344 def _repr(self):
345 return '{} ({})'.format(self._value, ', '.join(self.labels))
346
347 @property
348 def labels(self):
349 status, labels = self._get_mapping_labels(self._ptr)
350 utils._handle_func_status(status, "cannot get label for enumeration field")
351
352 assert labels is not None
353 return labels
354
355
356 class _UnsignedEnumerationField(_EnumerationField, _UnsignedIntegerField):
357 _NAME = 'Unsigned Enumeration'
358 _get_mapping_labels = staticmethod(
359 native_bt.field_enumeration_unsigned_get_mapping_labels
360 )
361
362
363 class _SignedEnumerationField(_EnumerationField, _SignedIntegerField):
364 _NAME = 'Signed Enumeration'
365 _get_mapping_labels = staticmethod(
366 native_bt.field_enumeration_signed_get_mapping_labels
367 )
368
369
370 @functools.total_ordering
371 class _StringField(_Field):
372 _NAME = 'String'
373
374 def _value_to_str(self, value):
375 if isinstance(value, self.__class__):
376 value = value._value
377
378 if not isinstance(value, str):
379 raise TypeError("expecting a 'str' object")
380
381 return value
382
383 @property
384 def _value(self):
385 return native_bt.field_string_get_value(self._ptr)
386
387 def _set_value(self, value):
388 value = self._value_to_str(value)
389 native_bt.field_string_set_value(self._ptr, value)
390
391 value = property(fset=_set_value)
392
393 def _spec_eq(self, other):
394 try:
395 return self._value == self._value_to_str(other)
396 except Exception:
397 return False
398
399 def __lt__(self, other):
400 return self._value < self._value_to_str(other)
401
402 def __bool__(self):
403 return bool(self._value)
404
405 def _repr(self):
406 return repr(self._value)
407
408 def __str__(self):
409 return str(self._value)
410
411 def __getitem__(self, index):
412 return self._value[index]
413
414 def __len__(self):
415 return native_bt.field_string_get_length(self._ptr)
416
417 def __iadd__(self, value):
418 value = self._value_to_str(value)
419 status = native_bt.field_string_append(self._ptr, value)
420 utils._handle_func_status(
421 status, "cannot append to string field object's value"
422 )
423 return self
424
425
426 class _ContainerField(_Field):
427 def __bool__(self):
428 return len(self) != 0
429
430 def __len__(self):
431 count = self._count()
432 assert count >= 0
433 return count
434
435 def __delitem__(self, index):
436 raise NotImplementedError
437
438
439 class _StructureField(_ContainerField, collections.abc.MutableMapping):
440 _NAME = 'Structure'
441
442 def _count(self):
443 return len(self.cls)
444
445 def __setitem__(self, key, value):
446 # raises if key is somehow invalid
447 field = self[key]
448
449 # the field's property does the appropriate conversion or raises
450 # the appropriate exception
451 field.value = value
452
453 def __iter__(self):
454 # same name iterator
455 return iter(self.cls)
456
457 def _spec_eq(self, other):
458 if not isinstance(other, collections.abc.Mapping):
459 return False
460
461 if len(self) != len(other):
462 # early mismatch
463 return False
464
465 for self_key in self:
466 if self_key not in other:
467 return False
468
469 if self[self_key] != other[self_key]:
470 return False
471
472 return True
473
474 def _set_value(self, values):
475 try:
476 for key, value in values.items():
477 self[key].value = value
478 except Exception:
479 raise
480
481 value = property(fset=_set_value)
482
483 def _repr(self):
484 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
485 return '{{{}}}'.format(', '.join(items))
486
487 def __getitem__(self, key):
488 utils._check_str(key)
489 field_ptr = native_bt.field_structure_borrow_member_field_by_name(
490 self._ptr, key
491 )
492
493 if field_ptr is None:
494 raise KeyError(key)
495
496 return _create_field_from_ptr(
497 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
498 )
499
500 def member_at_index(self, index):
501 utils._check_uint64(index)
502
503 if index >= len(self):
504 raise IndexError
505
506 field_ptr = native_bt.field_structure_borrow_member_field_by_index(
507 self._ptr, index
508 )
509 assert field_ptr is not None
510 return _create_field_from_ptr(
511 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
512 )
513
514
515 class _OptionField(_Field):
516 _NAME = 'Option'
517
518 @property
519 def field(self):
520 field_ptr = native_bt.field_option_borrow_field_const(self._ptr)
521
522 if field_ptr is None:
523 return
524
525 return _create_field_from_ptr(
526 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
527 )
528
529 @property
530 def has_field(self):
531 return self.field is not None
532
533 @has_field.setter
534 def has_field(self, value):
535 utils._check_bool(value)
536 native_bt.field_option_set_has_field(self._ptr, value)
537
538 def _spec_eq(self, other):
539 return _get_leaf_field(self) == other
540
541 def __bool__(self):
542 return self.has_field
543
544 def __str__(self):
545 return str(self.field)
546
547 def _repr(self):
548 return repr(self.field)
549
550 def _set_value(self, value):
551 self.has_field = True
552 field = self.field
553 assert field is not None
554 field.value = value
555
556 value = property(fset=_set_value)
557
558
559 class _VariantField(_ContainerField, _Field):
560 _NAME = 'Variant'
561
562 @property
563 def selected_option_index(self):
564 return native_bt.field_variant_get_selected_option_field_index(self._ptr)
565
566 @selected_option_index.setter
567 def selected_option_index(self, index):
568 native_bt.field_variant_select_option_field_by_index(self._ptr, index)
569
570 @property
571 def selected_option(self):
572 # TODO: Is there a way to check if the variant field has a selected_option,
573 # so we can raise an exception instead of hitting a pre-condition check?
574 # If there is something, that check should be added to selected_option_index too.
575 field_ptr = native_bt.field_variant_borrow_selected_option_field(self._ptr)
576
577 return _create_field_from_ptr(
578 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
579 )
580
581 def _spec_eq(self, other):
582 return _get_leaf_field(self) == other
583
584 def __bool__(self):
585 raise NotImplementedError
586
587 def __str__(self):
588 return str(self.selected_option)
589
590 def _repr(self):
591 return repr(self.selected_option)
592
593 def _set_value(self, value):
594 self.selected_option.value = value
595
596 value = property(fset=_set_value)
597
598
599 class _ArrayField(_ContainerField, _Field, collections.abc.MutableSequence):
600 def _get_length(self):
601 return native_bt.field_array_get_length(self._ptr)
602
603 length = property(fget=_get_length)
604
605 def __getitem__(self, index):
606 if not isinstance(index, numbers.Integral):
607 raise TypeError(
608 "'{}' is not an integral number object: invalid index".format(
609 index.__class__.__name__
610 )
611 )
612
613 index = int(index)
614
615 if index < 0 or index >= len(self):
616 raise IndexError('{} field object index is out of range'.format(self._NAME))
617
618 field_ptr = native_bt.field_array_borrow_element_field_by_index(
619 self._ptr, index
620 )
621 assert field_ptr
622 return _create_field_from_ptr(
623 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
624 )
625
626 def __setitem__(self, index, value):
627 # raises if index is somehow invalid
628 field = self[index]
629
630 if not isinstance(field, (_NumericField, _StringField)):
631 raise TypeError('can only set the value of a number or string field')
632
633 # the field's property does the appropriate conversion or raises
634 # the appropriate exception
635 field.value = value
636
637 def insert(self, index, value):
638 raise NotImplementedError
639
640 def _spec_eq(self, other):
641 if not isinstance(other, collections.abc.Sequence):
642 return False
643
644 if len(self) != len(other):
645 # early mismatch
646 return False
647
648 for self_elem, other_elem in zip(self, other):
649 if self_elem != other_elem:
650 return False
651
652 return True
653
654 def _repr(self):
655 return '[{}]'.format(', '.join([repr(v) for v in self]))
656
657
658 class _StaticArrayField(_ArrayField, _Field):
659 _NAME = 'Static array'
660
661 def _count(self):
662 return native_bt.field_array_get_length(self._ptr)
663
664 def _set_value(self, values):
665 if len(self) != len(values):
666 raise ValueError('expected length of value and array field to match')
667
668 for index, value in enumerate(values):
669 if value is not None:
670 self[index].value = value
671
672 value = property(fset=_set_value)
673
674
675 class _DynamicArrayField(_ArrayField, _Field):
676 _NAME = 'Dynamic array'
677
678 def _count(self):
679 return self.length
680
681 def _set_length(self, length):
682 utils._check_uint64(length)
683 status = native_bt.field_array_dynamic_set_length(self._ptr, length)
684 utils._handle_func_status(status, "cannot set dynamic array length")
685
686 length = property(fget=_ArrayField._get_length, fset=_set_length)
687
688 def _set_value(self, values):
689 if len(values) != self.length:
690 self.length = len(values)
691
692 for index, value in enumerate(values):
693 if value is not None:
694 self[index].value = value
695
696 value = property(fset=_set_value)
697
698
699 _TYPE_ID_TO_OBJ = {
700 native_bt.FIELD_CLASS_TYPE_BOOL: _BoolField,
701 native_bt.FIELD_CLASS_TYPE_BIT_ARRAY: _BitArrayField,
702 native_bt.FIELD_CLASS_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerField,
703 native_bt.FIELD_CLASS_TYPE_SIGNED_INTEGER: _SignedIntegerField,
704 native_bt.FIELD_CLASS_TYPE_REAL: _RealField,
705 native_bt.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION: _UnsignedEnumerationField,
706 native_bt.FIELD_CLASS_TYPE_SIGNED_ENUMERATION: _SignedEnumerationField,
707 native_bt.FIELD_CLASS_TYPE_STRING: _StringField,
708 native_bt.FIELD_CLASS_TYPE_STRUCTURE: _StructureField,
709 native_bt.FIELD_CLASS_TYPE_STATIC_ARRAY: _StaticArrayField,
710 native_bt.FIELD_CLASS_TYPE_DYNAMIC_ARRAY: _DynamicArrayField,
711 native_bt.FIELD_CLASS_TYPE_OPTION: _OptionField,
712 native_bt.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR: _VariantField,
713 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR: _VariantField,
714 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR: _VariantField,
715 }
This page took 0.043857 seconds and 5 git commands to generate.