tulisp 0.29.0

An embeddable lisp interpreter.
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
use std::fmt::Display;

use crate::{Error, TulispObject, TulispValue};

#[derive(Debug, Clone, Copy)]
pub enum Number {
    Int(i64),
    Float(f64),
}

impl Default for Number {
    fn default() -> Self {
        Number::Int(0)
    }
}

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

impl From<f64> for Number {
    fn from(value: f64) -> Self {
        Number::Float(value)
    }
}

impl TryFrom<TulispObject> for Number {
    type Error = Error;

    fn try_from(value: TulispObject) -> Result<Self, Self::Error> {
        match &value.inner_ref().0 {
            TulispValue::Number { value } => Ok(*value),
            _ => Err(Error::type_mismatch(format!(
                "Expected number, got: {}",
                value
            ))),
        }
    }
}

impl From<Number> for TulispObject {
    fn from(value: Number) -> Self {
        match value {
            Number::Int(v) => v.into(),
            Number::Float(v) => v.into(),
        }
    }
}

impl Display for Number {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Number::Int(v) => write!(f, "{}", v),
            // Match Emacs' float printer:
            // - `f64::INFINITY` / `NEG_INFINITY` print as
            //   `1.0e+INF` / `-1.0e+INF`
            // - NaN prints with the sign bit reflected in the
            //   leading mantissa: `0.0e+NaN` (positive bit) or
            //   `-0.0e+NaN` (negative bit). Both still round-trip
            //   through `read` because Emacs accepts the same forms.
            // - Whole-value finite floats keep the trailing `.0`
            //   via `{:?}` (`2.0` => `"2.0"`, not `"2"`).
            Number::Float(v) => {
                if v.is_infinite() {
                    if *v < 0.0 {
                        f.write_str("-1.0e+INF")
                    } else {
                        f.write_str("1.0e+INF")
                    }
                } else if v.is_nan() {
                    if v.is_sign_negative() {
                        f.write_str("-0.0e+NaN")
                    } else {
                        f.write_str("0.0e+NaN")
                    }
                } else {
                    write!(f, "{:?}", v)
                }
            }
        }
    }
}

/// Convert `value` to `i64`, raising `OutOfRange` for NaN, ±inf,
/// or values outside `i64`'s range. `f64 as i64` saturates these
/// silently — for `truncate` / `floor` / `ceiling` / `round` and
/// the `try_int` extractor, the saturated sentinel is misleading.
/// `op` names the caller for the error message.
#[inline]
pub(crate) fn f64_to_i64_checked(value: f64, op: &str) -> Result<i64, Error> {
    if !value.is_finite() {
        return Err(Error::out_of_range(format!(
            "{op}: cannot convert {value} to integer"
        )));
    }
    // `i64::MAX as f64` rounds up to `9.223…e18`, so the
    // representable bound is `< MAX_F64`. `MIN_F64` is exact
    // (`-2^63` is exactly representable in f64).
    const I64_MAX_F64: f64 = 9.223372036854776e18;
    const I64_MIN_F64: f64 = -9.223372036854776e18;
    if !(I64_MIN_F64..I64_MAX_F64).contains(&value) {
        return Err(Error::out_of_range(format!(
            "{op}: float {value} out of range for integer"
        )));
    }
    Ok(value as i64)
}

/// Floored remainder for floats — `a - b*floor(a/b)`, taking the
/// divisor's sign, matching Emacs `mod`. A zero divisor yields NaN
/// (the comparisons below are all false for NaN, so it's returned
/// unadjusted), which Emacs also surfaces for float `mod`.
#[inline]
fn floor_mod_f64(a: f64, b: f64) -> f64 {
    let m = a % b;
    if m != 0.0 && (m < 0.0) != (b < 0.0) {
        m + b
    } else {
        m
    }
}

impl Number {
    /// Like `Add` but raises `OutOfRange` on `Int + Int` overflow
    /// instead of wrapping. Float operands fall through to `f64::add`,
    /// which produces `inf` rather than overflowing — matches Emacs
    /// (which would promote to bignum on integer overflow).
    pub(crate) fn checked_add(self, rhs: Number) -> Result<Number, Error> {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => l
                .checked_add(r)
                .map(Number::Int)
                .ok_or_else(|| Error::out_of_range(format!("integer overflow: {} + {}", l, r))),
            (Number::Int(l), Number::Float(r)) => Ok(Number::Float(l as f64 + r)),
            (Number::Float(l), Number::Int(r)) => Ok(Number::Float(l + r as f64)),
            (Number::Float(l), Number::Float(r)) => Ok(Number::Float(l + r)),
        }
    }

    /// `Sub` counterpart with `Int - Int` overflow detection.
    pub(crate) fn checked_sub(self, rhs: Number) -> Result<Number, Error> {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => l
                .checked_sub(r)
                .map(Number::Int)
                .ok_or_else(|| Error::out_of_range(format!("integer overflow: {} - {}", l, r))),
            (Number::Int(l), Number::Float(r)) => Ok(Number::Float(l as f64 - r)),
            (Number::Float(l), Number::Int(r)) => Ok(Number::Float(l - r as f64)),
            (Number::Float(l), Number::Float(r)) => Ok(Number::Float(l - r)),
        }
    }

    /// `Mul` counterpart with `Int * Int` overflow detection.
    pub(crate) fn checked_mul(self, rhs: Number) -> Result<Number, Error> {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => l
                .checked_mul(r)
                .map(Number::Int)
                .ok_or_else(|| Error::out_of_range(format!("integer overflow: {} * {}", l, r))),
            (Number::Int(l), Number::Float(r)) => Ok(Number::Float(l as f64 * r)),
            (Number::Float(l), Number::Int(r)) => Ok(Number::Float(l * r as f64)),
            (Number::Float(l), Number::Float(r)) => Ok(Number::Float(l * r)),
        }
    }

    /// Integer/float division matching Emacs `/` (integers truncate
    /// toward zero). Raises `OutOfRange` on an integer zero divisor
    /// and on `i64::MIN / -1` overflow; float operands divide
    /// normally, yielding ±inf for a zero divisor as Emacs does.
    pub(crate) fn checked_div(self, rhs: Number) -> Result<Number, Error> {
        match (self, rhs) {
            (Number::Int(_), Number::Int(0)) => {
                Err(Error::out_of_range("Division by zero".to_string()))
            }
            (Number::Int(l), Number::Int(r)) => l
                .checked_div(r)
                .map(Number::Int)
                .ok_or_else(|| Error::out_of_range(format!("integer overflow: {} / {}", l, r))),
            (Number::Int(l), Number::Float(r)) => Ok(Number::Float(l as f64 / r)),
            (Number::Float(l), Number::Int(r)) => Ok(Number::Float(l / r as f64)),
            (Number::Float(l), Number::Float(r)) => Ok(Number::Float(l / r)),
        }
    }

    /// Floored modulo matching Emacs `mod`: the result takes the
    /// divisor's sign (`(mod -7 3)` => 2, `(mod 7 -3)` => -2). Raises
    /// `OutOfRange` on an integer zero divisor; a float divisor
    /// yields NaN. A `-1` divisor always yields 0, so the
    /// `i64::MIN % -1` overflow can't arise.
    pub(crate) fn checked_mod(self, rhs: Number) -> Result<Number, Error> {
        match (self, rhs) {
            (Number::Int(_), Number::Int(0)) => {
                Err(Error::out_of_range("Division by zero".to_string()))
            }
            (Number::Int(_), Number::Int(-1)) => Ok(Number::Int(0)),
            (Number::Int(l), Number::Int(r)) => {
                let m = l % r;
                let m = if m != 0 && (m < 0) != (r < 0) {
                    m + r
                } else {
                    m
                };
                Ok(Number::Int(m))
            }
            (Number::Int(l), Number::Float(r)) => Ok(Number::Float(floor_mod_f64(l as f64, r))),
            (Number::Float(l), Number::Int(r)) => Ok(Number::Float(floor_mod_f64(l, r as f64))),
            (Number::Float(l), Number::Float(r)) => Ok(Number::Float(floor_mod_f64(l, r))),
        }
    }
}

impl std::ops::Add for Number {
    type Output = Number;

    fn add(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => Number::Int(l + r),
            (Number::Int(l), Number::Float(r)) => Number::Float(l as f64 + r),
            (Number::Float(l), Number::Int(r)) => Number::Float(l + r as f64),
            (Number::Float(l), Number::Float(r)) => Number::Float(l + r),
        }
    }
}

impl std::ops::Add<i64> for Number {
    type Output = Number;

    fn add(self, rhs: i64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Int(l + rhs),
            Number::Float(l) => Number::Float(l + rhs as f64),
        }
    }
}

impl std::ops::Add<f64> for Number {
    type Output = Number;

    fn add(self, rhs: f64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Float(l as f64 + rhs),
            Number::Float(l) => Number::Float(l + rhs),
        }
    }
}

impl std::ops::Sub for Number {
    type Output = Number;

    fn sub(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => Number::Int(l - r),
            (Number::Int(l), Number::Float(r)) => Number::Float(l as f64 - r),
            (Number::Float(l), Number::Int(r)) => Number::Float(l - r as f64),
            (Number::Float(l), Number::Float(r)) => Number::Float(l - r),
        }
    }
}

impl std::ops::Sub<i64> for Number {
    type Output = Number;

    fn sub(self, rhs: i64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Int(l - rhs),
            Number::Float(l) => Number::Float(l - rhs as f64),
        }
    }
}

impl std::ops::Sub<f64> for Number {
    type Output = Number;

    fn sub(self, rhs: f64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Float(l as f64 - rhs),
            Number::Float(l) => Number::Float(l - rhs),
        }
    }
}

impl std::ops::Mul for Number {
    type Output = Number;

    fn mul(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => Number::Int(l * r),
            (Number::Int(l), Number::Float(r)) => Number::Float(l as f64 * r),
            (Number::Float(l), Number::Int(r)) => Number::Float(l * r as f64),
            (Number::Float(l), Number::Float(r)) => Number::Float(l * r),
        }
    }
}

impl std::ops::Mul<i64> for Number {
    type Output = Number;

    fn mul(self, rhs: i64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Int(l * rhs),
            Number::Float(l) => Number::Float(l * rhs as f64),
        }
    }
}

impl std::ops::Mul<f64> for Number {
    type Output = Number;

    fn mul(self, rhs: f64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Float(l as f64 * rhs),
            Number::Float(l) => Number::Float(l * rhs),
        }
    }
}

impl std::ops::Div for Number {
    type Output = Number;

    /// Match Emacs Lisp `/`: integer division when both operands are
    /// integers, float division otherwise. Callers must guard against
    /// `Int(0)` divisor before calling — Rust's `i64::div` panics for
    /// that, but `f64::div` returns `inf`/`nan` (which Emacs surfaces).
    fn div(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => Number::Int(l / r),
            (Number::Int(l), Number::Float(r)) => Number::Float(l as f64 / r),
            (Number::Float(l), Number::Int(r)) => Number::Float(l / r as f64),
            (Number::Float(l), Number::Float(r)) => Number::Float(l / r),
        }
    }
}

impl std::ops::Div<i64> for Number {
    type Output = Number;

    fn div(self, rhs: i64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Int(l / rhs),
            Number::Float(l) => Number::Float(l / rhs as f64),
        }
    }
}

impl std::ops::Div<f64> for Number {
    type Output = Number;

    fn div(self, rhs: f64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Float(l as f64 / rhs),
            Number::Float(l) => Number::Float(l / rhs),
        }
    }
}

impl std::ops::Rem for Number {
    type Output = Number;

    fn rem(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Number::Int(l), Number::Int(r)) => Number::Int(l % r),
            (Number::Int(l), Number::Float(r)) => Number::Float(l as f64 % r),
            (Number::Float(l), Number::Int(r)) => Number::Float(l % r as f64),
            (Number::Float(l), Number::Float(r)) => Number::Float(l % r),
        }
    }
}

impl std::ops::Rem<i64> for Number {
    type Output = Number;

    fn rem(self, rhs: i64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Int(l % rhs),
            Number::Float(l) => Number::Float(l % rhs as f64),
        }
    }
}

impl std::ops::Rem<f64> for Number {
    type Output = Number;

    fn rem(self, rhs: f64) -> Self::Output {
        match self {
            Number::Int(l) => Number::Float(l as f64 % rhs),
            Number::Float(l) => Number::Float(l % rhs),
        }
    }
}

impl PartialEq for Number {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Number::Int(l), Number::Int(r)) => l == r,
            (Number::Int(l), Number::Float(r)) => (*l as f64) == *r,
            (Number::Float(l), Number::Int(r)) => *l == (*r as f64),
            (Number::Float(l), Number::Float(r)) => l == r,
        }
    }
}

impl PartialEq<i64> for Number {
    fn eq(&self, other: &i64) -> bool {
        match self {
            Number::Int(l) => l == other,
            Number::Float(l) => *l == (*other as f64),
        }
    }
}

impl PartialEq<f64> for Number {
    fn eq(&self, other: &f64) -> bool {
        match self {
            Number::Int(l) => (*l as f64) == *other,
            Number::Float(l) => l == other,
        }
    }
}

impl PartialOrd for Number {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match (self, other) {
            (Number::Int(l), Number::Int(r)) => l.partial_cmp(r),
            (Number::Int(l), Number::Float(r)) => (*l as f64).partial_cmp(r),
            (Number::Float(l), Number::Int(r)) => l.partial_cmp(&(*r as f64)),
            (Number::Float(l), Number::Float(r)) => l.partial_cmp(r),
        }
    }
}

impl PartialOrd<i64> for Number {
    fn partial_cmp(&self, other: &i64) -> Option<std::cmp::Ordering> {
        match self {
            Number::Int(l) => l.partial_cmp(other),
            Number::Float(l) => l.partial_cmp(&(*other as f64)),
        }
    }
}

impl PartialOrd<f64> for Number {
    fn partial_cmp(&self, other: &f64) -> Option<std::cmp::Ordering> {
        match self {
            Number::Int(l) => (*l as f64).partial_cmp(other),
            Number::Float(l) => l.partial_cmp(other),
        }
    }
}