midenc_hir/attributes/
overflow.rs

1use core::fmt;
2
3use crate::define_attr_type;
4
5/// This enumeration represents the various ways in which arithmetic operations
6/// can be configured to behave when either the operands or results over/underflow
7/// the range of the integral type.
8///
9/// Always check the documentation of the specific instruction involved to see if there
10/// are any specific differences in how this enum is interpreted compared to the default
11/// meaning of each variant.
12#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
13pub enum Overflow {
14    /// Typically, this means the operation is performed using the equivalent field element
15    /// operation, rather than a dedicated operation for the given type. Because of this, the
16    /// result of the operation may exceed that of the integral type expected, but this will
17    /// not be caught right away.
18    ///
19    /// It is the callers responsibility to ensure that resulting value is in range.
20    #[default]
21    Unchecked,
22    /// The operation will trap if the operands, or the result, is not valid for the range of the
23    /// integral type involved, e.g. u32.
24    Checked,
25    /// The operation will wrap around, depending on the range of the integral type. For example,
26    /// given a u32 value, this is done by applying `mod 2^32` to the result.
27    Wrapping,
28    /// The result of the operation will be computed as in [Wrapping], however in addition to the
29    /// result, this variant also pushes a value on the stack which represents whether or not the
30    /// operation over/underflowed; either 1 if over/underflow occurred, or 0 otherwise.
31    Overflowing,
32}
33impl Overflow {
34    /// Returns true if overflow is unchecked
35    pub fn is_unchecked(&self) -> bool {
36        matches!(self, Self::Unchecked)
37    }
38
39    /// Returns true if overflow will cause a trap
40    pub fn is_checked(&self) -> bool {
41        matches!(self, Self::Checked)
42    }
43
44    /// Returns true if overflow will add an extra boolean on top of the stack
45    pub fn is_overflowing(&self) -> bool {
46        matches!(self, Self::Overflowing)
47    }
48}
49impl fmt::Display for Overflow {
50    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51        match self {
52            Self::Unchecked => f.write_str("unchecked"),
53            Self::Checked => f.write_str("checked"),
54            Self::Wrapping => f.write_str("wrapping"),
55            Self::Overflowing => f.write_str("overflow"),
56        }
57    }
58}
59impl crate::formatter::PrettyPrint for Overflow {
60    fn render(&self) -> crate::formatter::Document {
61        use crate::formatter::*;
62        display(self)
63    }
64}
65
66define_attr_type!(Overflow);