1use std::rc::Rc;
4
5use logicaffeine_base::{BigInt, Complex, ComplexF, Decimal, Modular, Rational, WordVal};
6
7use crate::ast::stmt::BinaryOpKind;
8use crate::interpreter::RuntimeValue;
9
10use super::compare::{compare, values_equal};
11use super::exact;
12use super::temporal::date_add_span;
13
14fn rat_of(v: &RuntimeValue) -> Option<Rational> {
18 match v {
19 RuntimeValue::Int(n) => Some(Rational::from_i64(*n)),
20 RuntimeValue::BigInt(b) => Some(Rational::from_bigint((**b).clone())),
21 RuntimeValue::Rational(r) => Some((**r).clone()),
22 RuntimeValue::Decimal(d) => Some(d.to_rational()),
23 _ => None,
24 }
25}
26
27fn dec_of(v: &RuntimeValue) -> Option<Decimal> {
31 match v {
32 RuntimeValue::Int(n) => Some(Decimal::from_i64(*n)),
33 RuntimeValue::BigInt(b) => Some(Decimal::from_bigint((**b).clone())),
34 RuntimeValue::Decimal(d) => Some((**d).clone()),
35 _ => None,
36 }
37}
38
39fn num_f64(v: &RuntimeValue) -> Option<f64> {
42 match v {
43 RuntimeValue::Int(n) => Some(*n as f64),
44 RuntimeValue::BigInt(b) => Some(b.to_f64()),
45 RuntimeValue::Rational(r) => Some(r.to_f64()),
46 RuntimeValue::Decimal(d) => Some(d.to_rational().to_f64()),
47 RuntimeValue::Float(f) => Some(*f),
48 _ => None,
49 }
50}
51
52fn complex_of(v: &RuntimeValue) -> Option<Complex> {
56 match v {
57 RuntimeValue::Int(n) => Some(Complex::from_i64(*n)),
58 RuntimeValue::BigInt(b) => {
59 Some(Complex::from_rational(Rational::from_bigint((**b).clone())))
60 }
61 RuntimeValue::Rational(r) => Some(Complex::from_rational((**r).clone())),
62 RuntimeValue::Decimal(d) => Some(Complex::from_rational(d.to_rational())),
63 RuntimeValue::Complex(c) => Some((**c).clone()),
64 _ => None,
65 }
66}
67
68fn modular_binop(
73 left: &RuntimeValue,
74 right: &RuntimeValue,
75 op_name: &str,
76 f: impl Fn(&Modular, &Modular) -> Option<Modular>,
77) -> Option<Result<RuntimeValue, String>> {
78 if !matches!(left, RuntimeValue::Modular(_)) && !matches!(right, RuntimeValue::Modular(_)) {
79 return None;
80 }
81 Some(match (left, right) {
82 (RuntimeValue::Modular(a), RuntimeValue::Modular(b)) => match f(a, b) {
83 Some(r) => Ok(RuntimeValue::Modular(Rc::new(r))),
84 None => Err(logicaffeine_data::failure::modular_rings_differ(op_name)),
85 },
86 _ => Err(format!(
87 "Cannot {} {} and {} (modular arithmetic needs two ℤ/nℤ values of the same modulus)",
88 op_name,
89 left.type_name(),
90 right.type_name()
91 )),
92 })
93}
94
95fn complex_binop(
99 left: &RuntimeValue,
100 right: &RuntimeValue,
101 op_name: &str,
102 f: impl Fn(&Complex, &Complex) -> Complex,
103) -> Option<Result<RuntimeValue, String>> {
104 if !matches!(left, RuntimeValue::Complex(_)) && !matches!(right, RuntimeValue::Complex(_)) {
105 return None;
106 }
107 Some(match (complex_of(left), complex_of(right)) {
108 (Some(a), Some(b)) => Ok(RuntimeValue::Complex(Rc::new(f(&a, &b)))),
109 _ => Err(format!(
110 "Cannot {} {} and {} (Complex combines only with exact numbers)",
111 op_name,
112 left.type_name(),
113 right.type_name()
114 )),
115 })
116}
117
118fn complexf_of(v: &RuntimeValue) -> Option<ComplexF> {
121 match v {
122 RuntimeValue::Float(f) => Some(ComplexF::from_f64(*f)),
123 RuntimeValue::ComplexF(c) => Some(**c),
124 RuntimeValue::Complex(c) => Some(ComplexF::new(c.re().to_f64(), c.im().to_f64())),
125 other => complex_of(other).map(|c| ComplexF::new(c.re().to_f64(), c.im().to_f64())),
126 }
127}
128
129fn complexf_binop(
135 left: &RuntimeValue,
136 right: &RuntimeValue,
137 op_name: &str,
138 f: impl Fn(&ComplexF, &ComplexF) -> Option<ComplexF>,
139) -> Option<Result<RuntimeValue, String>> {
140 let is_cf = |v: &RuntimeValue| matches!(v, RuntimeValue::ComplexF(_));
141 let is_c = |v: &RuntimeValue| matches!(v, RuntimeValue::Complex(_));
142 let is_f = |v: &RuntimeValue| matches!(v, RuntimeValue::Float(_));
143 let fires =
144 is_cf(left) || is_cf(right) || (is_c(left) && is_f(right)) || (is_f(left) && is_c(right));
145 if !fires {
146 return None;
147 }
148 Some(match (complexf_of(left), complexf_of(right)) {
149 (Some(a), Some(b)) => match f(&a, &b) {
150 Some(r) => Ok(RuntimeValue::ComplexF(Rc::new(r))),
151 None => Err(format!(
152 "Cannot {} {} and {} (division by zero)",
153 op_name,
154 left.type_name(),
155 right.type_name()
156 )),
157 },
158 _ => Err(format!(
159 "Cannot {} {} and {} (complex combines only with numbers)",
160 op_name,
161 left.type_name(),
162 right.type_name()
163 )),
164 })
165}
166
167fn decimal_binop(
172 left: &RuntimeValue,
173 right: &RuntimeValue,
174 dec: impl Fn(&Decimal, &Decimal) -> Decimal,
175 rat: impl Fn(&Rational, &Rational) -> Rational,
176 flt: impl Fn(f64, f64) -> f64,
177) -> Option<RuntimeValue> {
178 if !matches!(left, RuntimeValue::Decimal(_)) && !matches!(right, RuntimeValue::Decimal(_)) {
179 return None;
180 }
181 if let (Some(a), Some(b)) = (dec_of(left), dec_of(right)) {
182 return Some(RuntimeValue::Decimal(Rc::new(dec(&a, &b))));
183 }
184 if let (Some(a), Some(b)) = (rat_of(left), rat_of(right)) {
185 return Some(RuntimeValue::from_rational(rat(&a, &b)));
186 }
187 let (a, b) = (num_f64(left)?, num_f64(right)?);
188 Some(RuntimeValue::Float(flt(a, b)))
189}
190
191fn quantity_binop(
197 left: &RuntimeValue,
198 right: &RuntimeValue,
199 op: char,
200) -> Option<Result<RuntimeValue, String>> {
201 use crate::interpreter::QuantityValue;
202 use logicaffeine_base::{Quantity, Unit};
203 if !matches!(left, RuntimeValue::Quantity(_)) && !matches!(right, RuntimeValue::Quantity(_)) {
204 return None;
205 }
206 let mk = |q: Quantity, unit: Unit| RuntimeValue::Quantity(Rc::new(QuantityValue { q, unit }));
207 let si_unit = |q: &Quantity| Unit::linear("", q.dimension(), Rational::one());
210 Some(match (left, right) {
211 (RuntimeValue::Quantity(a), RuntimeValue::Quantity(b)) => match op {
212 '+' => a.q.add(&b.q).map(|q| mk(q, a.unit.clone())).ok_or_else(|| {
213 logicaffeine_data::failure::quantities_differ(
214 "add",
215 a.q.dimension(),
216 b.q.dimension(),
217 )
218 }),
219 '-' => a.q.sub(&b.q).map(|q| mk(q, a.unit.clone())).ok_or_else(|| {
220 logicaffeine_data::failure::quantities_differ(
221 "subtract",
222 a.q.dimension(),
223 b.q.dimension(),
224 )
225 }),
226 '*' => {
227 let q = a.q.mul(&b.q);
228 let u = si_unit(&q);
229 Ok(mk(q, u))
230 }
231 '/' => match a.q.div(&b.q) {
232 Some(q) => {
233 let u = si_unit(&q);
234 Ok(mk(q, u))
235 }
236 None => Err(logicaffeine_data::failure::DIVIDE_BY_ZERO_QUANTITY.to_string()),
237 },
238 _ => unreachable!("quantity_binop only handles + - * /"),
239 },
240 (RuntimeValue::Quantity(a), scalar) if matches!(op, '*' | '/') => match rat_of(scalar) {
242 Some(k) => {
243 let mag = if op == '*' {
244 a.q.magnitude_si().mul(&k)
245 } else {
246 match a.q.magnitude_si().div(&k) {
247 Some(m) => m,
248 None => {
249 return Some(Err(
250 logicaffeine_data::failure::DIVIDE_QUANTITY_BY_ZERO.to_string()
251 ))
252 }
253 }
254 };
255 Ok(mk(Quantity::si(mag, a.q.dimension()), a.unit.clone()))
256 }
257 None => return None,
258 },
259 (scalar, RuntimeValue::Quantity(b)) if op == '*' => match rat_of(scalar) {
261 Some(k) => Ok(mk(
262 Quantity::si(b.q.magnitude_si().mul(&k), b.q.dimension()),
263 b.unit.clone(),
264 )),
265 None => return None,
266 },
267 _ => return None,
268 })
269}
270
271fn money_binop(
276 left: &RuntimeValue,
277 right: &RuntimeValue,
278 op: char,
279) -> Option<Result<RuntimeValue, String>> {
280 use logicaffeine_base::{Decimal, Money, RoundingMode};
281 if !matches!(left, RuntimeValue::Money(_)) && !matches!(right, RuntimeValue::Money(_)) {
282 return None;
283 }
284 let dec_of = |v: &RuntimeValue| -> Option<Decimal> {
286 match v {
287 RuntimeValue::Int(n) => Some(Decimal::from_i64(*n)),
288 RuntimeValue::Decimal(d) => Some((**d).clone()),
289 _ => None,
290 }
291 };
292 let mk = |m: Money| RuntimeValue::Money(Rc::new(m));
293 let mismatch = |a: &Money, b: &Money, verb: &str| {
294 logicaffeine_data::failure::currencies_differ(verb, a.currency.code, b.currency.code)
295 };
296 Some(match (left, right) {
297 (RuntimeValue::Money(a), RuntimeValue::Money(b)) => match op {
298 '+' => a.add(b).map(mk).ok_or_else(|| mismatch(a, b, "add")),
299 '-' => a.sub(b).map(mk).ok_or_else(|| mismatch(a, b, "subtract")),
300 '/' => match a.ratio(b) {
301 Some(r) => Ok(RuntimeValue::from_rational(r)),
302 None if a.currency != b.currency => Err(mismatch(a, b, "compare")),
303 None => Err(logicaffeine_data::failure::DIVIDE_MONEY_BY_ZERO_AMOUNT.to_string()),
304 },
305 '*' => Err("cannot multiply money by money — scale by a number instead".to_string()),
306 _ => unreachable!("money_binop only handles + - * /"),
307 },
308 (RuntimeValue::Money(a), scalar) | (scalar, RuntimeValue::Money(a)) if op == '*' => {
310 match dec_of(scalar) {
311 Some(s) => Ok(mk(Money::of(a.amount.mul(&s), a.currency))),
312 None => Err(format!("cannot multiply money by {}", scalar.type_name())),
313 }
314 }
315 (RuntimeValue::Money(a), scalar) if op == '/' => match dec_of(scalar) {
317 Some(s) => match a.amount.div(&s, a.currency.scale, RoundingMode::HalfEven) {
318 Some(d) => Ok(mk(Money::of(d, a.currency))),
319 None => Err(logicaffeine_data::failure::DIVIDE_MONEY_BY_ZERO.to_string()),
320 },
321 None => Err(format!("cannot divide money by {}", scalar.type_name())),
322 },
323 _ => return None,
324 })
325}
326
327fn word_width_err(a: WordVal, b: WordVal) -> String {
336 format!(
337 "cannot combine Word{} and Word{} — width mismatch",
338 a.width(),
339 b.width()
340 )
341}
342
343fn shift_count(v: &RuntimeValue) -> Option<u32> {
345 match v {
346 RuntimeValue::Int(n) => Some(*n as u32),
347 RuntimeValue::Word(w) => Some(w.to_u64() as u32),
348 _ => None,
349 }
350}
351
352fn word_binary_op(
356 op: BinaryOpKind,
357 left: &RuntimeValue,
358 right: &RuntimeValue,
359) -> Result<Option<RuntimeValue>, String> {
360 use BinaryOpKind::*;
361 if matches!(op, Shl | Shr) {
362 if let RuntimeValue::Word(a) = left {
363 let n =
364 shift_count(right).ok_or_else(|| "shift count must be an integer".to_string())?;
365 let r = if matches!(op, Shl) {
366 a.shl(n)
367 } else {
368 a.shr(n)
369 };
370 return Ok(Some(RuntimeValue::Word(r)));
371 }
372 return Ok(None);
373 }
374 let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (left, right) else {
375 return Ok(None);
376 };
377 let combined = match op {
378 And | BitAnd => a.bitand(*b),
381 Or | BitOr => a.bitor(*b),
382 BitXor => a.bitxor(*b),
383 _ => return Ok(None),
384 };
385 match combined {
386 Some(w) => Ok(Some(RuntimeValue::Word(w))),
387 None => Err(word_width_err(*a, *b)),
388 }
389}
390
391fn lanes_binary_op(
395 op: BinaryOpKind,
396 left: &RuntimeValue,
397 right: &RuntimeValue,
398) -> Result<Option<RuntimeValue>, String> {
399 let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (left, right) else {
400 return Ok(None);
401 };
402 let combined = match op {
403 BinaryOpKind::BitXor => a.bitxor(**b),
404 _ => return Ok(None),
405 };
406 match combined {
407 Some(v) => Ok(Some(RuntimeValue::Lanes(std::rc::Rc::new(v)))),
408 None => Err(format!(
409 "cannot combine {} and {} — lane-config mismatch",
410 a.type_name(),
411 b.type_name()
412 )),
413 }
414}
415
416fn exact_recurse(op: exact::Op, a: RuntimeValue, b: RuntimeValue) -> Result<RuntimeValue, String> {
419 match op {
420 exact::Op::Add => add(a, b),
421 exact::Op::Sub => subtract(a, b),
422 exact::Op::Mul => multiply(a, b),
423 exact::Op::Div => divide(a, b),
424 exact::Op::ExactDiv => exact_divide(a, b),
425 exact::Op::FloorDiv => floor_divide(a, b),
426 exact::Op::Mod => modulo(a, b),
427 exact::Op::Pow => power(a, b),
428 }
429}
430
431pub fn binary_op(
432 op: BinaryOpKind,
433 left: RuntimeValue,
434 right: RuntimeValue,
435) -> Result<RuntimeValue, String> {
436 if let Some(result) = word_binary_op(op, &left, &right)? {
439 return Ok(result);
440 }
441 if let Some(result) = lanes_binary_op(op, &left, &right)? {
443 return Ok(result);
444 }
445 match op {
446 BinaryOpKind::Add => add(left, right),
447 BinaryOpKind::Subtract => subtract(left, right),
448 BinaryOpKind::Multiply => multiply(left, right),
449 BinaryOpKind::Pow => power(left, right),
450 BinaryOpKind::Divide => divide(left, right),
451 BinaryOpKind::ExactDivide => exact_divide(left, right),
452 BinaryOpKind::FloorDivide => floor_divide(left, right),
453 BinaryOpKind::Modulo => modulo(left, right),
454 BinaryOpKind::Eq => super::compare::equality(&left, &right, false),
455 BinaryOpKind::NotEq => super::compare::equality(&left, &right, true),
456 BinaryOpKind::ApproxEq => approx_eq(left, right),
457 BinaryOpKind::Lt | BinaryOpKind::Gt | BinaryOpKind::LtEq | BinaryOpKind::GtEq => {
458 compare(op, &left, &right)
459 }
460 BinaryOpKind::And => Ok(RuntimeValue::Bool(left.decided_truth()? && right.decided_truth()?)),
462 BinaryOpKind::Or => Ok(RuntimeValue::Bool(left.decided_truth()? || right.decided_truth()?)),
463 BinaryOpKind::Concat => concat(left, right),
464 BinaryOpKind::SeqConcat => seq_concat(left, right),
465 BinaryOpKind::BitXor => match (&left, &right) {
466 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Int(a ^ b)),
467 (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => Ok(RuntimeValue::Bool(a ^ b)),
470 (RuntimeValue::Set(_), RuntimeValue::Set(_)) => {
472 set_binop(&left, &right, SetOp::SymmetricDifference)
473 }
474 _ => Err(logicaffeine_data::failure::BITXOR_OPERANDS.to_string()),
475 },
476 BinaryOpKind::BitAnd => match (&left, &right) {
478 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Int(a & b)),
479 (RuntimeValue::BigInt(big), RuntimeValue::Int(m))
485 | (RuntimeValue::Int(m), RuntimeValue::BigInt(big))
486 if *m >= 0
487 && (*m as u64).wrapping_add(1).is_power_of_two()
488 && !big.is_negative() =>
489 {
490 let modulus = BigInt::from_i64(*m).add(&BigInt::from_i64(1));
491 match big.div_rem(&modulus) {
492 Some((_, r)) => Ok(RuntimeValue::from_bigint(r)),
493 None => Ok(RuntimeValue::Int(0)),
494 }
495 }
496 (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => Ok(RuntimeValue::Bool(a & b)),
497 (RuntimeValue::Set(_), RuntimeValue::Set(_)) => {
498 set_binop(&left, &right, SetOp::Intersection)
499 }
500 _ => Err(logicaffeine_data::failure::BITAND_OPERANDS.to_string()),
501 },
502 BinaryOpKind::BitOr => match (&left, &right) {
504 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Int(a | b)),
505 (RuntimeValue::Bool(a), RuntimeValue::Bool(b)) => Ok(RuntimeValue::Bool(a | b)),
506 (RuntimeValue::Set(_), RuntimeValue::Set(_)) => set_binop(&left, &right, SetOp::Union),
507 _ => Err(logicaffeine_data::failure::BITOR_OPERANDS.to_string()),
508 },
509 BinaryOpKind::Shl => match (left, right) {
511 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
512 Ok(RuntimeValue::Int(a.wrapping_shl(b as u32)))
513 }
514 _ => Err(logicaffeine_data::failure::SHL_OPERANDS.to_string()),
515 },
516 BinaryOpKind::Shr => match (left, right) {
517 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
518 Ok(RuntimeValue::Int(a.wrapping_shr(b as u32)))
519 }
520 _ => Err(logicaffeine_data::failure::SHR_OPERANDS.to_string()),
521 },
522 }
523}
524
525pub fn add(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
526 if let Some(r) = exact::arith(exact::Op::Add, &left, &right, &exact_recurse) {
527 return r;
528 }
529 if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
532 return a
533 .add(*b)
534 .map(RuntimeValue::Word)
535 .ok_or_else(|| word_width_err(*a, *b));
536 }
537 if let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (&left, &right) {
539 return a
540 .add(**b)
541 .map(|v| RuntimeValue::Lanes(std::rc::Rc::new(v)))
542 .ok_or_else(|| {
543 format!(
544 "cannot add {} and {} — lane-config mismatch",
545 a.type_name(),
546 b.type_name()
547 )
548 });
549 }
550 if let Some(r) = quantity_binop(&left, &right, '+') {
551 return r;
552 }
553 if let Some(r) = money_binop(&left, &right, '+') {
554 return r;
555 }
556 if let Some(r) = modular_binop(&left, &right, "add", |a, b| a.add(b)) {
557 return r;
558 }
559 if let Some(r) = complexf_binop(&left, &right, "add", |a, b| Some(a.add(b))) {
560 return r;
561 }
562 if let Some(r) = complex_binop(&left, &right, "add", |a, b| a.add(b)) {
563 return r;
564 }
565 if let Some(r) = decimal_binop(
566 &left,
567 &right,
568 |a, b| a.add(b),
569 |a, b| a.add(b),
570 |a, b| a + b,
571 ) {
572 return Ok(r);
573 }
574 match (&left, &right) {
575 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(match a.checked_add(*b) {
579 Some(s) => RuntimeValue::Int(s),
580 None => RuntimeValue::from_bigint(BigInt::from_i64(*a).add(&BigInt::from_i64(*b))),
581 }),
582 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
583 Ok(RuntimeValue::from_bigint(a.add(b)))
584 }
585 (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
586 Ok(RuntimeValue::from_bigint(a.add(&BigInt::from_i64(*b))))
587 }
588 (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
589 Ok(RuntimeValue::from_bigint(BigInt::from_i64(*a).add(b)))
590 }
591 (RuntimeValue::Float(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(a + b)),
592 (RuntimeValue::Int(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(*a as f64 + b)),
593 (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Float(a + *b as f64)),
594 (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
595 Ok(RuntimeValue::Float(a.to_f64() + b))
596 }
597 (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
598 Ok(RuntimeValue::Float(a + b.to_f64()))
599 }
600 (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
604 Ok(RuntimeValue::from_rational(a.add(b)))
605 }
606 (RuntimeValue::Rational(_), RuntimeValue::Int(_))
607 | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
608 | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
609 | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => Ok(RuntimeValue::from_rational(
610 rat_of(&left).unwrap().add(&rat_of(&right).unwrap()),
611 )),
612 (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
613 Ok(RuntimeValue::Float(r.to_f64() + b))
614 }
615 (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
616 Ok(RuntimeValue::Float(a + r.to_f64()))
617 }
618 (RuntimeValue::Text(a), RuntimeValue::Text(b)) => {
619 Ok(RuntimeValue::Text(Rc::new(format!("{}{}", a, b))))
620 }
621 (RuntimeValue::Text(a), other) => Ok(RuntimeValue::Text(Rc::new(format!(
622 "{}{}",
623 a,
624 other.to_display_string()
625 )))),
626 (other, RuntimeValue::Text(b)) => Ok(RuntimeValue::Text(Rc::new(format!(
627 "{}{}",
628 other.to_display_string(),
629 b
630 )))),
631 (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => {
632 Ok(RuntimeValue::Duration(a.wrapping_add(*b)))
633 }
634 (
635 RuntimeValue::Date(days),
636 RuntimeValue::Span {
637 months,
638 days: span_days,
639 },
640 ) => Ok(RuntimeValue::Date(date_add_span(
641 *days, *months, *span_days,
642 ))),
643 (
646 RuntimeValue::Moment(nanos),
647 RuntimeValue::Span {
648 months,
649 days: span_days,
650 },
651 )
652 | (
653 RuntimeValue::Span {
654 months,
655 days: span_days,
656 },
657 RuntimeValue::Moment(nanos),
658 ) => Ok(RuntimeValue::Moment(super::temporal::moment_add_span(
659 *nanos, *months, *span_days,
660 ))),
661 (RuntimeValue::Moment(nanos), RuntimeValue::Duration(d))
663 | (RuntimeValue::Duration(d), RuntimeValue::Moment(nanos)) => {
664 Ok(RuntimeValue::Moment(nanos.wrapping_add(*d)))
665 }
666 (RuntimeValue::List(_), RuntimeValue::List(_)) => seq_concat(left.clone(), right.clone()),
669 _ => Err(format!(
670 "Cannot add {} and {}",
671 left.type_name(),
672 right.type_name()
673 )),
674 }
675}
676
677pub fn concat(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
678 Ok(RuntimeValue::Text(Rc::new(format!(
679 "{}{}",
680 left.to_display_string(),
681 right.to_display_string()
682 ))))
683}
684
685enum SetOp {
689 Union,
690 Intersection,
691 Difference,
692 SymmetricDifference,
693}
694
695fn set_binop(left: &RuntimeValue, right: &RuntimeValue, op: SetOp) -> Result<RuntimeValue, String> {
696 let (RuntimeValue::Set(a), RuntimeValue::Set(b)) = (left, right) else {
697 return Err("set operation requires two Sets".to_string());
698 };
699 let (a, b) = (a.borrow(), b.borrow());
700 let contains = |xs: &[RuntimeValue], v: &RuntimeValue| xs.iter().any(|x| values_equal(x, v));
701 let mut out: Vec<RuntimeValue> = Vec::new();
702 match op {
703 SetOp::Union => {
704 out.extend(a.iter().cloned());
705 for v in b.iter() {
706 if !contains(&out, v) {
707 out.push(v.clone());
708 }
709 }
710 }
711 SetOp::Intersection => {
712 for v in a.iter() {
713 if contains(&b, v) {
714 out.push(v.clone());
715 }
716 }
717 }
718 SetOp::Difference => {
719 for v in a.iter() {
720 if !contains(&b, v) {
721 out.push(v.clone());
722 }
723 }
724 }
725 SetOp::SymmetricDifference => {
726 for v in a.iter() {
727 if !contains(&b, v) {
728 out.push(v.clone());
729 }
730 }
731 for v in b.iter() {
732 if !contains(&a, v) {
733 out.push(v.clone());
734 }
735 }
736 }
737 }
738 Ok(RuntimeValue::Set(Rc::new(std::cell::RefCell::new(out))))
739}
740
741pub fn approx_eq(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
746 let as_f64 = |v: &RuntimeValue| -> Option<f64> {
747 match v {
748 RuntimeValue::Float(f) => Some(*f),
749 RuntimeValue::Int(n) => Some(*n as f64),
750 RuntimeValue::BigInt(b) => Some(b.to_f64()),
751 RuntimeValue::Rational(r) => Some(r.to_f64()),
752 _ => None,
753 }
754 };
755 match (as_f64(&left), as_f64(&right)) {
756 (Some(a), Some(b)) => Ok(RuntimeValue::Bool(logicaffeine_data::ops::logos_approx_eq(
757 a, b,
758 ))),
759 _ => Err(format!(
760 "`is approximately` compares numbers, got {} and {}",
761 left.type_name(),
762 right.type_name()
763 )),
764 }
765}
766
767pub fn seq_concat(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
770 use crate::interpreter::ListRepr;
771 match (&left, &right) {
772 (RuntimeValue::List(a), RuntimeValue::List(b)) => {
773 let mut items = a.borrow().to_values();
774 items.extend(b.borrow().to_values());
775 Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
776 ListRepr::from_values(items),
777 ))))
778 }
779 _ => Err("`followed by` requires two sequences (merge two sequences into one)".to_string()),
780 }
781}
782
783pub fn subtract(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
784 if let Some(r) = exact::arith(exact::Op::Sub, &left, &right, &exact_recurse) {
785 return r;
786 }
787 if matches!(
789 (&left, &right),
790 (RuntimeValue::Set(_), RuntimeValue::Set(_))
791 ) {
792 return set_binop(&left, &right, SetOp::Difference);
793 }
794 if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
795 return a
796 .sub(*b)
797 .map(RuntimeValue::Word)
798 .ok_or_else(|| word_width_err(*a, *b));
799 }
800 if let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (&left, &right) {
802 return a
803 .sub(**b)
804 .map(|v| RuntimeValue::Lanes(std::rc::Rc::new(v)))
805 .ok_or_else(|| {
806 format!(
807 "cannot subtract {} and {} — lane-config mismatch",
808 a.type_name(),
809 b.type_name()
810 )
811 });
812 }
813 if let Some(r) = quantity_binop(&left, &right, '-') {
814 return r;
815 }
816 if let Some(r) = money_binop(&left, &right, '-') {
817 return r;
818 }
819 if let Some(r) = modular_binop(&left, &right, "subtract", |a, b| a.sub(b)) {
820 return r;
821 }
822 if let Some(r) = complexf_binop(&left, &right, "subtract", |a, b| Some(a.sub(b))) {
823 return r;
824 }
825 if let Some(r) = complex_binop(&left, &right, "subtract", |a, b| a.sub(b)) {
826 return r;
827 }
828 if let Some(r) = decimal_binop(
829 &left,
830 &right,
831 |a, b| a.sub(b),
832 |a, b| a.sub(b),
833 |a, b| a - b,
834 ) {
835 return Ok(r);
836 }
837 match (&left, &right) {
838 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(match a.checked_sub(*b) {
839 Some(s) => RuntimeValue::Int(s),
840 None => RuntimeValue::from_bigint(BigInt::from_i64(*a).sub(&BigInt::from_i64(*b))),
841 }),
842 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
843 Ok(RuntimeValue::from_bigint(a.sub(b)))
844 }
845 (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
846 Ok(RuntimeValue::from_bigint(a.sub(&BigInt::from_i64(*b))))
847 }
848 (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
849 Ok(RuntimeValue::from_bigint(BigInt::from_i64(*a).sub(b)))
850 }
851 (RuntimeValue::Float(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(a - b)),
852 (RuntimeValue::Int(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(*a as f64 - b)),
853 (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Float(a - *b as f64)),
854 (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
855 Ok(RuntimeValue::Float(a.to_f64() - b))
856 }
857 (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
858 Ok(RuntimeValue::Float(a - b.to_f64()))
859 }
860 (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
861 Ok(RuntimeValue::from_rational(a.sub(b)))
862 }
863 (RuntimeValue::Rational(_), RuntimeValue::Int(_))
864 | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
865 | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
866 | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => Ok(RuntimeValue::from_rational(
867 rat_of(&left).unwrap().sub(&rat_of(&right).unwrap()),
868 )),
869 (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
870 Ok(RuntimeValue::Float(r.to_f64() - b))
871 }
872 (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
873 Ok(RuntimeValue::Float(a - r.to_f64()))
874 }
875 (RuntimeValue::Duration(a), RuntimeValue::Duration(b)) => {
876 Ok(RuntimeValue::Duration(a.wrapping_sub(*b)))
877 }
878 (
879 RuntimeValue::Date(days),
880 RuntimeValue::Span {
881 months,
882 days: span_days,
883 },
884 ) => Ok(RuntimeValue::Date(date_add_span(
885 *days,
886 -*months,
887 -*span_days,
888 ))),
889 (
891 RuntimeValue::Moment(nanos),
892 RuntimeValue::Span {
893 months,
894 days: span_days,
895 },
896 ) => Ok(RuntimeValue::Moment(super::temporal::moment_add_span(
897 *nanos,
898 -*months,
899 -*span_days,
900 ))),
901 (RuntimeValue::Moment(nanos), RuntimeValue::Duration(d)) => {
905 Ok(RuntimeValue::Moment(nanos.wrapping_sub(*d)))
906 }
907 _ => Err(format!(
908 "Cannot subtract {} from {}",
909 right.type_name(),
910 left.type_name()
911 )),
912 }
913}
914
915pub fn power(base: RuntimeValue, exp: RuntimeValue) -> Result<RuntimeValue, String> {
921 if let Some(r) = exact::arith(exact::Op::Pow, &base, &exp, &exact_recurse) {
922 return r;
923 }
924 if matches!(base, RuntimeValue::Float(_)) || matches!(exp, RuntimeValue::Float(_)) {
926 let b = num_f64(&base)
927 .ok_or_else(|| format!("cannot raise {} to a power", base.type_name()))?;
928 let e =
929 num_f64(&exp).ok_or_else(|| format!("cannot raise to a {} power", exp.type_name()))?;
930 return Ok(RuntimeValue::Float(b.powf(e)));
931 }
932 match (&base, &exp) {
933 (RuntimeValue::Int(b), RuntimeValue::Int(e)) => int_power(*b, *e),
934 (RuntimeValue::BigInt(b), RuntimeValue::Int(e)) => {
935 let ue = u32::try_from(*e).map_err(|_| {
936 "negative or too-large exponent on an integer (use a Float base)".to_string()
937 })?;
938 Ok(RuntimeValue::from_bigint(b.pow(ue)))
939 }
940 (RuntimeValue::Rational(b), RuntimeValue::Int(e)) => {
941 let ie = i32::try_from(*e).map_err(|_| "exponent too large".to_string())?;
942 b.pow(ie)
943 .map(RuntimeValue::from_rational)
944 .ok_or_else(|| "zero raised to a negative power".to_string())
945 }
946 _ => Err(format!(
947 "cannot raise {} to the {} power",
948 base.type_name(),
949 exp.type_name()
950 )),
951 }
952}
953
954fn int_power(base: i64, exp: i64) -> Result<RuntimeValue, String> {
957 if exp < 0 {
958 return Err(
959 "negative exponent on an integer (an Int can't hold a fraction — use a Float base)"
960 .to_string(),
961 );
962 }
963 let e = u32::try_from(exp).map_err(|_| "exponent too large".to_string())?;
964 match base.checked_pow(e) {
965 Some(r) => Ok(RuntimeValue::Int(r)),
966 None => Ok(RuntimeValue::from_bigint(BigInt::from_i64(base).pow(e))),
967 }
968}
969
970pub fn multiply(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
971 if let Some(r) = exact::arith(exact::Op::Mul, &left, &right, &exact_recurse) {
972 return r;
973 }
974 if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
975 return a
976 .mul(*b)
977 .map(RuntimeValue::Word)
978 .ok_or_else(|| word_width_err(*a, *b));
979 }
980 if let (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) = (&left, &right) {
982 return a
983 .mullo(**b)
984 .map(|v| RuntimeValue::Lanes(std::rc::Rc::new(v)))
985 .ok_or_else(|| {
986 format!(
987 "cannot multiply {} and {} — lane op undefined",
988 a.type_name(),
989 b.type_name()
990 )
991 });
992 }
993 if let Some(r) = quantity_binop(&left, &right, '*') {
994 return r;
995 }
996 if let Some(r) = money_binop(&left, &right, '*') {
997 return r;
998 }
999 if let Some(r) = modular_binop(&left, &right, "multiply", |a, b| a.mul(b)) {
1000 return r;
1001 }
1002 if let Some(r) = complexf_binop(&left, &right, "multiply", |a, b| Some(a.mul(b))) {
1003 return r;
1004 }
1005 if let Some(r) = complex_binop(&left, &right, "multiply", |a, b| a.mul(b)) {
1006 return r;
1007 }
1008 if let Some(r) = decimal_binop(
1009 &left,
1010 &right,
1011 |a, b| a.mul(b),
1012 |a, b| a.mul(b),
1013 |a, b| a * b,
1014 ) {
1015 return Ok(r);
1016 }
1017 match (&left, &right) {
1018 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => Ok(match a.checked_mul(*b) {
1019 Some(p) => RuntimeValue::Int(p),
1020 None => RuntimeValue::from_bigint(BigInt::from_i64(*a).mul(&BigInt::from_i64(*b))),
1021 }),
1022 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => {
1023 Ok(RuntimeValue::from_bigint(a.mul(b)))
1024 }
1025 (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
1026 Ok(RuntimeValue::from_bigint(a.mul(&BigInt::from_i64(*b))))
1027 }
1028 (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => {
1029 Ok(RuntimeValue::from_bigint(BigInt::from_i64(*a).mul(b)))
1030 }
1031 (RuntimeValue::Float(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(a * b)),
1032 (RuntimeValue::Int(a), RuntimeValue::Float(b)) => Ok(RuntimeValue::Float(*a as f64 * b)),
1033 (RuntimeValue::Float(a), RuntimeValue::Int(b)) => Ok(RuntimeValue::Float(a * *b as f64)),
1034 (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
1035 Ok(RuntimeValue::Float(a.to_f64() * b))
1036 }
1037 (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
1038 Ok(RuntimeValue::Float(a * b.to_f64()))
1039 }
1040 (RuntimeValue::Rational(a), RuntimeValue::Rational(b)) => {
1041 Ok(RuntimeValue::from_rational(a.mul(b)))
1042 }
1043 (RuntimeValue::Rational(_), RuntimeValue::Int(_))
1044 | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
1045 | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
1046 | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => Ok(RuntimeValue::from_rational(
1047 rat_of(&left).unwrap().mul(&rat_of(&right).unwrap()),
1048 )),
1049 (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
1050 Ok(RuntimeValue::Float(r.to_f64() * b))
1051 }
1052 (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
1053 Ok(RuntimeValue::Float(a * r.to_f64()))
1054 }
1055 (RuntimeValue::List(items), RuntimeValue::Int(n))
1060 | (RuntimeValue::Int(n), RuntimeValue::List(items)) => {
1061 use crate::interpreter::ListRepr;
1062 let src = items.borrow().to_values();
1063 let count = (*n).max(0) as usize;
1064 let mut out = Vec::with_capacity(src.len() * count);
1065 for _ in 0..count {
1066 out.extend(src.iter().map(|v| v.deep_clone()));
1067 }
1068 Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
1069 ListRepr::from_values(out),
1070 ))))
1071 }
1072 _ => Err(format!(
1073 "Cannot multiply {} and {}",
1074 left.type_name(),
1075 right.type_name()
1076 )),
1077 }
1078}
1079
1080pub fn divide(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1081 if let Some(r) = exact::arith(exact::Op::Div, &left, &right, &exact_recurse) {
1082 return r;
1083 }
1084 if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
1085 if a.width() != b.width() {
1086 return Err(word_width_err(*a, *b));
1087 }
1088 if b.to_u64() == 0 {
1089 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1090 }
1091 return Ok(RuntimeValue::Word(a.div(*b).expect("width checked above")));
1092 }
1093 if let Some(r) = quantity_binop(&left, &right, '/') {
1094 return r;
1095 }
1096 if let Some(r) = money_binop(&left, &right, '/') {
1097 return r;
1098 }
1099 if matches!(left, RuntimeValue::Modular(_)) || matches!(right, RuntimeValue::Modular(_)) {
1102 return match (&left, &right) {
1103 (RuntimeValue::Modular(a), RuntimeValue::Modular(b)) => {
1104 if a.modulus() != b.modulus() {
1105 Err(logicaffeine_data::failure::modular_rings_differ("divide"))
1106 } else {
1107 a.div(b)
1108 .map(|r| RuntimeValue::Modular(Rc::new(r)))
1109 .ok_or_else(|| logicaffeine_data::failure::NO_MODULAR_INVERSE.to_string())
1110 }
1111 }
1112 _ => Err(format!(
1113 "Cannot divide {} by {}",
1114 left.type_name(),
1115 right.type_name()
1116 )),
1117 };
1118 }
1119 if let Some(r) = complexf_binop(&left, &right, "divide", |a, b| a.div(b)) {
1122 return r;
1123 }
1124 if matches!(left, RuntimeValue::Complex(_)) || matches!(right, RuntimeValue::Complex(_)) {
1126 return match (complex_of(&left), complex_of(&right)) {
1127 (Some(a), Some(b)) => a
1128 .div(&b)
1129 .map(|c| RuntimeValue::Complex(Rc::new(c)))
1130 .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string()),
1131 _ => Err(format!(
1132 "Cannot divide {} by {}",
1133 left.type_name(),
1134 right.type_name()
1135 )),
1136 };
1137 }
1138 if matches!(left, RuntimeValue::Decimal(_)) || matches!(right, RuntimeValue::Decimal(_)) {
1141 if let (Some(a), Some(b)) = (rat_of(&left), rat_of(&right)) {
1142 return a
1143 .div(&b)
1144 .map(RuntimeValue::from_rational)
1145 .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1146 }
1147 if let (Some(a), Some(b)) = (num_f64(&left), num_f64(&right)) {
1148 if b == 0.0 {
1149 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1150 }
1151 return Ok(RuntimeValue::Float(a / b));
1152 }
1153 }
1154 match (&left, &right) {
1155 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
1156 if *b == 0 {
1157 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1158 }
1159 Ok(match a.checked_div(*b) {
1162 Some(q) => RuntimeValue::Int(q),
1163 None => RuntimeValue::from_bigint(int_div(*a, *b).0),
1164 })
1165 }
1166 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1167 a.div_rem(b).expect("BigInt divisor is never zero").0,
1168 )),
1169 (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
1170 if *b == 0 {
1171 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1172 }
1173 Ok(RuntimeValue::from_bigint(
1174 a.div_rem(&BigInt::from_i64(*b)).unwrap().0,
1175 ))
1176 }
1177 (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1178 BigInt::from_i64(*a).div_rem(b).unwrap().0,
1179 )),
1180 (RuntimeValue::Float(a), RuntimeValue::Float(b)) => {
1181 if *b == 0.0 {
1182 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1183 }
1184 Ok(RuntimeValue::Float(a / b))
1185 }
1186 (RuntimeValue::Int(a), RuntimeValue::Float(b)) => {
1187 if *b == 0.0 {
1188 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1189 }
1190 Ok(RuntimeValue::Float(*a as f64 / b))
1191 }
1192 (RuntimeValue::Float(a), RuntimeValue::Int(b)) => {
1193 if *b == 0 {
1194 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1195 }
1196 Ok(RuntimeValue::Float(a / *b as f64))
1197 }
1198 (RuntimeValue::BigInt(a), RuntimeValue::Float(b)) => {
1199 if *b == 0.0 {
1200 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1201 }
1202 Ok(RuntimeValue::Float(a.to_f64() / b))
1203 }
1204 (RuntimeValue::Float(a), RuntimeValue::BigInt(b)) => {
1205 Ok(RuntimeValue::Float(a / b.to_f64()))
1206 }
1207 (RuntimeValue::Rational(_), RuntimeValue::Rational(_))
1210 | (RuntimeValue::Rational(_), RuntimeValue::Int(_))
1211 | (RuntimeValue::Int(_), RuntimeValue::Rational(_))
1212 | (RuntimeValue::Rational(_), RuntimeValue::BigInt(_))
1213 | (RuntimeValue::BigInt(_), RuntimeValue::Rational(_)) => rat_of(&left)
1214 .unwrap()
1215 .div(&rat_of(&right).unwrap())
1216 .map(RuntimeValue::from_rational)
1217 .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string()),
1218 (RuntimeValue::Rational(r), RuntimeValue::Float(b)) => {
1219 if *b == 0.0 {
1220 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1221 }
1222 Ok(RuntimeValue::Float(r.to_f64() / b))
1223 }
1224 (RuntimeValue::Float(a), RuntimeValue::Rational(r)) => {
1225 Ok(RuntimeValue::Float(a / r.to_f64()))
1226 }
1227 _ => Err(format!(
1228 "Cannot divide {} by {}",
1229 left.type_name(),
1230 right.type_name()
1231 )),
1232 }
1233}
1234
1235fn int_div(a: i64, b: i64) -> (BigInt, BigInt) {
1238 BigInt::from_i64(a)
1239 .div_rem(&BigInt::from_i64(b))
1240 .expect("nonzero divisor")
1241}
1242
1243pub fn floor_divide(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1249 if let Some(r) = exact::arith(exact::Op::FloorDiv, &left, &right, &exact_recurse) {
1250 return r;
1251 }
1252 if matches!(left, RuntimeValue::Float(_)) || matches!(right, RuntimeValue::Float(_)) {
1254 if let (Some(a), Some(b)) = (num_f64(&left), num_f64(&right)) {
1255 if b == 0.0 {
1256 return Err(logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1257 }
1258 return Ok(RuntimeValue::Float((a / b).floor()));
1259 }
1260 }
1261 if let (Some(a), Some(b)) = (rat_of(&left), rat_of(&right)) {
1264 return a
1265 .div(&b)
1266 .map(|q| RuntimeValue::from_bigint(q.floor()))
1267 .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string());
1268 }
1269 Err(format!(
1270 "Cannot floor-divide {} by {}",
1271 left.type_name(),
1272 right.type_name()
1273 ))
1274}
1275
1276pub fn exact_divide(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1282 if let Some(r) = exact::arith(exact::Op::ExactDiv, &left, &right, &exact_recurse) {
1283 return r;
1284 }
1285 match (&left, &right) {
1286 (a, b) if rat_of(a).is_some() && rat_of(b).is_some() => rat_of(&left)
1289 .unwrap()
1290 .div(&rat_of(&right).unwrap())
1291 .map(RuntimeValue::from_rational)
1292 .ok_or_else(|| logicaffeine_data::failure::DIVISION_BY_ZERO.to_string()),
1293 (RuntimeValue::Float(_), _) | (_, RuntimeValue::Float(_)) => divide(left, right),
1296 _ => Err(format!(
1297 "Cannot divide {} by {}",
1298 left.type_name(),
1299 right.type_name()
1300 )),
1301 }
1302}
1303
1304pub fn modulo(left: RuntimeValue, right: RuntimeValue) -> Result<RuntimeValue, String> {
1305 if let Some(r) = exact::arith(exact::Op::Mod, &left, &right, &exact_recurse) {
1306 return r;
1307 }
1308 if let (RuntimeValue::Word(a), RuntimeValue::Word(b)) = (&left, &right) {
1309 if a.width() != b.width() {
1310 return Err(word_width_err(*a, *b));
1311 }
1312 if b.to_u64() == 0 {
1313 return Err(logicaffeine_data::failure::MODULO_BY_ZERO.to_string());
1314 }
1315 return Ok(RuntimeValue::Word(a.rem(*b).expect("width checked above")));
1316 }
1317 match (&left, &right) {
1318 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => {
1319 if *b == 0 {
1320 return Err(logicaffeine_data::failure::MODULO_BY_ZERO.to_string());
1321 }
1322 Ok(RuntimeValue::Int(a.checked_rem(*b).unwrap_or(0)))
1324 }
1325 (RuntimeValue::BigInt(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1326 a.div_rem(b).expect("BigInt divisor is never zero").1,
1327 )),
1328 (RuntimeValue::BigInt(a), RuntimeValue::Int(b)) => {
1329 if *b == 0 {
1330 return Err(logicaffeine_data::failure::MODULO_BY_ZERO.to_string());
1331 }
1332 Ok(RuntimeValue::from_bigint(
1333 a.div_rem(&BigInt::from_i64(*b)).unwrap().1,
1334 ))
1335 }
1336 (RuntimeValue::Int(a), RuntimeValue::BigInt(b)) => Ok(RuntimeValue::from_bigint(
1337 BigInt::from_i64(*a).div_rem(b).unwrap().1,
1338 )),
1339 _ => Err(format!(
1340 "Cannot compute modulo of {} and {}",
1341 left.type_name(),
1342 right.type_name()
1343 )),
1344 }
1345}
1346
1347pub fn crdt_counter_bump(
1352 current: RuntimeValue,
1353 amount: i64,
1354 field_name: &str,
1355) -> Result<RuntimeValue, String> {
1356 match current {
1357 RuntimeValue::Crdt(rc) => {
1361 let mut cv = rc.borrow().clone();
1362 cv.bump(amount)?;
1363 Ok(RuntimeValue::Crdt(std::rc::Rc::new(
1364 std::cell::RefCell::new(cv),
1365 )))
1366 }
1367 RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n.wrapping_add(amount))),
1368 RuntimeValue::Nothing => Ok(RuntimeValue::Int(amount)),
1369 _ => Err(format!("Field '{}' is not a counter", field_name)),
1370 }
1371}
1372
1373pub const GCOUNTER_TAG: &str = "__GCounter";
1382
1383pub fn gcounter_value(v: &RuntimeValue) -> Option<i64> {
1386 match v {
1387 RuntimeValue::Struct(s) if s.type_name == GCOUNTER_TAG => Some(
1388 s.fields
1389 .values()
1390 .map(|c| if let RuntimeValue::Int(n) = c { *n } else { 0 })
1391 .fold(0i64, i64::wrapping_add),
1392 ),
1393 _ => None,
1394 }
1395}
1396
1397pub fn crdt_merge_field(current: &RuntimeValue, incoming: RuntimeValue) -> RuntimeValue {
1398 match (current, &incoming) {
1399 (RuntimeValue::Struct(a), RuntimeValue::Struct(b))
1404 if a.type_name == GCOUNTER_TAG && b.type_name == GCOUNTER_TAG =>
1405 {
1406 let mut fields = a.fields.clone();
1407 for (replica, count) in &b.fields {
1408 let next = match (fields.get(replica), count) {
1409 (Some(RuntimeValue::Int(x)), RuntimeValue::Int(y)) => {
1410 RuntimeValue::Int((*x).max(*y))
1411 }
1412 _ => count.clone(),
1413 };
1414 fields.insert(replica.clone(), next);
1415 }
1416 RuntimeValue::Struct(Box::new(crate::interpreter::StructValue {
1417 type_name: GCOUNTER_TAG.to_string(),
1418 fields,
1419 }))
1420 }
1421 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => RuntimeValue::Int(a.wrapping_add(*b)),
1422 (RuntimeValue::Set(_), RuntimeValue::Set(_)) => {
1423 crate::semantics::collections::union(current, &incoming).unwrap_or(incoming)
1424 }
1425 (RuntimeValue::Map(a), RuntimeValue::Map(b)) => {
1430 let mut out = a.borrow().clone();
1431 for (k, v) in b.borrow().iter() {
1432 let merged = match out.get(k) {
1433 Some(cur) => crdt_merge_field(cur, v.clone()),
1434 None => v.clone(),
1435 };
1436 out.insert(k.clone(), merged);
1437 }
1438 RuntimeValue::Map(std::rc::Rc::new(std::cell::RefCell::new(out)))
1439 }
1440 (RuntimeValue::Crdt(a), RuntimeValue::Crdt(b)) => {
1445 let mut merged = a.borrow().clone();
1446 let _ = merged.merge(&b.borrow());
1447 RuntimeValue::Crdt(std::rc::Rc::new(std::cell::RefCell::new(merged)))
1448 }
1449 (RuntimeValue::Crdt(a), _) if a.borrow().counter_value().is_some() => {
1456 RuntimeValue::Crdt(a.clone())
1457 }
1458 _ => incoming,
1459 }
1460}
1461
1462pub fn crdt_join_field(current: &RuntimeValue, incoming: RuntimeValue) -> RuntimeValue {
1466 match (current, &incoming) {
1467 (RuntimeValue::Int(a), RuntimeValue::Int(b)) => RuntimeValue::Int((*a).max(*b)),
1468 _ => crdt_merge_field(current, incoming),
1469 }
1470}
1471
1472fn field_to_json(value: &RuntimeValue) -> Option<serde_json::Value> {
1476 use serde_json::{json, Value};
1477 Some(match value {
1478 RuntimeValue::Int(n) => json!(n),
1479 RuntimeValue::Bool(b) => json!(b),
1480 RuntimeValue::Float(f) => json!(f),
1481 RuntimeValue::Text(s) => json!(s.as_str()),
1482 RuntimeValue::Nothing => Value::Null,
1483 RuntimeValue::Set(items) => {
1484 Value::Array(items.borrow().iter().filter_map(field_to_json).collect())
1485 }
1486 RuntimeValue::Map(m) => {
1489 let pairs: Vec<Value> = m
1490 .borrow()
1491 .iter()
1492 .filter_map(|(k, v)| Some(Value::Array(vec![field_to_json(k)?, field_to_json(v)?])))
1493 .collect();
1494 json!({ "__map": pairs })
1495 }
1496 RuntimeValue::Crdt(rc) => match rc.borrow().counter_value() {
1501 Some(n) => json!(n),
1502 None => return None,
1503 },
1504 _ => return None,
1505 })
1506}
1507
1508fn field_from_json(value: &serde_json::Value) -> RuntimeValue {
1511 use serde_json::Value;
1512 match value {
1513 Value::Bool(b) => RuntimeValue::Bool(*b),
1514 Value::String(s) => RuntimeValue::Text(std::rc::Rc::new(s.clone())),
1515 Value::Number(n) => match n.as_i64() {
1516 Some(i) => RuntimeValue::Int(i),
1517 None => RuntimeValue::Float(n.as_f64().unwrap_or(0.0)),
1518 },
1519 Value::Array(items) => RuntimeValue::Set(std::rc::Rc::new(std::cell::RefCell::new(
1520 items.iter().map(field_from_json).collect(),
1521 ))),
1522 Value::Object(o) if o.contains_key("__map") => {
1524 let mut map = crate::interpreter::MapStorage::default();
1525 if let Some(Value::Array(pairs)) = o.get("__map") {
1526 for p in pairs {
1527 if let Value::Array(kv) = p {
1528 if kv.len() == 2 {
1529 map.insert(field_from_json(&kv[0]), field_from_json(&kv[1]));
1530 }
1531 }
1532 }
1533 }
1534 RuntimeValue::Map(std::rc::Rc::new(std::cell::RefCell::new(map)))
1535 }
1536 _ => RuntimeValue::Nothing,
1537 }
1538}
1539
1540pub fn crdt_to_wire(value: &RuntimeValue) -> Option<Vec<u8>> {
1545 use serde_json::{Map, Value};
1546 let mut map = Map::new();
1547 match value {
1548 RuntimeValue::Nothing => return None,
1549 RuntimeValue::Struct(s) => {
1550 for (k, v) in &s.fields {
1551 if let Some(j) = field_to_json(v) {
1552 map.insert(k.clone(), j);
1553 }
1554 }
1555 }
1556 other => match field_to_json(other) {
1558 Some(j) => {
1559 map.insert(String::new(), j);
1560 }
1561 None => return None,
1562 },
1563 }
1564 serde_json::to_vec(&Value::Object(map)).ok()
1565}
1566
1567pub fn crdt_merge_wire(local: RuntimeValue, bytes: &[u8]) -> RuntimeValue {
1572 let Ok(serde_json::Value::Object(map)) = serde_json::from_slice::<serde_json::Value>(bytes)
1573 else {
1574 return local;
1575 };
1576 match local {
1577 RuntimeValue::Struct(mut s) => {
1578 for (k, v) in map {
1579 let incoming = field_from_json(&v);
1580 let current = s.fields.get(&k).cloned().unwrap_or(RuntimeValue::Nothing);
1581 s.fields.insert(k, crdt_merge_field(¤t, incoming));
1582 }
1583 RuntimeValue::Struct(s)
1584 }
1585 other => match map.get("") {
1586 Some(v) => crdt_merge_field(&other, field_from_json(v)),
1587 None => other,
1588 },
1589 }
1590}
1591
1592pub fn not_value(val: RuntimeValue) -> Result<RuntimeValue, String> {
1594 if let Some(r) = exact::not(&val, ¬_value) {
1595 return r;
1596 }
1597 Ok(RuntimeValue::Bool(!val.is_truthy()))
1598}
1599
1600#[cfg(test)]
1601#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/tests.rs"]
1602mod tests;
1603
1604#[cfg(test)]
1605#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/bigint_exact_arithmetic.rs"]
1606mod bigint_exact_arithmetic;
1607
1608#[cfg(test)]
1609#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/rational_exact_arithmetic.rs"]
1610mod rational_exact_arithmetic;
1611
1612#[cfg(test)]
1613#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/arith/word_tests.rs"]
1614mod word_tests;