-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy path_ast.py
3088 lines (2501 loc) · 109 KB
/
_ast.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from abc import ABCMeta, abstractmethod
import warnings
import functools
import operator
import string
import re
from collections import OrderedDict
from collections.abc import Iterable, MutableMapping, MutableSet, MutableSequence
from enum import Enum, EnumMeta
from itertools import chain
from .. import tracer
from ..utils import *
from .._utils import *
from .._unused import *
__all__ = [
"Shape", "signed", "unsigned", "ShapeCastable", "ShapeLike",
"Value", "Const", "C", "AnyConst", "AnySeq", "Operator", "Mux", "Part", "Slice", "Cat", "Concat",
"Array", "ArrayProxy",
"Signal", "ClockSignal", "ResetSignal",
"ValueCastable", "ValueLike",
"Initial",
"Format",
"Statement", "Switch",
"Property", "Assign", "Print", "Assert", "Assume", "Cover",
"IOValue", "IOPort", "IOConcat", "IOSlice",
"SignalKey", "SignalDict", "SignalSet",
]
class DUID:
"""Deterministic Unique IDentifier."""
__next_uid = 0
def __init__(self):
self.duid = DUID.__next_uid
DUID.__next_uid += 1
class Shape:
"""Bit width and signedness of a :class:`Value`.
A :class:`Shape` can be obtained by:
* constructing with explicit bit width and signedness;
* using the :func:`signed` and :func:`unsigned` aliases if the signedness is known upfront;
* casting from a variety of objects using the :meth:`cast` method.
Parameters
----------
width : int
The number of bits in the representation of a value. This includes the sign bit for signed
values. Cannot be zero if the value is signed.
signed : bool
Whether the value is signed. Signed values use the
`two's complement <https://en.wikipedia.org/wiki/Two's_complement>`_ representation.
"""
def __init__(self, width=1, signed=False):
if not isinstance(width, int):
raise TypeError(f"Width must be an integer, not {width!r}")
if not signed and width < 0:
raise TypeError(f"Width of an unsigned value must be zero or a positive integer, "
f"not {width}")
if signed and width <= 0:
raise TypeError(f"Width of a signed value must be a positive integer, not {width}")
self._width = width
self._signed = bool(signed)
@property
def width(self):
return self._width
@property
def signed(self):
return self._signed
# The algorithm for inferring shape for standard Python enumerations is factored out so that
# `Shape.cast()` and Amaranth's `EnumMeta.as_shape()` can both use it.
@staticmethod
def _cast_plain_enum(obj):
signed = False
width = 0
for member in obj:
try:
member_shape = Const.cast(member.value).shape()
except TypeError as e:
raise TypeError("Only enumerations whose members have constant-castable "
"values can be used in Amaranth code")
if not signed and member_shape.signed:
signed = True
width = max(width + 1, member_shape.width)
elif signed and not member_shape.signed:
width = max(width, member_shape.width + 1)
else:
width = max(width, member_shape.width)
return Shape(width, signed)
@staticmethod
def cast(obj, *, src_loc_at=0):
"""Cast :py:`obj` to a shape.
Many :ref:`shape-like <lang-shapelike>` objects can be cast to a shape:
* a :class:`Shape`, where the result is itself;
* an :class:`int`, where the result is :func:`unsigned(obj) <unsigned>`;
* a :class:`range`, where the result has minimal width required to represent all elements
of the range, and is signed if any element of the range is signed;
* an :class:`enum.Enum` whose members are all :ref:`constant-castable <lang-constcasting>`
or :class:`enum.IntEnum`, where the result is wide enough to represent any member of
the enumeration, and is signed if any member of the enumeration is signed;
* a :class:`ShapeCastable` object, where the result is obtained by repeatedly calling
:meth:`obj.as_shape() <ShapeCastable.as_shape>`.
Raises
------
TypeError
If :py:`obj` cannot be converted to a :class:`Shape`.
RecursionError
If :py:`obj` is a :class:`ShapeCastable` object that casts to itself.
"""
while True:
if isinstance(obj, Shape):
return obj
elif isinstance(obj, ShapeCastable):
new_obj = obj.as_shape()
elif isinstance(obj, int):
return Shape(obj)
elif isinstance(obj, range):
if len(obj) == 0:
return Shape(0)
signed = obj[0] < 0 or obj[-1] < 0
width = max(bits_for(obj[0], signed),
bits_for(obj[-1], signed))
if obj[0] == obj[-1] == 0:
width = 0
return Shape(width, signed)
elif isinstance(obj, type) and issubclass(obj, Enum):
# For compatibility with third party enumerations, handle them as if they were
# defined as subclasses of lib.enum.Enum with no explicitly specified shape.
return Shape._cast_plain_enum(obj)
else:
raise TypeError(f"Object {obj!r} cannot be converted to an Amaranth shape")
if new_obj is obj:
raise RecursionError(f"Shape-castable object {obj!r} casts to itself")
obj = new_obj
def __repr__(self):
"""Python code that creates this shape.
Returns :py:`f"signed({self.width})"` or :py:`f"unsigned({self.width})"`.
"""
if self.signed:
return f"signed({self.width})"
else:
return f"unsigned({self.width})"
def __hash__(self):
return hash((self._width, self._signed))
def __eq__(self, other):
return (isinstance(other, Shape) and
self.width == other.width and self.signed == other.signed)
@staticmethod
def _unify(shapes):
"""Returns the minimal shape that contains all shapes from the list.
If no shapes passed in, returns unsigned(0).
"""
unsigned_width = signed_width = 0
has_signed = False
for shape in shapes:
assert isinstance(shape, Shape)
if shape.signed:
has_signed = True
signed_width = max(signed_width, shape.width)
else:
unsigned_width = max(unsigned_width, shape.width)
# If all shapes unsigned, simply take max.
if not has_signed:
return unsigned(unsigned_width)
# Otherwise, result is signed. All unsigned inputs, if any,
# need to be converted to signed by adding a zero bit.
return signed(max(signed_width, unsigned_width + 1))
def unsigned(width):
"""Returns :py:`Shape(width, signed=False)`."""
return Shape(width, signed=False)
def signed(width):
"""Returns :py:`Shape(width, signed=True)`."""
return Shape(width, signed=True)
class ShapeCastable:
"""Interface class for objects that can be cast to a :class:`Shape`.
Shapes of values in the Amaranth language are specified using :ref:`shape-like objects
<lang-shapelike>`. Inheriting a class from :class:`ShapeCastable` and implementing all of
the methods described below adds instances of that class to the list of shape-like objects
recognized by the :meth:`Shape.cast` method. This is a part of the mechanism for seamlessly
extending the Amaranth language in third-party code.
To illustrate their purpose, consider constructing a signal from a shape-castable object
:py:`shape_castable`:
.. code::
value_like = Signal(shape_castable, init=initializer)
The code above is equivalent to:
.. code::
value_like = shape_castable(Signal(
shape_castable.as_shape(),
init=shape_castable.const(initializer)
))
Note that the :py:`shape_castable(x)` syntax performs :py:`shape_castable.__call__(x)`.
.. tip::
The source code of the :mod:`amaranth.lib.data` module can be used as a reference for
implementing a fully featured shape-castable object.
"""
def __init__(self, *args, **kwargs):
if type(self) is ShapeCastable:
raise TypeError("Can't instantiate abstract class ShapeCastable")
super().__init__(*args, **kwargs)
def __init_subclass__(cls, **kwargs):
if cls.as_shape is ShapeCastable.as_shape:
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
f"the 'as_shape' method")
if cls.const is ShapeCastable.const:
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
f"the 'const' method")
if cls.__call__ is ShapeCastable.__call__:
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
f"the '__call__' method")
if cls.from_bits is ShapeCastable.from_bits:
warnings.warn(f"Class '{cls.__name__}' deriving from 'ShapeCastable' does not override "
f"the 'from_bits' method, which will be required in Amaranth 0.6",
DeprecationWarning, stacklevel=2)
# The signatures and definitions of these methods are weird because they are present here for
# documentation (and error checking above) purpose only and should not affect control flow.
# This especially applies to `__call__`, where subclasses may call `super().__call__()` in
# creative ways.
def as_shape(self, *args, **kwargs):
"""as_shape()
Convert :py:`self` to a :ref:`shape-like object <lang-shapelike>`.
This method is called by the Amaranth language to convert :py:`self` to a concrete
:class:`Shape`. It will usually return a :class:`Shape` object, but it may also return
another shape-like object to delegate its functionality.
This method must be idempotent: when called twice on the same object, the result must be
exactly the same.
This method may also be called by code that is not a part of the Amaranth language.
Returns
-------
Any other object recognized by :meth:`Shape.cast`.
Raises
------
Exception
When the conversion cannot be done. This exception must be propagated by callers
(except when checking whether an object is shape-castable or not), either directly
or as a cause of another exception.
"""
return super().as_shape(*args, **kwargs) # :nocov:
def const(self, *args, **kwargs):
"""const(obj)
Convert a constant initializer :py:`obj` to its value representation.
This method is called by the Amaranth language to convert :py:`obj`, which may be an
arbitrary Python object, to a concrete :ref:`value-like object <lang-valuelike>`.
The object :py:`obj` will usually be a Python literal that can conveniently represent
a constant value whose shape is described by :py:`self`. While not constrained here,
the result will usually be an instance of the return type of :meth:`__call__`.
For any :py:`obj`, the following condition must hold:
.. code::
Shape.cast(self) == Const.cast(self.const(obj)).shape()
This method may also be called by code that is not a part of the Amaranth language.
Returns
-------
A :ref:`value-like object <lang-valuelike>` that is :ref:`constant-castable <lang-constcasting>`.
Raises
------
Exception
When the conversion cannot be done. This exception must be propagated by callers,
either directly or as a cause of another exception. While not constrained here,
usually the exception class will be :exc:`TypeError` or :exc:`ValueError`.
"""
return super().const(*args, **kwargs) # :nocov:
def from_bits(self, raw):
"""Lift a bit pattern to a higher-level representation.
This method is called by the Amaranth language to lift :py:`raw`, which is an :class:`int`,
to a higher-level representation, which may be any object accepted by :meth:`const`.
Most importantly, the simulator calls this method when the value of a shape-castable
object is retrieved.
For any valid bit pattern :py:`raw`, the following condition must hold:
.. code::
Const.cast(self.const(self.from_bits(raw))).value == raw
While :meth:`const` will usually return an Amaranth value or a custom value-castable
object that is convenient to use while constructing the design, this method will usually
return a Python object that is convenient to use while simulating the design. While not
constrained here, these objects should have the same type whenever feasible.
This method may also be called by code that is not a part of the Amaranth language.
Returns
-------
unspecified type
Raises
------
Exception
When the bit pattern isn't valid. This exception must be propagated by callers,
either directly or as a cause of another exception. While not constrained here,
usually the exception class will be :exc:`ValueError`.
"""
return raw
def __call__(self, *args, **kwargs):
"""__call__(obj)
Lift a :ref:`value-like object <lang-valuelike>` to a higher-level representation.
This method is called by the Amaranth language to lift :py:`obj`, which may be any
:ref:`value-like object <lang-valuelike>` whose shape equals :py:`Shape.cast(self)`,
to a higher-level representation, which may be any value-like object with the same
shape. While not constrained here, usually a :class:`ShapeCastable` implementation will
be paired with a :class:`ValueCastable` implementation, and this method will return
an instance of the latter.
If :py:`obj` is not as described above, this interface does not constrain the behavior
of this method. This may be used to implement another call-based protocol at the same
time.
For any compliant :py:`obj`, the following condition must hold:
.. code::
Value.cast(self(obj)) == Value.cast(obj)
This method may also be called by code that is not a part of the Amaranth language.
Returns
-------
A :ref:`value-like object <lang-valuelike>`.
"""
return super().__call__(*args, **kwargs) # :nocov:
# TODO: write an RFC for turning this into a proper interface method
def _value_repr(self, value):
return (_repr.Repr(_repr.FormatInt(), value),)
class _ShapeLikeMeta(type):
def __subclasscheck__(cls, subclass):
return issubclass(subclass, (Shape, ShapeCastable, int, range, EnumMeta)) or subclass is ShapeLike
def __instancecheck__(cls, instance):
if isinstance(instance, (Shape, ShapeCastable, range)):
return True
if isinstance(instance, int):
return instance >= 0
if isinstance(instance, EnumMeta):
for member in instance:
if not isinstance(member.value, ValueLike):
return False
return True
return False
@final
class ShapeLike(metaclass=_ShapeLikeMeta):
"""Abstract class representing all objects that can be cast to a :class:`Shape`.
:py:`issubclass(cls, ShapeLike)` returns :py:`True` for:
* :class:`Shape`;
* :class:`ShapeCastable` and its subclasses;
* :class:`int` and its subclasses;
* :class:`range` and its subclasses;
* :class:`enum.EnumMeta` and its subclasses;
* :class:`ShapeLike` itself.
:py:`isinstance(obj, ShapeLike)` returns :py:`True` for:
* :class:`Shape` instances;
* :class:`ShapeCastable` instances;
* non-negative :class:`int` values;
* :class:`range` instances;
* :class:`enum.Enum` subclasses where all values are :ref:`value-like objects <lang-valuelike>`.
This class cannot be instantiated or subclassed. It can only be used for checking types of
objects.
"""
def __new__(cls, *args, **kwargs):
raise TypeError("ShapeLike is an abstract class and cannot be instantiated")
def _overridable_by_reflected(method_name):
"""Allow overriding the decorated method.
Allows :class:`ValueCastable` to override the decorated method by implementing
a reflected method named ``method_name``. Intended for operators, but
also usable for other methods that have a reflected counterpart.
"""
def decorator(f):
@functools.wraps(f)
def wrapper(self, other):
if isinstance(other, ValueCastable) and hasattr(other, method_name):
res = getattr(other, method_name)(self)
if res is not NotImplemented:
return res
return f(self, other)
return wrapper
return decorator
class Value(metaclass=ABCMeta):
"""Abstract representation of a bit pattern computed in a circuit.
The Amaranth language gives Python code the ability to create a circuit netlist by manipulating
objects representing the computations within that circuit. The :class:`Value` class represents
the bit pattern of a constant, or of a circuit input or output, or within a storage element; or
the result of an arithmetic, logical, or bit container operation.
Operations on this class interpret this bit pattern either as an integer, which can be signed
or unsigned depending on the value's :meth:`shape`, or as a bit container. In either case,
the semantics of operations that implement Python's syntax, like :py:`+` (also known as
:meth:`__add__`), are identical to the corresponding operation on a Python :class:`int` (or on
a Python sequence container). The bitwise inversion :py:`~` (also known as :meth:`__invert__`)
is the sole exception to this rule.
Data that is not conveniently representable by a single integer or a bit container can be
represented by wrapping a :class:`Value` in a :class:`ValueCastable` subclass that provides
domain-specific operations. It is possible to extend Amaranth in third-party code using
value-castable objects, and the Amaranth standard library provides several built-in ones:
* :mod:`amaranth.lib.enum` classes are a drop-in replacement for the standard Python
:mod:`enum` classes that can be defined with an Amaranth shape;
* :mod:`amaranth.lib.data` classes allow defining complex data structures such as structures
and unions.
Operations on :class:`Value` instances return another :class:`Value` instance. Unless the exact
type and value of the result is explicitly specified below, it should be considered opaque, and
may change without notice between Amaranth releases as long as the semantics remains the same.
.. note::
In each of the descriptions below, you will see a line similar to:
**Return type:** :class:`Value`, :py:`unsigned(1)`, :ref:`assignable <lang-assignable>`
The first part (:class:`Value`) indicates that the returned object's type is a subclass
of :class:`Value`. The second part (:py:`unsigned(1)`) describes the shape of that value.
The third part, if present, indicates that the value is assignable if :py:`self` is
assignable.
"""
@staticmethod
def cast(obj):
"""Cast :py:`obj` to an Amaranth value.
Many :ref:`value-like <lang-valuelike>` objects can be cast to a value:
* a :class:`Value` instance, where the result is itself;
* a :class:`bool` or :class:`int` instance, where the result is :py:`Const(obj)`;
* an :class:`enum.IntEnum` instance, or a :class:`enum.Enum` instance whose members are
all integers, where the result is a :class:`Const(obj, enum_shape)` where :py:`enum_shape`
is a shape that can represent every member of the enumeration;
* a :class:`ValueCastable` instance, where the result is obtained by repeatedly calling
:meth:`obj.as_value() <ValueCastable.as_value>`.
Raises
------
TypeError
If :py:`obj` cannot be converted to a :class:`Value`.
RecursionError
If :py:`obj` is a :class:`ValueCastable` object that casts to itself.
"""
while True:
if isinstance(obj, Value):
return obj
elif isinstance(obj, ValueCastable):
new_obj = obj.as_value()
elif isinstance(obj, Enum):
return Const(obj.value, Shape.cast(type(obj)))
elif isinstance(obj, int):
return Const(obj)
else:
raise TypeError(f"Object {obj!r} cannot be converted to an Amaranth value")
if new_obj is obj:
raise RecursionError(f"Value-castable object {obj!r} casts to itself")
obj = new_obj
def __init__(self, *, src_loc_at=0):
super().__init__()
self.src_loc = tracer.get_src_loc(1 + src_loc_at)
@abstractmethod
def shape(self):
"""Shape of :py:`self`.
Returns
-------
:ref:`shape-like object <lang-shapelike>`
"""
# TODO: while this is documented as returning a shape-like object, in practice we
# guarantee that this is a concrete Shape. it's unclear whether we will ever want to
# return a shape-catable object here, but there is not much harm in stating a relaxed
# contract, as it can always be tightened later, but not vice-versa
pass # :nocov:
def as_unsigned(self):
"""Reinterpretation as an unsigned value.
Returns
-------
:class:`Value`, :py:`unsigned(len(self))`, :ref:`assignable <lang-assignable>`
"""
return Operator("u", [self])
def as_signed(self):
"""Reinterpretation as a signed value.
Returns
-------
:class:`Value`, :py:`signed(len(self))`, :ref:`assignable <lang-assignable>`
Raises
------
ValueError
If :py:`len(self) == 0`.
"""
if len(self) == 0:
raise ValueError("Cannot create a 0-width signed value")
return Operator("s", [self])
def __bool__(self):
"""Forbidden conversion to boolean.
Python uses this operator for its built-in semantics, e.g. :py:`if`, and requires it to
return a :class:`bool`. Since this is not possible for Amaranth values, this operator
always raises an exception.
Raises
------
:exc:`TypeError`
Always.
"""
raise TypeError("Attempted to convert Amaranth value to Python boolean")
def bool(self):
"""Conversion to boolean.
Performs the same operation as :meth:`any`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("b", [self])
def __pos__(self):
"""Unary position, :py:`+self`.
Returns
-------
:class:`Value`, :py:`self.shape()`
:py:`self`
"""
return self
def __neg__(self):
"""Unary negation, :py:`-self`.
..
>>> C(-1).value, C(-1).shape()
-1, signed(1)
>>> C(-(-1), signed(1)).value # overflows
-1
Returns
-------
:class:`Value`, :py:`signed(len(self) + 1)`
"""
return Operator("-", [self])
@_overridable_by_reflected("__radd__")
def __add__(self, other):
"""Addition, :py:`self + other`.
Returns
-------
:class:`Value`, :py:`unsigned(max(self.width(), other.width()) + 1)`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(max(self.width() + 1, other.width()) + 1)`
If :py:`self` is unsigned and :py:`other` is signed.
:class:`Value`, :py:`signed(max(self.width(), other.width() + 1) + 1)`
If :py:`self` is signed and :py:`other` is unsigned.
:class:`Value`, :py:`signed(max(self.width(), other.width()) + 1)`
If both :py:`self` and :py:`other` are unsigned.
"""
return Operator("+", [self, other], src_loc_at=1)
def __radd__(self, other):
"""Addition, :py:`other + self` (reflected).
Like :meth:`__add__`, with operands swapped.
"""
return Operator("+", [other, self])
@_overridable_by_reflected("__rsub__")
def __sub__(self, other):
"""Subtraction, :py:`self - other`.
Returns
-------
:class:`Value`, :py:`signed(max(self.width(), other.width()) + 1)`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(max(self.width() + 1, other.width()) + 1)`
If :py:`self` is unsigned and :py:`other` is signed.
:class:`Value`, :py:`signed(max(self.width(), other.width() + 1) + 1)`
If :py:`self` is signed and :py:`other` is unsigned.
:class:`Value`, :py:`signed(max(self.width(), other.width()) + 1)`
If both :py:`self` and :py:`other` are unsigned.
Returns
-------
:class:`Value`
"""
return Operator("-", [self, other], src_loc_at=1)
def __rsub__(self, other):
"""Subtraction, :py:`other - self` (reflected).
Like :meth:`__sub__`, with operands swapped.
"""
return Operator("-", [other, self])
@_overridable_by_reflected("__rmul__")
def __mul__(self, other):
"""Multiplication, :py:`self * other`.
Returns
-------
:class:`Value`, :py:`unsigned(len(self) + len(other))`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(len(self) + len(other))`
If either :py:`self` or :py:`other` are signed.
"""
return Operator("*", [self, other], src_loc_at=1)
def __rmul__(self, other):
"""Multiplication, :py:`other * self` (reflected).
Like :meth:`__mul__`, with operands swapped.
"""
return Operator("*", [other, self])
@_overridable_by_reflected("__rfloordiv__")
def __floordiv__(self, other):
"""Flooring division, :py:`self // other`.
If :py:`other` is zero, the result of this operation is zero.
Returns
-------
:class:`Value`, :py:`unsigned(len(self))`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(len(self) + 1)`
If :py:`self` is unsigned and :py:`other` is signed.
:class:`Value`, :py:`signed(len(self))`
If :py:`self` is signed and :py:`other` is unsigned.
:class:`Value`, :py:`signed(len(self) + 1)`
If both :py:`self` and :py:`other` are signed.
"""
return Operator("//", [self, other], src_loc_at=1)
def __rfloordiv__(self, other):
"""Flooring division, :py:`other // self` (reflected).
If :py:`self` is zero, the result of this operation is zero.
Like :meth:`__floordiv__`, with operands swapped.
"""
return Operator("//", [other, self])
@_overridable_by_reflected("__rmod__")
def __mod__(self, other):
"""Flooring modulo or remainder, :py:`self % other`.
If :py:`other` is zero, the result of this operation is zero.
Returns
-------
:class:`Value`, :py:`other.shape()`
"""
return Operator("%", [self, other], src_loc_at=1)
def __rmod__(self, other):
"""Flooring modulo or remainder, :py:`other % self` (reflected).
Like :meth:`__mod__`, with operands swapped.
"""
return Operator("%", [other, self])
@_overridable_by_reflected("__eq__")
def __eq__(self, other):
"""Equality comparison, :py:`self == other`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("==", [self, other], src_loc_at=1)
@_overridable_by_reflected("__ne__")
def __ne__(self, other):
"""Inequality comparison, :py:`self != other`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("!=", [self, other], src_loc_at=1)
@_overridable_by_reflected("__gt__")
def __lt__(self, other):
"""Less than comparison, :py:`self < other`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("<", [self, other], src_loc_at=1)
@_overridable_by_reflected("__ge__")
def __le__(self, other):
"""Less than or equals comparison, :py:`self <= other`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("<=", [self, other], src_loc_at=1)
@_overridable_by_reflected("__lt__")
def __gt__(self, other):
"""Greater than comparison, :py:`self > other`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator(">", [self, other], src_loc_at=1)
@_overridable_by_reflected("__le__")
def __ge__(self, other):
"""Greater than or equals comparison, :py:`self >= other`.
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator(">=", [self, other], src_loc_at=1)
def __abs__(self):
"""Absolute value, :py:`abs(self)`.
..
>>> abs(C(-1)).shape()
unsigned(1)
>>> C(1).shape()
unsigned(1)
Return
------
:class:`Value`, :py:`unsigned(len(self))`
"""
if self.shape().signed:
return Mux(self >= 0, self, -self)[:len(self)]
else:
return self
def __invert__(self):
"""Bitwise NOT, :py:`~self`.
The shape of the result is the same as the shape of :py:`self`, even for unsigned values.
.. important::
In Python, :py:`~0` equals :py:`-1`. In Amaranth, :py:`~C(0)` equals :py:`C(1)`.
This is the only case where an Amaranth operator deviates from the Python operator
with the same name.
This deviation is necessary because Python does not allow overriding the logical
:py:`and`, :py:`or`, and :py:`not` operators. Amaranth uses :py:`&`, :py:`|`, and
:py:`~` instead; if it wasn't the case that :py:`~C(0) == C(1)`, that would have
been impossible.
Returns
-------
:class:`Value`, :py:`self.shape()`
"""
return Operator("~", [self])
@_overridable_by_reflected("__rand__")
def __and__(self, other):
"""Bitwise AND, :py:`self & other`.
Returns
-------
:class:`Value`, :py:`unsigned(max(self.width(), other.width()))`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(max(self.width() + 1, other.width()))`
If :py:`self` is unsigned and :py:`other` is signed.
:class:`Value`, :py:`signed(max(self.width(), other.width() + 1))`
If :py:`self` is signed and :py:`other` is unsigned.
:class:`Value`, :py:`signed(max(self.width(), other.width()))`
If both :py:`self` and :py:`other` are unsigned.
"""
return Operator("&", [self, other], src_loc_at=1)
def __rand__(self, other):
"""Bitwise AND, :py:`other & self`.
Like :meth:`__and__`, with operands swapped.
"""
return Operator("&", [other, self])
def all(self):
"""Reduction AND; are all bits :py:`1`?
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("r&", [self])
@_overridable_by_reflected("__ror__")
def __or__(self, other):
"""Bitwise OR, :py:`self | other`.
Returns
-------
:class:`Value`, :py:`unsigned(max(self.width(), other.width()))`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(max(self.width() + 1, other.width()))`
If :py:`self` is unsigned and :py:`other` is signed.
:class:`Value`, :py:`signed(max(self.width(), other.width() + 1))`
If :py:`self` is signed and :py:`other` is unsigned.
:class:`Value`, :py:`signed(max(self.width(), other.width()))`
If both :py:`self` and :py:`other` are unsigned.
"""
return Operator("|", [self, other], src_loc_at=1)
def __ror__(self, other):
"""Bitwise OR, :py:`other | self`.
Like :meth:`__or__`, with operands swapped.
"""
return Operator("|", [other, self])
def any(self):
"""Reduction OR; is any bit :py:`1`?
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("r|", [self])
@_overridable_by_reflected("__rxor__")
def __xor__(self, other):
"""Bitwise XOR, :py:`self ^ other`.
Returns
-------
:class:`Value`, :py:`unsigned(max(self.width(), other.width()))`
If both :py:`self` and :py:`other` are unsigned.
:class:`Value`, :py:`signed(max(self.width() + 1, other.width()))`
If :py:`self` is unsigned and :py:`other` is signed.
:class:`Value`, :py:`signed(max(self.width(), other.width() + 1))`
If :py:`self` is signed and :py:`other` is unsigned.
:class:`Value`, :py:`signed(max(self.width(), other.width()))`
If both :py:`self` and :py:`other` are unsigned.
"""
return Operator("^", [self, other], src_loc_at=1)
def __rxor__(self, other):
"""Bitwise XOR, :py:`other ^ self`.
Like :meth:`__xor__`, with operands swapped.
"""
return Operator("^", [other, self])
def xor(self):
"""Reduction XOR; are an odd amount of bits :py:`1`?
Returns
-------
:class:`Value`, :py:`unsigned(1)`
"""
return Operator("r^", [self])
def implies(self, conclusion):
# TODO: should we document or just deprecate this?
return ~self | conclusion
def __check_shamt(self):
if self.shape().signed:
# Neither Python nor HDLs implement shifts by negative values; prohibit any shifts
# by a signed value to make sure the shift amount can always be interpreted as
# an unsigned value.
raise TypeError("Shift amount must be unsigned")
@_overridable_by_reflected("__rlshift__")
def __lshift__(self, other):
"""Left shift by variable amount, :py:`self << other`.
Returns
-------
:class:`Value`, :py:`unsigned(len(self) + 2 ** len(other) - 1)`
If :py:`self` is unsigned.
:class:`Value`, :py:`signed(len(self) + 2 ** len(other) - 1)`
If :py:`self` is signed.
Raises
------
:exc:`TypeError`
If :py:`other` is signed.
"""
other = Value.cast(other)
other.__check_shamt()
return Operator("<<", [self, other], src_loc_at=1)
def __rlshift__(self, other):
"""Left shift by variable amount, :py:`other << self`.
Like :meth:`__lshift__`, with operands swapped.
"""
self.__check_shamt()
return Operator("<<", [other, self])
def shift_left(self, amount):
"""Left shift by constant amount.
If :py:`amount < 0`, performs the same operation as :py:`self.shift_right(-amount)`.
Returns
-------
:class:`Value`, :py:`unsigned(max(len(self) + amount, 0))`
If :py:`self` is unsigned.
:class:`Value`, :py:`signed(max(len(self) + amount, 1))`
If :py:`self` is signed.
"""
if not isinstance(amount, int):
raise TypeError(f"Shift amount must be an integer, not {amount!r}")
if amount < 0:
return self.shift_right(-amount)
if self.shape().signed:
return Cat(Const(0, amount), self).as_signed()
else:
return Cat(Const(0, amount), self) # unsigned
def rotate_left(self, amount):
"""Left rotate by constant amount.
If :py:`amount < 0`, performs the same operation as :py:`self.rotate_right(-amount)`.