dive-value 0.1.0

TLA+ values with TLC's canonical ordering, printing and fingerprints
Documentation
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
//! TLA+ integers in both modes: TLC's 32-bit semantics and arbitrary precision.
//!
//! Port of the integer semantics of `tlc2.module.Naturals` and `tlc2.module.Integers`
//! (tlaplus `94d0c50`): which operations overflow, the overflow messages, floored
//! `\div`, non-negative `%`, and the rejection of literals above `2^31 - 1`
//! (`tlc2.tool.impl.SpecProcessor`, `NumeralKind`). [`Int::div`] is
//! `Integers.Divide`; [`Int::div_naturals`] is `Naturals.Divide`, which TLC uses for
//! a specification that loads `Naturals` but not `Integers` (fixture `RvNatDiv`).
//! An earlier note here said TLC always uses `Integers.Divide`: that was measured
//! with `-dumpTrace json`, which itself loads `Integers` (issue #35).

use std::cmp::Ordering;
use std::fmt;
use std::sync::Arc;

use num_bigint::BigInt;
use num_integer::Integer as _;
use num_traits::{One, Signed, ToPrimitive};

use crate::ctx::IntMode;
use crate::error::{ErrorKind, Result, ValueError};

/// An integer: inline when it fits in an `i64`, otherwise a shared big integer.
///
/// Constructors keep the representation canonical (`Big` only outside `i64` range);
/// equality, ordering and hashing are numeric even for a hand-built non-canonical `Big`.
#[derive(Clone)]
pub enum Int {
    /// A value in `i64` range.
    Small(i64),
    /// A value outside `i64` range.
    Big(Arc<BigInt>),
}

/// The largest exponent bit-size dive will compute in big mode: results above
/// 2^26 bits (8 MiB) are refused with [`ErrorKind::DiveLimit`].
const MAX_POW_BITS: u64 = 1 << 26;

fn overflow(what: &str) -> ValueError {
    ValueError::new(
        ErrorKind::Overflow,
        format!("Overflow when computing {what}"),
    )
}

impl Int {
    /// Zero.
    pub const ZERO: Self = Self::Small(0);
    /// One.
    pub const ONE: Self = Self::Small(1);

    /// Converts a big integer, keeping the representation canonical.
    #[must_use]
    pub fn from_big(b: BigInt) -> Self {
        match b.to_i64() {
            Some(v) => Self::Small(v),
            None => Self::Big(Arc::new(b)),
        }
    }

    /// The value as an `i64`, if it fits.
    #[must_use]
    pub fn to_i64(&self) -> Option<i64> {
        match self {
            Self::Small(v) => Some(*v),
            Self::Big(b) => b.to_i64(),
        }
    }

    /// The value as an `i32` (a TLC `IntValue`), if it fits.
    #[must_use]
    pub fn to_i32(&self) -> Option<i32> {
        self.to_i64().and_then(|v| i32::try_from(v).ok())
    }

    /// The value as a big integer.
    #[must_use]
    pub fn to_big(&self) -> BigInt {
        match self {
            Self::Small(v) => BigInt::from(*v),
            Self::Big(b) => (**b).clone(),
        }
    }

    /// Whether the value is negative.
    #[must_use]
    pub fn is_negative(&self) -> bool {
        match self {
            Self::Small(v) => *v < 0,
            Self::Big(b) => b.is_negative(),
        }
    }

    /// Parses a decimal numeral as written in a spec.
    ///
    /// In [`IntMode::Tlc`] a numeral above `2^31 - 1` is `EC.TLC_INTEGER_TOO_BIG`, even
    /// when it is the operand of unary minus (`-2147483648` is rejected, as in TLC).
    ///
    /// # Errors
    /// [`ErrorKind::IntegerTooBig`] in TLC mode; [`ErrorKind::Argument`] if `digits` is
    /// not a non-empty string of ASCII digits.
    pub fn from_literal(digits: &str, mode: IntMode) -> Result<Self> {
        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
            return Err(ValueError::new(
                ErrorKind::Argument,
                format!("Not a decimal numeral: {digits}"),
            ));
        }
        let big: BigInt = digits.parse().map_err(|_| {
            ValueError::new(
                ErrorKind::Argument,
                format!("Not a decimal numeral: {digits}"),
            )
        })?;
        Self::from_literal_value(big, digits, mode)
    }

    /// Accepts a numeral already converted to a big integer (for `\b`, `\o`, `\h`
    /// numerals). `text` is the numeral as SANY prints it, used in the error message.
    ///
    /// # Errors
    /// [`ErrorKind::IntegerTooBig`] in TLC mode when the value exceeds `2^31 - 1`.
    pub fn from_literal_value(value: BigInt, text: &str, mode: IntMode) -> Result<Self> {
        let v = Self::from_big(value);
        if mode == IntMode::Tlc && v.to_i32().is_none() {
            return Err(ValueError::new(
                ErrorKind::IntegerTooBig,
                format!("TLC can't handle a number this big.\n{text}"),
            ));
        }
        Ok(v)
    }

    fn tlc_operand(&self) -> Result<i32> {
        self.to_i32().ok_or_else(|| {
            ValueError::new(
                ErrorKind::Overflow,
                format!("Overflow when computing {self} (not a 32-bit TLC integer)"),
            )
        })
    }

    /// `a + b`.
    ///
    /// # Errors
    /// [`ErrorKind::Overflow`] in TLC mode (`Overflow when computing a+b`).
    pub fn add(&self, other: &Self, mode: IntMode) -> Result<Self> {
        match mode {
            IntMode::Tlc => {
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                a.checked_add(b)
                    .map(|r| Self::Small(i64::from(r)))
                    .ok_or_else(|| overflow(&format!("{a}+{b}")))
            }
            IntMode::Big => Ok(match (self, other) {
                (Self::Small(a), Self::Small(b)) => match a.checked_add(*b) {
                    Some(r) => Self::Small(r),
                    None => Self::from_big(BigInt::from(*a) + b),
                },
                _ => Self::from_big(self.to_big() + other.to_big()),
            }),
        }
    }

    /// `a - b`.
    ///
    /// # Errors
    /// [`ErrorKind::Overflow`] in TLC mode (`Overflow when computing a-b`).
    pub fn sub(&self, other: &Self, mode: IntMode) -> Result<Self> {
        match mode {
            IntMode::Tlc => {
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                a.checked_sub(b)
                    .map(|r| Self::Small(i64::from(r)))
                    .ok_or_else(|| overflow(&format!("{a}-{b}")))
            }
            IntMode::Big => Ok(match (self, other) {
                (Self::Small(a), Self::Small(b)) => match a.checked_sub(*b) {
                    Some(r) => Self::Small(r),
                    None => Self::from_big(BigInt::from(*a) - b),
                },
                _ => Self::from_big(self.to_big() - other.to_big()),
            }),
        }
    }

    /// `a * b`.
    ///
    /// # Errors
    /// [`ErrorKind::Overflow`] in TLC mode (`Overflow when computing a*b`).
    pub fn mul(&self, other: &Self, mode: IntMode) -> Result<Self> {
        match mode {
            IntMode::Tlc => {
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                a.checked_mul(b)
                    .map(|r| Self::Small(i64::from(r)))
                    .ok_or_else(|| overflow(&format!("{a}*{b}")))
            }
            IntMode::Big => Ok(match (self, other) {
                (Self::Small(a), Self::Small(b)) => match a.checked_mul(*b) {
                    Some(r) => Self::Small(r),
                    None => Self::from_big(BigInt::from(*a) * b),
                },
                _ => Self::from_big(self.to_big() * other.to_big()),
            }),
        }
    }

    /// Unary minus, `-a` (`Integers.Neg`).
    ///
    /// # Errors
    /// [`ErrorKind::Overflow`] in TLC mode for `-(-2^31)`
    /// (`Overflow when computing --2147483648`).
    pub fn neg(&self, mode: IntMode) -> Result<Self> {
        match mode {
            IntMode::Tlc => {
                let a = self.tlc_operand()?;
                a.checked_neg()
                    .map(|r| Self::Small(i64::from(r)))
                    .ok_or_else(|| overflow("--2147483648"))
            }
            IntMode::Big => Ok(match self {
                Self::Small(a) => match a.checked_neg() {
                    Some(r) => Self::Small(r),
                    None => Self::from_big(-BigInt::from(*a)),
                },
                Self::Big(b) => Self::from_big(-(**b).clone()),
            }),
        }
    }

    /// Floored division, `a \div b` (`Integers.Divide`).
    ///
    /// # Errors
    /// [`ErrorKind::DivisionByZero`] when `b = 0`; [`ErrorKind::Overflow`] in TLC mode
    /// for `-2^31 \div -1`.
    pub fn div(&self, other: &Self, mode: IntMode) -> Result<Self> {
        if other.is_zero() {
            return Err(ValueError::new(
                ErrorKind::DivisionByZero,
                "The second argument of \\div is 0.",
            ));
        }
        match mode {
            IntMode::Tlc => {
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                if a == i32::MIN && b == -1 {
                    return Err(overflow("-2147483648 \\div -1"));
                }
                Ok(Self::Small(i64::from(num_integer::Integer::div_floor(
                    &a, &b,
                ))))
            }
            IntMode::Big => Ok(match (self, other) {
                (Self::Small(a), Self::Small(b)) if !(*a == i64::MIN && *b == -1) => {
                    Self::Small(num_integer::Integer::div_floor(a, b))
                }
                _ => Self::from_big(self.to_big().div_floor(&other.to_big())),
            }),
        }
    }

    /// `a \div b` as `Naturals.Divide` computes it, for specifications that load
    /// `Naturals` but not `Integers`.
    ///
    /// In TLC mode this ports `tlc2.module.Naturals.Divide` (tlaplus `94d0c50`):
    /// Java's truncating `int` division, decremented when the quotient is
    /// *negative* and inexact. A quotient that truncates to `0` is therefore
    /// never decremented, so `-1 \div 2` and `1 \div -2` are `0`, not the floored
    /// `-1`; and `-2147483648 \div -1` wraps to `-2147483648` instead of
    /// overflowing. In big mode it is floored division, like [`Int::div`].
    ///
    /// ```
    /// use dive_value::{Int, IntMode};
    /// let q = |a: i64, b: i64| Int::from(a).div_naturals(&Int::from(b), IntMode::Tlc);
    /// assert_eq!(q(-1, 2)?, Int::from(0_i64));
    /// assert_eq!(q(-7, 2)?, Int::from(-4_i64));
    /// assert_eq!(q(-2_147_483_648, -1)?, Int::from(-2_147_483_648_i64));
    /// assert_eq!(Int::from(-1_i64).div(&Int::from(2_i64), IntMode::Tlc)?, Int::from(-1_i64));
    /// # Ok::<(), dive_value::ValueError>(())
    /// ```
    ///
    /// # Errors
    /// [`ErrorKind::DivisionByZero`] when `b = 0`.
    pub fn div_naturals(&self, other: &Self, mode: IntMode) -> Result<Self> {
        match mode {
            IntMode::Tlc => {
                if other.is_zero() {
                    return self.div(other, mode);
                }
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                let mut q = a.wrapping_div(b);
                if q < 0 && q.wrapping_mul(b) != a {
                    q -= 1;
                }
                Ok(Self::Small(i64::from(q)))
            }
            IntMode::Big => self.div(other, mode),
        }
    }

    /// `a % b`, defined for `b > 0`, with a result in `0 .. b-1` (`Integers.Mod`).
    ///
    /// # Errors
    /// [`ErrorKind::Argument`] when `b <= 0`.
    pub fn rem(&self, other: &Self, mode: IntMode) -> Result<Self> {
        if !other.is_positive() {
            return Err(ValueError::new(
                ErrorKind::Argument,
                format!(
                    "The second argument of % should be a positive number, but instead it is:\n{other}"
                ),
            ));
        }
        match mode {
            IntMode::Tlc => {
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                Ok(Self::Small(i64::from(num_integer::Integer::mod_floor(
                    &a, &b,
                ))))
            }
            IntMode::Big => Ok(match (self, other) {
                (Self::Small(a), Self::Small(b)) => {
                    Self::Small(num_integer::Integer::mod_floor(a, b))
                }
                _ => Self::from_big(self.to_big().mod_floor(&other.to_big())),
            }),
        }
    }

    /// `a ^ b` for `b >= 0` (`Integers.Expt`).
    ///
    /// # Errors
    /// [`ErrorKind::Argument`] when `b < 0`; [`ErrorKind::NullPowerNull`] for `0^0`;
    /// [`ErrorKind::Overflow`] in TLC mode (`Overflow when computing a^b`);
    /// [`ErrorKind::DiveLimit`] in big mode when the result would exceed 2^26 bits.
    pub fn pow(&self, other: &Self, mode: IntMode) -> Result<Self> {
        if other.is_negative() {
            return Err(ValueError::new(
                ErrorKind::Argument,
                format!(
                    "The second argument of ^ should be a natural number, but instead it is:\n{other}"
                ),
            ));
        }
        if other.is_zero() {
            if self.is_zero() {
                return Err(ValueError::new(
                    ErrorKind::NullPowerNull,
                    "0^0 is undefined.",
                ));
            }
            return Ok(Self::ONE);
        }
        match mode {
            IntMode::Tlc => {
                let (a, b) = (self.tlc_operand()?, other.tlc_operand()?);
                let mut res = i64::from(a);
                for _ in 1..b {
                    // |res| is non-decreasing for |a| >= 2, and bounded for |a| <= 1,
                    // so stopping early gives TLC's answer without its O(b) loop.
                    if a.unsigned_abs() <= 1 {
                        res = if a == -1 && b % 2 == 0 {
                            1
                        } else {
                            i64::from(a)
                        };
                        break;
                    }
                    res *= i64::from(a);
                    if res < i64::from(i32::MIN) || res > i64::from(i32::MAX) {
                        return Err(overflow(&format!("{a}^{b}")));
                    }
                }
                Ok(Self::Small(res))
            }
            IntMode::Big => {
                let base = self.to_big();
                if base.abs() <= BigInt::one() {
                    let odd = other.to_big().is_odd();
                    return Ok(if base.is_negative() && !odd {
                        Self::ONE
                    } else {
                        self.clone()
                    });
                }
                let exp = other.to_i64().and_then(|e| u64::try_from(e).ok());
                let bits = base.bits();
                match exp {
                    Some(e) if e.saturating_mul(bits) <= MAX_POW_BITS => {
                        let e = u32::try_from(e).unwrap_or(u32::MAX);
                        Ok(Self::from_big(num_traits::Pow::pow(base, e)))
                    }
                    _ => Err(ValueError::new(
                        ErrorKind::DiveLimit,
                        format!(
                            "The value of {self}^{other} is too large: it exceeds dive's limit of {MAX_POW_BITS} bits."
                        ),
                    )),
                }
            }
        }
    }

    fn is_zero(&self) -> bool {
        matches!(self, Self::Small(0))
    }

    fn is_positive(&self) -> bool {
        match self {
            Self::Small(v) => *v > 0,
            Self::Big(b) => b.is_positive(),
        }
    }
}

impl From<i64> for Int {
    fn from(v: i64) -> Self {
        Self::Small(v)
    }
}

impl From<i32> for Int {
    fn from(v: i32) -> Self {
        Self::Small(i64::from(v))
    }
}

/// Numeric order. A `Big` that fits in an `i64` (possible only by building the
/// variant directly) still compares by value.
impl Ord for Int {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (Self::Small(a), Self::Small(b)) => a.cmp(b),
            _ => self.to_big().cmp(&other.to_big()),
        }
    }
}

impl PartialEq for Int {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Int {}

impl std::hash::Hash for Int {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self.to_i64() {
            Some(v) => v.hash(state),
            None => self.to_big().hash(state),
        }
    }
}

impl PartialOrd for Int {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for Int {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Small(v) => write!(f, "{v}"),
            Self::Big(b) => write!(f, "{b}"),
        }
    }
}

impl fmt::Debug for Int {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}