Skip to main content

hir_lang/
ops.rs

1//! Intrinsic operations (`specs/OPS.md`) and their per-instance policies.
2//!
3//! An [`Op`] names one OPS operation and carries exactly the policy fields that
4//! operation consults. The policy is fixed when the op is lowered, so every tier
5//! (T0 evaluator, VM, JIT, AOT) sees the same choice and produces the same result
6//! or the same error.
7
8use crate::lit::Prim;
9
10/// What happens on integer overflow (`add sub mul neg abs`, `div MIN / -1`,
11/// `int_cast`); `specs/OPS.md` section 2.
12///
13/// # Examples
14///
15/// ```
16/// use hir_lang::Overflow;
17///
18/// assert_ne!(Overflow::Error, Overflow::Wrap);
19/// ```
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum Overflow {
22    /// A runtime error with kind `ArithOverflow` (OPS default).
23    Error,
24    /// Two's-complement wrap-around; never an error.
25    Wrap,
26    /// A deterministic abort with the same kind code.
27    Trap,
28    /// The result is the `f64` nearest to the exact mathematical result
29    /// (PHP's `PHP_INT_MAX + 1`). Valid only where the result is dynamically
30    /// typed: the validator rejects it where HIR fixes a static result type
31    /// (`int_cast`, a cast to anything but `Any`, an integer constant context),
32    /// and typeck-lang rejects it where it infers one.
33    Promote,
34}
35
36/// What happens on integer division or remainder by zero.
37///
38/// # Examples
39///
40/// ```
41/// use hir_lang::DivZero;
42///
43/// assert_ne!(DivZero::Error, DivZero::Trap);
44/// ```
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
46pub enum DivZero {
47    /// A runtime error with kind `DivByZero` (OPS default).
48    Error,
49    /// A deterministic abort.
50    Trap,
51}
52
53/// What happens when a shift amount is at least the bit width, or negative.
54///
55/// # Examples
56///
57/// ```
58/// use hir_lang::Shift;
59///
60/// assert_ne!(Shift::Error, Shift::Mask);
61/// assert_ne!(Shift::Mask, Shift::Saturate);
62/// ```
63#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
64pub enum Shift {
65    /// A runtime error with kind `ShiftOutOfRange` (OPS default).
66    Error,
67    /// Use the amount modulo the bit width.
68    Mask,
69    /// PHP semantics (OPS v2): an amount at or above the width gives `0`
70    /// (`shr` of a negative signed value gives `-1`); a negative amount is
71    /// still `ShiftOutOfRange`.
72    Saturate,
73}
74
75/// What happens when a float-to-int conversion meets NaN or an out-of-range value.
76///
77/// # Examples
78///
79/// ```
80/// use hir_lang::FloatToInt;
81///
82/// assert_ne!(FloatToInt::Error, FloatToInt::Saturate);
83/// ```
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
85pub enum FloatToInt {
86    /// A runtime error with kind `InvalidConversion` (OPS default).
87    Error,
88    /// Clamp to the target's range; NaN becomes `0`.
89    Saturate,
90}
91
92/// The policy fields of one op instance.
93///
94/// A field is `Some` exactly when the op consults it: the validator rejects a
95/// missing field (a tier would have to guess) and an extra one (a sign of a
96/// lowering bug).
97///
98/// # Examples
99///
100/// ```
101/// use hir_lang::{Overflow, Policy};
102///
103/// let policy = Policy::NONE.with_overflow(Overflow::Wrap);
104/// assert_eq!(policy.overflow, Some(Overflow::Wrap));
105/// assert_eq!(policy.div_zero, None);
106/// ```
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
108pub struct Policy {
109    /// The overflow policy.
110    pub overflow: Option<Overflow>,
111    /// The division-by-zero policy.
112    pub div_zero: Option<DivZero>,
113    /// The shift-amount policy.
114    pub shift: Option<Shift>,
115    /// The float-to-int conversion policy.
116    pub float_to_int: Option<FloatToInt>,
117}
118
119impl Policy {
120    /// No policy fields: for ops that consult none.
121    pub const NONE: Self = Self {
122        overflow: None,
123        div_zero: None,
124        shift: None,
125        float_to_int: None,
126    };
127
128    /// The policy a [`Cast`](crate::Expr::Cast) carries: `overflow` and
129    /// `float_to_int`, at the OPS defaults (`error`).
130    ///
131    /// # Examples
132    ///
133    /// ```
134    /// use hir_lang::{FloatToInt, Overflow, Policy};
135    ///
136    /// let p = Policy::CAST;
137    /// assert_eq!((p.overflow, p.float_to_int), (Some(Overflow::Error), Some(FloatToInt::Error)));
138    /// ```
139    pub const CAST: Self = Self {
140        overflow: Some(Overflow::Error),
141        div_zero: None,
142        shift: None,
143        float_to_int: Some(FloatToInt::Error),
144    };
145
146    /// Returns the policy with `overflow` set.
147    ///
148    /// # Examples
149    ///
150    /// ```
151    /// use hir_lang::{Overflow, Policy};
152    ///
153    /// assert_eq!(Policy::NONE.with_overflow(Overflow::Trap).overflow, Some(Overflow::Trap));
154    /// ```
155    #[must_use]
156    pub const fn with_overflow(mut self, overflow: Overflow) -> Self {
157        self.overflow = Some(overflow);
158        self
159    }
160
161    /// Returns the policy with `div_zero` set.
162    ///
163    /// # Examples
164    ///
165    /// ```
166    /// use hir_lang::{DivZero, Policy};
167    ///
168    /// assert_eq!(Policy::NONE.with_div_zero(DivZero::Trap).div_zero, Some(DivZero::Trap));
169    /// ```
170    #[must_use]
171    pub const fn with_div_zero(mut self, div_zero: DivZero) -> Self {
172        self.div_zero = Some(div_zero);
173        self
174    }
175
176    /// Returns the policy with `shift` set.
177    ///
178    /// # Examples
179    ///
180    /// ```
181    /// use hir_lang::{Policy, Shift};
182    ///
183    /// assert_eq!(Policy::NONE.with_shift(Shift::Mask).shift, Some(Shift::Mask));
184    /// ```
185    #[must_use]
186    pub const fn with_shift(mut self, shift: Shift) -> Self {
187        self.shift = Some(shift);
188        self
189    }
190
191    /// Returns the policy with `float_to_int` set.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use hir_lang::{FloatToInt, Policy};
197    ///
198    /// let p = Policy::NONE.with_float_to_int(FloatToInt::Saturate);
199    /// assert_eq!(p.float_to_int, Some(FloatToInt::Saturate));
200    /// ```
201    #[must_use]
202    pub const fn with_float_to_int(mut self, float_to_int: FloatToInt) -> Self {
203        self.float_to_int = Some(float_to_int);
204        self
205    }
206
207    /// Returns `true` if the same fields are set in both policies (values aside).
208    pub(crate) const fn same_fields(self, other: Self) -> bool {
209        self.overflow.is_some() == other.overflow.is_some()
210            && self.div_zero.is_some() == other.div_zero.is_some()
211            && self.shift.is_some() == other.shift.is_some()
212            && self.float_to_int.is_some() == other.float_to_int.is_some()
213    }
214}
215
216/// An operation from `specs/OPS.md`. Conversions carry their target type.
217///
218/// Operand types are not part of the op: the same `add` is an integer add under
219/// its overflow policy when typeck finds integer operands, an IEEE add for
220/// floats, and an operator-overloading site for user types.
221///
222/// # Examples
223///
224/// ```
225/// use hir_lang::{OpKind, Prim};
226///
227/// assert_eq!(OpKind::FloorDiv.name(), "floor_div");
228/// assert_eq!(OpKind::Fma.arity(), 3);
229/// assert_eq!(OpKind::IntCast(Prim::U8).name(), "int_cast");
230/// ```
231#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
232pub enum OpKind {
233    /// `add` (2).
234    Add,
235    /// `sub` (2).
236    Sub,
237    /// `mul` (2).
238    Mul,
239    /// `neg` (1).
240    Neg,
241    /// `abs` (1).
242    Abs,
243    /// `div`: truncating division (2).
244    Div,
245    /// `floor_div`: flooring division (2).
246    FloorDiv,
247    /// `rem`: remainder with the dividend's sign (2).
248    Rem,
249    /// `floor_mod`: remainder with the divisor's sign (2).
250    FloorMod,
251    /// `and` (2).
252    And,
253    /// `or` (2).
254    Or,
255    /// `xor` (2).
256    Xor,
257    /// `not`: logical negation (1). On dynamic values, negation of the
258    /// value's truthiness (LSB `dlnot`); the bitwise complement is
259    /// [`OpKind::BitNot`].
260    Not,
261    /// `bit_not`: bitwise complement of an integer (1; LSB `dnot` on dynamic
262    /// values).
263    BitNot,
264    /// `shl` (2).
265    Shl,
266    /// `shr`: arithmetic for signed, logical for unsigned (2).
267    Shr,
268    /// `pow`: exponentiation (2; OPS v2). Integer `pow` consults `overflow`
269    /// (and raises `NegativeExponent` for a negative exponent unless the
270    /// policy is `promote`); float `pow` ignores the policy.
271    Pow,
272    /// `eq` (2).
273    Eq,
274    /// `ne` (2).
275    Ne,
276    /// `lt` (2).
277    Lt,
278    /// `le` (2).
279    Le,
280    /// `gt` (2).
281    Gt,
282    /// `ge` (2).
283    Ge,
284    /// `min` (2).
285    Min,
286    /// `max` (2).
287    Max,
288    /// `ieee_rem`: IEEE 754 remainder (2).
289    IeeeRem,
290    /// `sqrt` (1).
291    Sqrt,
292    /// `fma`: fused multiply-add (3).
293    Fma,
294    /// `floor` (1).
295    Floor,
296    /// `ceil` (1).
297    Ceil,
298    /// `trunc`: float truncation toward zero (1).
299    Trunc,
300    /// `round`: ties away from zero (1).
301    Round,
302    /// `round_even`: ties to even (1).
303    RoundEven,
304    /// `total_cmp`: IEEE totalOrder, yielding `i8` (2).
305    TotalCmp,
306    /// `int_cast<T>`: exact integer conversion (1).
307    IntCast(Prim),
308    /// `float_to_int<T>` (1).
309    FloatToInt(Prim),
310    /// `zext<T>`: zero extension (1).
311    Zext(Prim),
312    /// `sext<T>`: sign extension (1).
313    Sext(Prim),
314    /// `narrow<T>`: OPS's integer `trunc` conversion, renamed so it cannot be
315    /// confused with the float [`OpKind::Trunc`] (1).
316    Narrow(Prim),
317    /// `int_to_float<T>` (1).
318    IntToFloat(Prim),
319    /// `bitcast<T>`: same-width reinterpretation (1).
320    Bitcast(Prim),
321    /// `bool_to_int<T>` (1).
322    BoolToInt(Prim),
323    /// `f32_to_f64` (1).
324    F32ToF64,
325    /// `f64_to_f32` (1).
326    F64ToF32,
327    /// `char_from_u32` (1).
328    CharFromU32,
329}
330
331impl OpKind {
332    /// Returns the operation's name as spelled in `specs/OPS.md` (`narrow` for
333    /// the integer truncation conversion). Conversion targets are not included.
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// use hir_lang::{OpKind, Prim};
339    ///
340    /// assert_eq!(OpKind::RoundEven.name(), "round_even");
341    /// assert_eq!(OpKind::Narrow(Prim::U8).name(), "narrow");
342    /// ```
343    #[must_use]
344    pub const fn name(self) -> &'static str {
345        match self {
346            Self::Add => "add",
347            Self::Sub => "sub",
348            Self::Mul => "mul",
349            Self::Neg => "neg",
350            Self::Abs => "abs",
351            Self::Div => "div",
352            Self::FloorDiv => "floor_div",
353            Self::Rem => "rem",
354            Self::FloorMod => "floor_mod",
355            Self::And => "and",
356            Self::Or => "or",
357            Self::Xor => "xor",
358            Self::Not => "not",
359            Self::BitNot => "bit_not",
360            Self::Shl => "shl",
361            Self::Shr => "shr",
362            Self::Pow => "pow",
363            Self::Eq => "eq",
364            Self::Ne => "ne",
365            Self::Lt => "lt",
366            Self::Le => "le",
367            Self::Gt => "gt",
368            Self::Ge => "ge",
369            Self::Min => "min",
370            Self::Max => "max",
371            Self::IeeeRem => "ieee_rem",
372            Self::Sqrt => "sqrt",
373            Self::Fma => "fma",
374            Self::Floor => "floor",
375            Self::Ceil => "ceil",
376            Self::Trunc => "trunc",
377            Self::Round => "round",
378            Self::RoundEven => "round_even",
379            Self::TotalCmp => "total_cmp",
380            Self::IntCast(_) => "int_cast",
381            Self::FloatToInt(_) => "float_to_int",
382            Self::Zext(_) => "zext",
383            Self::Sext(_) => "sext",
384            Self::Narrow(_) => "narrow",
385            Self::IntToFloat(_) => "int_to_float",
386            Self::Bitcast(_) => "bitcast",
387            Self::BoolToInt(_) => "bool_to_int",
388            Self::F32ToF64 => "f32_to_f64",
389            Self::F64ToF32 => "f64_to_f32",
390            Self::CharFromU32 => "char_from_u32",
391        }
392    }
393
394    /// Returns the conversion target type, for the conversions that have one.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// use hir_lang::{OpKind, Prim};
400    ///
401    /// assert_eq!(OpKind::Zext(Prim::U64).target(), Some(Prim::U64));
402    /// assert_eq!(OpKind::Add.target(), None);
403    /// ```
404    #[must_use]
405    pub const fn target(self) -> Option<Prim> {
406        match self {
407            Self::IntCast(t)
408            | Self::FloatToInt(t)
409            | Self::Zext(t)
410            | Self::Sext(t)
411            | Self::Narrow(t)
412            | Self::IntToFloat(t)
413            | Self::Bitcast(t)
414            | Self::BoolToInt(t) => Some(t),
415            _ => None,
416        }
417    }
418
419    /// Returns the number of operands.
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// use hir_lang::OpKind;
425    ///
426    /// assert_eq!(OpKind::Neg.arity(), 1);
427    /// assert_eq!(OpKind::Shl.arity(), 2);
428    /// ```
429    #[must_use]
430    pub const fn arity(self) -> usize {
431        match self {
432            Self::Neg
433            | Self::Abs
434            | Self::Not
435            | Self::BitNot
436            | Self::Sqrt
437            | Self::Floor
438            | Self::Ceil
439            | Self::Trunc
440            | Self::Round
441            | Self::RoundEven
442            | Self::IntCast(_)
443            | Self::FloatToInt(_)
444            | Self::Zext(_)
445            | Self::Sext(_)
446            | Self::Narrow(_)
447            | Self::IntToFloat(_)
448            | Self::Bitcast(_)
449            | Self::BoolToInt(_)
450            | Self::F32ToF64
451            | Self::F64ToF32
452            | Self::CharFromU32 => 1,
453            Self::Fma => 3,
454            _ => 2,
455        }
456    }
457
458    /// Returns the policy this op uses at the OPS defaults: exactly the fields
459    /// it consults, each set to `error`.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// use hir_lang::{DivZero, OpKind, Overflow};
465    ///
466    /// let p = OpKind::Div.default_policy();
467    /// assert_eq!((p.overflow, p.div_zero), (Some(Overflow::Error), Some(DivZero::Error)));
468    /// assert_eq!(OpKind::Eq.default_policy(), hir_lang::Policy::NONE);
469    /// ```
470    #[must_use]
471    pub const fn default_policy(self) -> Policy {
472        match self {
473            Self::Add
474            | Self::Sub
475            | Self::Mul
476            | Self::Neg
477            | Self::Abs
478            | Self::Pow
479            | Self::IntCast(_) => Policy::NONE.with_overflow(Overflow::Error),
480            Self::Div | Self::FloorDiv => Policy::NONE
481                .with_overflow(Overflow::Error)
482                .with_div_zero(DivZero::Error),
483            Self::Rem | Self::FloorMod => Policy::NONE.with_div_zero(DivZero::Error),
484            Self::Shl | Self::Shr => Policy::NONE.with_shift(Shift::Error),
485            Self::FloatToInt(_) => Policy::NONE.with_float_to_int(FloatToInt::Error),
486            _ => Policy::NONE,
487        }
488    }
489
490    /// Returns `true` if the conversion target (if any) has the right class:
491    /// integer for the integer conversions, float for `int_to_float`, numeric
492    /// for `bitcast`.
493    pub(crate) const fn target_ok(self) -> bool {
494        match self {
495            Self::IntCast(t)
496            | Self::FloatToInt(t)
497            | Self::Zext(t)
498            | Self::Sext(t)
499            | Self::Narrow(t)
500            | Self::BoolToInt(t) => t.is_int(),
501            Self::IntToFloat(t) => t.is_float(),
502            Self::Bitcast(t) => t.is_int() || t.is_float(),
503            _ => true,
504        }
505    }
506}
507
508/// One op instance: the operation and its policy.
509///
510/// # Examples
511///
512/// ```
513/// use hir_lang::{Op, OpKind, Overflow};
514///
515/// let wrapping_add = Op::new(OpKind::Add).with_overflow(Overflow::Wrap);
516/// assert_eq!(wrapping_add.policy.overflow, Some(Overflow::Wrap));
517/// assert!(wrapping_add.policy_matches());
518/// ```
519#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
520pub struct Op {
521    /// The operation.
522    pub kind: OpKind,
523    /// Its policy; exactly the fields `kind` consults are set.
524    pub policy: Policy,
525}
526
527impl Op {
528    /// The op at the OPS default policy.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// use hir_lang::{Op, OpKind};
534    ///
535    /// assert!(Op::new(OpKind::Shr).policy.shift.is_some());
536    /// ```
537    #[must_use]
538    pub const fn new(kind: OpKind) -> Self {
539        Self {
540            kind,
541            policy: kind.default_policy(),
542        }
543    }
544
545    /// Sets the overflow policy (meaningful only for ops that consult it; the
546    /// validator rejects it on others).
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// use hir_lang::{Op, OpKind, Overflow};
552    ///
553    /// assert!(Op::new(OpKind::Mul).with_overflow(Overflow::Trap).policy_matches());
554    /// assert!(!Op::new(OpKind::Eq).with_overflow(Overflow::Trap).policy_matches());
555    /// ```
556    #[must_use]
557    pub const fn with_overflow(mut self, overflow: Overflow) -> Self {
558        self.policy = self.policy.with_overflow(overflow);
559        self
560    }
561
562    /// Sets the division-by-zero policy.
563    ///
564    /// # Examples
565    ///
566    /// ```
567    /// use hir_lang::{DivZero, Op, OpKind};
568    ///
569    /// assert!(Op::new(OpKind::Rem).with_div_zero(DivZero::Trap).policy_matches());
570    /// ```
571    #[must_use]
572    pub const fn with_div_zero(mut self, div_zero: DivZero) -> Self {
573        self.policy = self.policy.with_div_zero(div_zero);
574        self
575    }
576
577    /// Sets the shift policy.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use hir_lang::{Op, OpKind, Shift};
583    ///
584    /// assert!(Op::new(OpKind::Shl).with_shift(Shift::Mask).policy_matches());
585    /// ```
586    #[must_use]
587    pub const fn with_shift(mut self, shift: Shift) -> Self {
588        self.policy = self.policy.with_shift(shift);
589        self
590    }
591
592    /// Sets the float-to-int policy.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// use hir_lang::{FloatToInt, Op, OpKind, Prim};
598    ///
599    /// let op = Op::new(OpKind::FloatToInt(Prim::I32)).with_float_to_int(FloatToInt::Saturate);
600    /// assert!(op.policy_matches());
601    /// ```
602    #[must_use]
603    pub const fn with_float_to_int(mut self, float_to_int: FloatToInt) -> Self {
604        self.policy = self.policy.with_float_to_int(float_to_int);
605        self
606    }
607
608    /// Returns `true` if the policy sets exactly the fields the op consults.
609    ///
610    /// # Examples
611    ///
612    /// ```
613    /// use hir_lang::{Op, OpKind, Policy};
614    ///
615    /// let missing = Op { kind: OpKind::Add, policy: Policy::NONE };
616    /// assert!(!missing.policy_matches());
617    /// ```
618    #[must_use]
619    pub const fn policy_matches(self) -> bool {
620        self.policy.same_fields(self.kind.default_policy())
621    }
622
623    /// Returns `true` if the op uses the `promote` overflow policy, so its
624    /// result may be an `f64` and must be dynamically typed.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// use hir_lang::{Op, OpKind, Overflow};
630    ///
631    /// assert!(Op::new(OpKind::Add).with_overflow(Overflow::Promote).promotes());
632    /// assert!(!Op::new(OpKind::Add).promotes());
633    /// ```
634    #[must_use]
635    pub const fn promotes(self) -> bool {
636        matches!(self.policy.overflow, Some(Overflow::Promote))
637    }
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643
644    #[test]
645    fn test_default_policy_matches_ops_families() {
646        assert_eq!(OpKind::Add.default_policy().overflow, Some(Overflow::Error));
647        assert_eq!(OpKind::Rem.default_policy().overflow, None);
648        assert_eq!(
649            OpKind::FloorMod.default_policy().div_zero,
650            Some(DivZero::Error)
651        );
652        assert_eq!(OpKind::Sqrt.default_policy(), Policy::NONE);
653        assert_eq!(
654            OpKind::IntCast(Prim::I8).default_policy().overflow,
655            Some(Overflow::Error)
656        );
657        assert_eq!(OpKind::Zext(Prim::I8).default_policy(), Policy::NONE);
658    }
659
660    #[test]
661    fn test_target_classes() {
662        assert!(OpKind::IntCast(Prim::U16).target_ok());
663        assert!(!OpKind::IntCast(Prim::F64).target_ok());
664        assert!(OpKind::IntToFloat(Prim::F32).target_ok());
665        assert!(!OpKind::IntToFloat(Prim::I32).target_ok());
666        assert!(!OpKind::Bitcast(Prim::Char).target_ok());
667        assert!(OpKind::Add.target_ok());
668    }
669}