Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/calc.rs

24.0 KiB, 1 run

created by r1870400018:63218, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// U3 owns this file. The `calc` module: `define` binds `calc` to a module whose scope holds these, plus
2// `pi`, `tau`, `e` and `inf` (Typst has no `calc.nan`; `float.nan` is the type's). `erf` is FreeBSD's
3// `s_erf.c`, the implementation Rust's `libm` ports, so results agree with Typst to the last bit.
4
5use crate::diag::DiagnosticKind;
6use crate::eval::args::Args;
7use crate::eval::func::{
8 Func,
9 NativeFunc,
10};
11use crate::eval::lib::decimal::Decimal;
12use crate::eval::lib::foundations::{
13 finish,
14 mismatch,
15 need,
16 round_with_precision,
17 words,
18};
19use crate::eval::ops;
20use crate::eval::scope::Scope;
21use crate::eval::value::{
22 Angle,
23 Fraction,
24 Length,
25 Module,
26 Ratio,
27 Value,
28};
29use crate::eval::Engine;
30use crate::syntax::Span;
31
32use oxedyne_fe2o3_core::prelude::*;
33
34use std::cmp::Ordering;
35use std::sync::Arc;
36
37native_fns! {
38 pub enum CalcFn {
39 Abs => "abs",
40 Pow => "pow",
41 Exp => "exp",
42 Sqrt => "sqrt",
43 Root => "root",
44 Sin => "sin",
45 Cos => "cos",
46 Tan => "tan",
47 Asin => "asin",
48 Acos => "acos",
49 Atan => "atan",
50 Atan2 => "atan2",
51 Sinh => "sinh",
52 Cosh => "cosh",
53 Tanh => "tanh",
54 Asinh => "asinh",
55 Acosh => "acosh",
56 Atanh => "atanh",
57 Log => "log",
58 Ln => "ln",
59 Erf => "erf",
60 Fact => "fact",
61 Perm => "perm",
62 Binom => "binom",
63 Gcd => "gcd",
64 Lcm => "lcm",
65 Floor => "floor",
66 Ceil => "ceil",
67 Trunc => "trunc",
68 Fract => "fract",
69 Round => "round",
70 Clamp => "clamp",
71 Min => "min",
72 Max => "max",
73 Even => "even",
74 Odd => "odd",
75 Rem => "rem",
76 DivEuclid => "div-euclid",
77 RemEuclid => "rem-euclid",
78 Quo => "quo",
79 Norm => "norm",
80 }
81}
82
83pub fn define(scope: &mut Scope) {
84 let mut s = Scope::new();
85 for (n, f) in CalcFn::ALL.iter().enumerate() {
86 crate::eval::lib::foundations::define_nth(&mut s, n, f.name(), Value::Func(Func::Native(NativeFunc::Calc(*f))));
87 }
88 let n = CalcFn::ALL.len();
89 crate::eval::lib::foundations::define_nth(&mut s, n, "inf", Value::Float(f64::INFINITY));
90 crate::eval::lib::foundations::define_nth(&mut s, n + 1, "pi", Value::Float(std::f64::consts::PI));
91 crate::eval::lib::foundations::define_nth(&mut s, n + 2, "tau", Value::Float(std::f64::consts::TAU));
92 crate::eval::lib::foundations::define_nth(&mut s, n + 3, "e", Value::Float(std::f64::consts::E));
93 scope.define("calc", Value::Module(Arc::new(Module::new("calc", s))));
94}
95
96// A number argument as Typst's `DecNum`: an int, a float or a decimal, kept apart. The functions that
97// take Typst's plain `Num` read it through `arg_float`, which refuses a decimal.
98#[derive(Clone, Copy, Debug)]
99enum Num {
100 Int(i64),
101 Float(f64),
102 Decimal(Decimal),
103}
104
105impl Num {
106 fn float(self) -> Option<f64> {
107 match self {
108 Num::Int(i) => Some(i as f64),
109 Num::Float(f) => Some(f),
110 Num::Decimal(_) => None,
111 }
112 }
113
114 fn decimal(self) -> Option<Decimal> {
115 match self {
116 Num::Int(i) => Some(Decimal::from(i)),
117 Num::Float(_) => None,
118 Num::Decimal(d) => Some(d),
119 }
120 }
121
122 fn is_zero(self) -> bool {
123 match self {
124 Num::Int(i) => i == 0,
125 Num::Float(f) => f == 0.0,
126 Num::Decimal(d) => d.is_zero(),
127 }
128 }
129}
130
131fn num(engine: &mut Engine, span: Span, v: Value) -> Outcome<Num> {
132 match v {
133 Value::Int(i) => Ok(Num::Int(i)),
134 Value::Float(f) => Ok(Num::Float(f)),
135 Value::Decimal(d) => Ok(Num::Decimal(d)),
136 other => Err(mismatch(engine, span, "integer, float, or decimal", &other)),
137 }
138}
139
140fn arg_num(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<Num> {
141 let v = res!(need(engine, args, what));
142 num(engine, args.span, v)
143}
144
145// An int or a float as `f64`, for the functions Typst gives no decimal form.
146fn float_of(engine: &mut Engine, span: Span, v: Value) -> Outcome<f64> {
147 match v {
148 Value::Int(i) => Ok(i as f64),
149 Value::Float(f) => Ok(f),
150 other => Err(mismatch(engine, span, "integer or float", &other)),
151 }
152}
153
154fn arg_float(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<f64> {
155 let v = res!(need(engine, args, what));
156 float_of(engine, args.span, v)
157}
158
159fn decimal_and_float(engine: &mut Engine, span: Span) -> Error<ErrTag> {
160 engine.error_hint(DiagnosticKind::Type, span, "cannot apply this operation to a decimal and a float",
161 "if loss of precision is acceptable, explicitly cast the decimal to a float with `float(value)`")
162}
163
164fn arg_int(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<i64> {
165 let v = res!(need(engine, args, what));
166 match v {
167 Value::Int(i) => Ok(i),
168 other => Err(mismatch(engine, args.span, "integer", &other)),
169 }
170}
171
172// A non-negative integer, as Typst's `u64` parameters demand.
173fn arg_nat(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<u64> {
174 let i = res!(arg_int(engine, args, what));
175 if i < 0 {
176 return Err(engine.error(DiagnosticKind::Type, args.span, "number must be at least zero"));
177 }
178 Ok(i as u64)
179}
180
181// An angle or a plain number of radians.
182fn arg_angle(engine: &mut Engine, args: &mut Args) -> Outcome<f64> {
183 let v = res!(need(engine, args, "angle"));
184 match v {
185 Value::Angle(a) => Ok(a.0),
186 Value::Int(i) => Ok(i as f64),
187 Value::Float(f) => Ok(f),
188 other => Err(mismatch(engine, args.span, "angle, integer, or float", &other)),
189 }
190}
191
192fn too_large(engine: &mut Engine, span: Span) -> Error<ErrTag> { engine.error(DiagnosticKind::Type, span, "the result is too large") }
193
194fn not_real(engine: &mut Engine, span: Span) -> Error<ErrTag> { engine.error(DiagnosticKind::Type, span, "the result is not a real number") }
195
196pub fn call(f: CalcFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
197 let span = args.span;
198 let out = match f {
199 CalcFn::Abs => {
200 let v = res!(need(engine, &mut args, "value"));
201 match v {
202 Value::Int(i) => match i.checked_abs() {
203 Some(a) => Value::Int(a),
204 None => return Err(too_large(engine, span)),
205 },
206 Value::Float(x) => Value::Float(x.abs()),
207 Value::Decimal(d) => Value::Decimal(d.abs()),
208 Value::Length(l) => Value::Length(Length { abs: l.abs.abs(), em: l.em.abs() }),
209 Value::Angle(a) => Value::Angle(Angle(a.0.abs())),
210 Value::Ratio(r) => Value::Ratio(Ratio(r.0.abs())),
211 Value::Fraction(x) => Value::Fraction(Fraction(x.0.abs())),
212 other => return Err(mismatch(engine, span,
213 "integer, float, length, angle, ratio, fraction, or decimal", &other)),
214 }
215 }
216 CalcFn::Pow => {
217 let base = res!(arg_num(engine, &mut args, "base"));
218 let exp = res!(need(engine, &mut args, "exponent"));
219 let exp = match exp {
220 Value::Int(i) => Num::Int(i),
221 other => Num::Float(res!(float_of(engine, span, other))),
222 };
223 res!(pow(engine, span, base, exp))
224 }
225 CalcFn::Exp => {
226 let x = res!(arg_float(engine, &mut args, "exponent"));
227 let r = x.exp();
228 if r.is_nan() {
229 return Err(not_real(engine, span));
230 }
231 Value::Float(r)
232 }
233 CalcFn::Sqrt => {
234 let x = res!(arg_float(engine, &mut args, "value"));
235 if x < 0.0 {
236 return Err(engine.error(DiagnosticKind::Type, span, "cannot take square root of negative number"));
237 }
238 Value::Float(x.sqrt())
239 }
240 CalcFn::Root => {
241 let r = res!(arg_float(engine, &mut args, "radicand"));
242 let n = res!(arg_int(engine, &mut args, "index"));
243 if n == 0 {
244 return Err(engine.error(DiagnosticKind::Type, span, "cannot take the 0th root of a number"));
245 }
246 if r < 0.0 {
247 if n % 2 == 0 {
248 return Err(engine.error(DiagnosticKind::Type, span,
249 "negative numbers do not have a real nth root when n is even"));
250 }
251 Value::Float(-(-r).powf(1.0 / n as f64))
252 } else if n == 1 {
253 Value::Float(r)
254 } else if n == 2 {
255 Value::Float(r.sqrt())
256 } else if n == 3 {
257 Value::Float(r.cbrt())
258 } else {
259 Value::Float(r.powf(1.0 / n as f64))
260 }
261 }
262 CalcFn::Sin => Value::Float(res!(arg_angle(engine, &mut args)).sin()),
263 CalcFn::Cos => Value::Float(res!(arg_angle(engine, &mut args)).cos()),
264 CalcFn::Tan => Value::Float(res!(arg_angle(engine, &mut args)).tan()),
265 CalcFn::Asin | CalcFn::Acos => {
266 let x = res!(arg_float(engine, &mut args, "value"));
267 if !(-1.0..=1.0).contains(&x) {
268 return Err(engine.error(DiagnosticKind::Type, span, "value must be between -1 and 1"));
269 }
270 Value::Angle(Angle(if f == CalcFn::Asin { x.asin() } else { x.acos() }))
271 }
272 CalcFn::Atan => Value::Angle(Angle(res!(arg_float(engine, &mut args, "value")).atan())),
273 CalcFn::Atan2 => {
274 let x = res!(arg_float(engine, &mut args, "x"));
275 let y = res!(arg_float(engine, &mut args, "y"));
276 Value::Angle(Angle(y.atan2(x)))
277 }
278 CalcFn::Sinh => Value::Float(res!(arg_float(engine, &mut args, "value")).sinh()),
279 CalcFn::Cosh => Value::Float(res!(arg_float(engine, &mut args, "value")).cosh()),
280 CalcFn::Tanh => Value::Float(res!(arg_float(engine, &mut args, "value")).tanh()),
281 CalcFn::Asinh => Value::Float(res!(arg_float(engine, &mut args, "value")).asinh()),
282 CalcFn::Acosh => {
283 let x = res!(arg_float(engine, &mut args, "value"));
284 if x < 1.0 {
285 return Err(engine.error(DiagnosticKind::Type, span, "value must be greater than or equal to 1"));
286 }
287 Value::Float(x.acosh())
288 }
289 CalcFn::Atanh => {
290 let x = res!(arg_float(engine, &mut args, "value"));
291 if x <= -1.0 || x >= 1.0 {
292 return Err(engine.error(DiagnosticKind::Type, span, "value must be between -1 and 1 (exclusive)"));
293 }
294 Value::Float(x.atanh())
295 }
296 CalcFn::Log => {
297 let x = res!(arg_float(engine, &mut args, "value"));
298 let base = match res!(args.named::<Value>("base")) {
299 None => 10.0,
300 Some(v) => res!(float_of(engine, span, v)),
301 };
302 if x <= 0.0 {
303 return Err(engine.error(DiagnosticKind::Type, span, "value must be strictly positive"));
304 }
305 if !base.is_normal() {
306 return Err(engine.error(DiagnosticKind::Type, span, "base may not be zero, NaN, infinite, or subnormal"));
307 }
308 let r = if base == std::f64::consts::E {
309 x.ln()
310 } else if base == 2.0 {
311 x.log2()
312 } else if base == 10.0 {
313 x.log10()
314 } else {
315 x.ln() / base.ln()
316 };
317 if r.is_infinite() || r.is_nan() {
318 return Err(not_real(engine, span));
319 }
320 Value::Float(r)
321 }
322 CalcFn::Ln => {
323 let x = res!(arg_float(engine, &mut args, "value"));
324 if x <= 0.0 {
325 return Err(engine.error(DiagnosticKind::Type, span, "value must be strictly positive"));
326 }
327 let r = x.ln();
328 if r.is_infinite() {
329 return Err(not_real(engine, span));
330 }
331 Value::Float(r)
332 }
333 CalcFn::Erf => Value::Float(erf(res!(arg_float(engine, &mut args, "value")))),
334 CalcFn::Fact => {
335 let n = res!(arg_nat(engine, &mut args, "number"));
336 let mut acc: i64 = 1;
337 for k in 2..=n {
338 acc = match acc.checked_mul(k as i64) {
339 Some(x) => x,
340 None => return Err(too_large(engine, span)),
341 };
342 }
343 Value::Int(acc)
344 }
345 CalcFn::Perm => {
346 let base = res!(arg_nat(engine, &mut args, "base"));
347 let k = res!(arg_nat(engine, &mut args, "numbers"));
348 if base < k {
349 Value::Int(0)
350 } else {
351 let mut acc: i64 = 1;
352 for x in (base - k + 1)..=base {
353 acc = match acc.checked_mul(x as i64) {
354 Some(y) => y,
355 None => return Err(too_large(engine, span)),
356 };
357 }
358 Value::Int(acc)
359 }
360 }
361 CalcFn::Binom => {
362 let n = res!(arg_nat(engine, &mut args, "n"));
363 let k = res!(arg_nat(engine, &mut args, "k"));
364 if k > n {
365 Value::Int(0)
366 } else {
367 // Typst's order: multiply by (n - i), then divide by (i + 1), from the smaller side.
368 let k = k.min(n - k);
369 let mut acc: u64 = 1;
370 for i in 0..k {
371 acc = match acc.checked_mul(n - i) {
372 Some(y) => y / (i + 1),
373 None => return Err(too_large(engine, span)),
374 };
375 }
376 if acc > i64::MAX as u64 {
377 return Err(too_large(engine, span));
378 }
379 Value::Int(acc as i64)
380 }
381 }
382 CalcFn::Gcd => {
383 let a = res!(arg_int(engine, &mut args, "a"));
384 let b = res!(arg_int(engine, &mut args, "b"));
385 Value::Int(gcd(a, b))
386 }
387 CalcFn::Lcm => {
388 let a = res!(arg_int(engine, &mut args, "a"));
389 let b = res!(arg_int(engine, &mut args, "b"));
390 if a == b {
391 Value::Int(a.abs())
392 } else if a == 0 || b == 0 {
393 Value::Int(0)
394 } else {
395 match (a / gcd(a, b)).checked_mul(b).and_then(|x| x.checked_abs()) {
396 Some(x) => Value::Int(x),
397 None => return Err(too_large(engine, span)),
398 }
399 }
400 }
401 CalcFn::Floor | CalcFn::Ceil | CalcFn::Trunc => {
402 let n = res!(arg_num(engine, &mut args, "value"));
403 match n {
404 Num::Int(i) => Value::Int(i),
405 Num::Float(x) => {
406 let r = match f {
407 CalcFn::Floor => x.floor(),
408 CalcFn::Ceil => x.ceil(),
409 _ => x.trunc(),
410 };
411 res!(float_to_int(engine, span, r))
412 }
413 Num::Decimal(d) => {
414 let r = match f {
415 CalcFn::Floor => d.floor(),
416 CalcFn::Ceil => d.ceil(),
417 _ => d.trunc(),
418 };
419 match r.to_i64() {
420 Some(i) => Value::Int(i),
421 None => return Err(too_large(engine, span)),
422 }
423 }
424 }
425 }
426 CalcFn::Fract => match res!(arg_num(engine, &mut args, "value")) {
427 Num::Int(_) => Value::Int(0),
428 Num::Float(x) => Value::Float(x.fract()),
429 Num::Decimal(d) => Value::Decimal(d.fract()),
430 },
431 CalcFn::Round => {
432 let n = res!(arg_num(engine, &mut args, "value"));
433 let digits = match res!(args.named::<Value>("digits")) {
434 None => 0i64,
435 Some(Value::Int(d)) => d,
436 Some(other) => return Err(mismatch(engine, span, "integer", &other)),
437 };
438 let d = digits.clamp(i16::MIN as i64, i16::MAX as i64) as i16;
439 match n {
440 Num::Int(i) => match round_int_with_precision(i, d) {
441 Some(r) => Value::Int(r),
442 None => return Err(too_large(engine, span)),
443 },
444 Num::Float(x) => Value::Float(round_with_precision(x, d)),
445 Num::Decimal(x) => match x.round(digits.clamp(i32::MIN as i64, i32::MAX as i64)) {
446 Some(r) => Value::Decimal(r),
447 None => return Err(too_large(engine, span)),
448 },
449 }
450 }
451 CalcFn::Clamp => {
452 let v = res!(arg_num(engine, &mut args, "value"));
453 let lo = res!(arg_num(engine, &mut args, "min"));
454 let hi = res!(arg_num(engine, &mut args, "max"));
455 match (v, lo, hi) {
456 (Num::Int(v), Num::Int(lo), Num::Int(hi)) => {
457 if hi < lo {
458 return Err(engine.error(DiagnosticKind::Type, span, "max must be greater than or equal to min"));
459 }
460 Value::Int(v.clamp(lo, hi))
461 }
462 (Num::Decimal(_), _, _) | (_, Num::Decimal(_), _) | (_, _, Num::Decimal(_)) => {
463 // A decimal among them makes the others decimals; a float then cannot join.
464 let pair = (lo.decimal(), hi.decimal());
465 if let (Some(l), Some(h)) = pair {
466 if h < l {
467 return Err(engine.error(DiagnosticKind::Type, span, "max must be greater than or equal to min"));
468 }
469 }
470 match (v.decimal(), pair.0, pair.1) {
471 (Some(v), Some(l), Some(h)) => Value::Decimal(if v < l { l } else if v > h { h } else { v }),
472 _ => return Err(decimal_and_float(engine, span)),
473 }
474 }
475 _ => {
476 let (v, lo, hi) = (v.float().unwrap_or(0.0), lo.float().unwrap_or(0.0), hi.float().unwrap_or(0.0));
477 if hi < lo {
478 return Err(engine.error(DiagnosticKind::Type, span, "max must be greater than or equal to min"));
479 }
480 Value::Float(v.clamp(lo, hi))
481 }
482 }
483 }
484 CalcFn::Min | CalcFn::Max => {
485 let vals = res!(args.all::<Value>());
486 let goal = if f == CalcFn::Min { Ordering::Less } else { Ordering::Greater };
487 let mut it = vals.into_iter();
488 let mut ext = match it.next() {
489 Some(v) => v,
490 None => return Err(engine.error(DiagnosticKind::Type, span, "expected at least one value")),
491 };
492 for v in it {
493 let ord = match ops::compare(&v, &ext) {
494 Ok(o) => o,
495 Err(e) => return Err(engine.error(DiagnosticKind::Type, span, words(&e))),
496 };
497 if ord == goal {
498 ext = v;
499 }
500 }
501 ext
502 }
503 CalcFn::Even | CalcFn::Odd => {
504 let i = res!(arg_int(engine, &mut args, "value"));
505 Value::Bool((i % 2 == 0) == (f == CalcFn::Even))
506 }
507 CalcFn::Rem | CalcFn::DivEuclid | CalcFn::RemEuclid | CalcFn::Quo => {
508 let a = res!(arg_num(engine, &mut args, "dividend"));
509 let b = res!(arg_num(engine, &mut args, "divisor"));
510 if b.is_zero() {
511 return Err(engine.error(DiagnosticKind::Type, span, "divisor must not be zero"));
512 }
513 res!(division(engine, span, f, a, b))
514 }
515 CalcFn::Norm => {
516 let p = match res!(args.named::<Value>("p")) {
517 None => 2.0,
518 Some(v) => res!(float_of(engine, span, v)),
519 };
520 let vals = res!(args.all::<Value>());
521 let mut xs = Vec::with_capacity(vals.len());
522 for v in vals {
523 xs.push(res!(float_of(engine, span, v)));
524 }
525 if p <= 0.0 {
526 return Err(engine.error(DiagnosticKind::Type, span, "p must be greater than zero"));
527 }
528 if p.is_infinite() {
529 Value::Float(xs.iter().fold(0.0f64, |m, x| m.max(x.abs())))
530 } else {
531 Value::Float(xs.iter().map(|x| x.abs().powf(p)).sum::<f64>().powf(1.0 / p))
532 }
533 }
534 };
535 res!(finish(engine, args));
536 Ok(out)
537}
538
539fn float_to_int(engine: &mut Engine, span: Span, x: f64) -> Outcome<Value> {
540 if x.is_nan() {
541 return Ok(Value::Int(0));
542 }
543 if x < -9.223372036854776e18 || x >= 9.223372036854776e18 {
544 return Err(too_large(engine, span));
545 }
546 Ok(Value::Int(x as i64))
547}
548
549fn pow(engine: &mut Engine, span: Span, base: Num, exp: Num) -> Outcome<Value> {
550 if exp.is_zero() && base.is_zero() {
551 return Err(engine.error(DiagnosticKind::Type, span, "zero to the power of zero is undefined"));
552 }
553 match exp {
554 Num::Int(i) if i32::try_from(i).is_err()
555 => return Err(engine.error(DiagnosticKind::Type, span, "exponent is too large")),
556 Num::Float(x) if !x.is_normal() && x != 0.0
557 => return Err(engine.error(DiagnosticKind::Type, span, "exponent may not be infinite, subnormal, or NaN")),
558 _ => (),
559 }
560 if let (Num::Int(a), Num::Int(b)) = (base, exp) {
561 if b >= 0 {
562 return match a.checked_pow(b as u32) {
563 Some(r) => Ok(Value::Int(r)),
564 None => Err(too_large(engine, span)),
565 };
566 }
567 }
568 if let (Num::Decimal(a), Num::Int(b)) = (base, exp) {
569 return match a.checked_powi(b) {
570 Some(r) => Ok(Value::Decimal(r)),
571 None => Err(too_large(engine, span)),
572 };
573 }
574 let a = match base.float() {
575 Some(a) => a,
576 None => return Err(decimal_and_float(engine, span)),
577 };
578 let e = exp.float().unwrap_or(0.0);
579 let r = if a == std::f64::consts::E {
580 e.exp()
581 } else if a == 2.0 {
582 e.exp2()
583 } else if let Num::Int(b) = exp {
584 a.powi(b as i32)
585 } else {
586 a.powf(e)
587 };
588 if r.is_nan() {
589 return Err(not_real(engine, span));
590 }
591 Ok(Value::Float(r))
592}
593
594fn division(engine: &mut Engine, span: Span, f: CalcFn, a: Num, b: Num) -> Outcome<Value> {
595 match (a, b) {
596 (Num::Int(x), Num::Int(y)) => {
597 let r = match f {
598 CalcFn::Rem => if y == -1 { Some(0) } else { x.checked_rem(y) },
599 CalcFn::DivEuclid => x.checked_div_euclid(y),
600 CalcFn::RemEuclid => if y == -1 { Some(0) } else { x.checked_rem_euclid(y) },
601 _ => x.checked_div(y).map(|q| {
602 // Floor division: truncation rounds towards zero, so step down when signs differ.
603 if x % y != 0 && ((x < 0) != (y < 0)) { q - 1 } else { q }
604 }),
605 };
606 match r {
607 Some(v) => Ok(Value::Int(v)),
608 None => Err(too_large(engine, span)),
609 }
610 }
611 (Num::Decimal(_), _) | (_, Num::Decimal(_)) => {
612 let (x, y) = match (a.decimal(), b.decimal()) {
613 (Some(x), Some(y)) => (x, y),
614 _ => return Err(decimal_and_float(engine, span)),
615 };
616 let r = match f {
617 CalcFn::Rem => x.checked_rem(y),
618 CalcFn::DivEuclid => x.checked_div_euclid(y),
619 CalcFn::RemEuclid => x.checked_rem_euclid(y),
620 _ => x.checked_div(y).map(|q| q.floor()),
621 };
622 match (r, f) {
623 (Some(r), CalcFn::Quo) => match r.to_i64() {
624 Some(i) => Ok(Value::Int(i)),
625 None => Err(too_large(engine, span)),
626 },
627 (Some(r), _) => Ok(Value::Decimal(r)),
628 (None, CalcFn::Rem | CalcFn::RemEuclid)
629 => Err(engine.error(DiagnosticKind::Type, span, "dividend too small compared to divisor")),
630 (None, _) => Err(too_large(engine, span)),
631 }
632 }
633 _ => {
634 let (x, y) = (a.float().unwrap_or(0.0), b.float().unwrap_or(1.0));
635 match f {
636 CalcFn::Rem => Ok(Value::Float(x % y)),
637 CalcFn::DivEuclid => Ok(Value::Float(x.div_euclid(y))),
638 CalcFn::RemEuclid => Ok(Value::Float(x.rem_euclid(y))),
639 _ => float_to_int(engine, span, (x / y).floor()),
640 }
641 }
642 }
643}
644
645fn gcd(a: i64, b: i64) -> i64 {
646 let (mut a, mut b) = (a, b);
647 while b != 0 {
648 let t = b;
649 b = a % b;
650 a = t;
651 }
652 a.abs()
653}
654
655fn round_int_with_precision(value: i64, precision: i16) -> Option<i64> {
656 if precision >= 0 {
657 return Some(value);
658 }
659 let digits = (-(precision as i32)) as u32;
660 let ten = match 10i64.checked_pow(digits - 1) {
661 Some(t) => t,
662 None => return Some(0),
663 };
664 let truncated = value / ten;
665 if truncated == 0 {
666 return Some(0);
667 }
668 let last = (truncated % 10).abs();
669 let rounded = if last >= 5 {
670 match truncated.checked_add(truncated.signum() * (10 - last)) {
671 Some(r) => r,
672 None => return None,
673 }
674 } else {
675 truncated - (truncated % 10)
676 };
677 rounded.checked_mul(ten)
678}
679
680// erf, after FreeBSD's s_erf.c (Sun Microsystems, 1993; freely redistributable with notice).
681
682const ERX: f64 = 8.45062911510467529297e-01;
683const EFX8: f64 = 1.02703333676410069053e+00;
684const PP: [f64; 5] = [1.28379167095512558561e-01, -3.25042107247001499370e-01,
685 -2.84817495755985104766e-02, -5.77027029648944159157e-03, -2.37630166566501626084e-05];
686const QQ: [f64; 5] = [3.97917223959155352819e-01, 6.50222499887672944485e-02,
687 5.08130628187576562776e-03, 1.32494738004321644526e-04, -3.96022827877536812320e-06];
688const PA: [f64; 7] = [-2.36211856075265944077e-03, 4.14856118683748331666e-01,
689 -3.72207876035701323847e-01, 3.18346619901161753674e-01, -1.10894694282396677476e-01,
690 3.54783043256182359371e-02, -2.16637559486879084300e-03];
691const QA: [f64; 6] = [1.06420880400844228286e-01, 5.40397917702171048937e-01,
692 7.18286544141962662868e-02, 1.26171219808761642112e-01, 1.36370839120290507362e-02,
693 1.19844998467991074170e-02];
694const RA: [f64; 8] = [-9.86494403484714822705e-03, -6.93858572707181764372e-01,
695 -1.05586262253232909814e+01, -6.23753324503260060396e+01, -1.62396669462573470355e+02,
696 -1.84605092906711035994e+02, -8.12874355063065934246e+01, -9.81432934416914548592e+00];
697const SA: [f64; 8] = [1.96512716674392571292e+01, 1.37657754143519042600e+02,
698 4.34565877475229228821e+02, 6.45387271733267880336e+02, 4.29008140027567833386e+02,
699 1.08635005541779435134e+02, 6.57024977031928170135e+00, -6.04244152148580987438e-02];
700const RB: [f64; 7] = [-9.86494292470009928597e-03, -7.99283237680523006574e-01,
701 -1.77579549177547519889e+01, -1.60636384855821916062e+02, -6.37566443368389627722e+02,
702 -1.02509513161107724954e+03, -4.83519191608651397019e+02];
703const SB: [f64; 7] = [3.03380607434824582924e+01, 3.25792512996573918826e+02,
704 1.53672958608443695994e+03, 3.19985821950859553908e+03, 2.55305040643316442583e+03,
705 4.74528541206955367215e+02, -2.24409524465858183362e+01];
706
707fn erf(x: f64) -> f64 {
708 let bits = x.to_bits();
709 let hx = (bits >> 32) as u32;
710 let sign = hx >> 31;
711 let ix = hx & 0x7fff_ffff;
712 if ix >= 0x7ff0_0000 {
713 // erf(nan) is nan, erf(+-inf) is +-1.
714 return 1.0 - 2.0 * sign as f64 + 1.0 / x;
715 }
716 if ix < 0x3feb_0000 {
717 // |x| < 0.84375
718 if ix < 0x3e30_0000 {
719 // |x| < 2**-28
720 return 0.125 * (8.0 * x + EFX8 * x);
721 }
722 let z = x * x;
723 let r = PP[0] + z * (PP[1] + z * (PP[2] + z * (PP[3] + z * PP[4])));
724 let s = 1.0 + z * (QQ[0] + z * (QQ[1] + z * (QQ[2] + z * (QQ[3] + z * QQ[4]))));
725 return x + x * (r / s);
726 }
727 if ix < 0x3ff4_0000 {
728 // 0.84375 <= |x| < 1.25
729 let s = x.abs() - 1.0;
730 let p = PA[0] + s * (PA[1] + s * (PA[2] + s * (PA[3] + s * (PA[4] + s * (PA[5] + s * PA[6])))));
731 let q = 1.0 + s * (QA[0] + s * (QA[1] + s * (QA[2] + s * (QA[3] + s * (QA[4] + s * QA[5])))));
732 return if sign == 0 { ERX + p / q } else { -ERX - p / q };
733 }
734 if ix >= 0x4018_0000 {
735 // |x| >= 6
736 return if sign == 0 { 1.0 - 1e-300 } else { 1e-300 - 1.0 };
737 }
738 let ax = x.abs();
739 let s = 1.0 / (ax * ax);
740 let (r, sv) = if ix < 0x4006_db6d {
741 // |x| < 1/0.35
742 (RA[0] + s * (RA[1] + s * (RA[2] + s * (RA[3] + s * (RA[4] + s * (RA[5] + s * (RA[6] + s * RA[7])))))),
743 1.0 + s * (SA[0] + s * (SA[1] + s * (SA[2] + s * (SA[3] + s * (SA[4] + s * (SA[5] + s * (SA[6] + s * SA[7]))))))))
744 } else {
745 (RB[0] + s * (RB[1] + s * (RB[2] + s * (RB[3] + s * (RB[4] + s * (RB[5] + s * RB[6]))))),
746 1.0 + s * (SB[0] + s * (SB[1] + s * (SB[2] + s * (SB[3] + s * (SB[4] + s * (SB[5] + s * SB[6])))))))
747 };
748 // z is ax with its low 32 bits cleared.
749 let z = f64::from_bits(ax.to_bits() & 0xffff_ffff_0000_0000);
750 let e = (-z * z - 0.5625).exp() * ((z - ax) * (z + ax) + r / sv).exp();
751 if sign == 0 { 1.0 - e / ax } else { e / ax - 1.0 }
752}