truecalc-core 3.2.0

Formula engine with exact Google Sheets semantics — stateless, embeddable evaluator
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
use crate::eval::coercion::{to_number, to_string_val};
use crate::eval::functions::check_arity;
use crate::types::{ErrorKind, Value};

// ── Internal complex type ─────────────────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Complex {
    pub re: f64,
    pub im: f64,
}

impl Complex {
    fn new(re: f64, im: f64) -> Self {
        Self { re, im }
    }

    fn abs(self) -> f64 {
        libm::sqrt(self.re * self.re + self.im * self.im)
    }

    fn arg(self) -> f64 {
        libm::atan2(self.im, self.re)
    }

    fn mul(self, rhs: Self) -> Self {
        Self {
            re: self.re * rhs.re - self.im * rhs.im,
            im: self.re * rhs.im + self.im * rhs.re,
        }
    }

    fn pow(self, n: Self) -> Option<Self> {
        // c^n = exp(n * ln(c))
        let r = self.abs();
        if r == 0.0 {
            // 0^0 = 1 by convention; 0^n = 0 for n != 0
            if n.re == 0.0 && n.im == 0.0 {
                return Some(Complex::new(1.0, 0.0));
            }
            if n.re > 0.0 {
                return Some(Complex::new(0.0, 0.0));
            }
            return None; // 0^negative
        }
        let theta = self.arg();
        let ln_r = libm::log(r);
        // ln(c) = ln_r + i*theta
        // n * ln(c) = (n.re*ln_r - n.im*theta) + i*(n.im*ln_r + n.re*theta)
        let exp_re = n.re * ln_r - n.im * theta;
        let exp_im = n.im * ln_r + n.re * theta;
        let scale = libm::exp(exp_re);
        Some(Complex::new(scale * libm::cos(exp_im), scale * libm::sin(exp_im)))
    }

    fn sqrt(self) -> Self {
        // Principal square root.
        //
        // For pure negative reals (im==0, re<0) GS uses the polar/trig form which
        // yields a tiny non-zero real part (cos(pi/2) ≈ 6.12e-17). Conformance
        // fixtures expect that floating-point residual, so we match it here.
        //
        // For all other inputs the algebraic formula avoids trig round-off --
        // most importantly IMSQRT("4j"): both components come out as sqrt(2)
        // exactly rather than differing by one ULP.
        let r = self.abs();
        if r == 0.0 {
            return Complex::new(0.0, 0.0);
        }
        if self.im == 0.0 && self.re < 0.0 {
            // Polar/trig form preserves the cos(pi/2) residual GS shows.
            let theta = self.arg(); // = pi
            let sqrt_r = libm::sqrt(r);
            return Complex::new(sqrt_r * libm::cos(theta / 2.0), sqrt_r * libm::sin(theta / 2.0));
        }
        // Algebraic form: sqrt((|z|+re)/2) + i*sign(im)*sqrt((|z|-re)/2)
        let re_out = libm::sqrt((r + self.re) / 2.0);
        let im_out = libm::sqrt((r - self.re) / 2.0);
        let im_out = if self.im < 0.0 { -im_out } else { im_out };
        Complex::new(re_out, im_out)
    }

    fn ln(self) -> Option<Self> {
        let r = self.abs();
        if r == 0.0 {
            return None;
        }
        Some(Complex::new(libm::log(r), self.arg()))
    }
}

// ── Complex string parsing / formatting ──────────────────────────────────────

/// Parse a complex number string like "3+4i", "3-4i", "i", "-i", "5", "2j", etc.
/// Returns None on parse failure.
pub(super) fn parse_complex(s: &str) -> Option<Complex> {
    let s = s.trim();
    if s.is_empty() {
        return None;
    }

    // Detect suffix ('i' or 'j')
    let suffix = if s.ends_with('i') || s.ends_with('j') {
        Some(s.chars().last().unwrap())
    } else {
        None
    };

    if suffix.is_none() {
        // Pure real number
        let re = s.parse::<f64>().ok()?;
        return Some(Complex::new(re, 0.0));
    }

    // Strip suffix
    let s = &s[..s.len() - 1];

    // Pure imaginary: "i", "-i", "+i"
    if s.is_empty() || s == "+" {
        return Some(Complex::new(0.0, 1.0));
    }
    if s == "-" {
        return Some(Complex::new(0.0, -1.0));
    }

    // Try parsing the whole thing as real (shouldn't happen but cover edge case)
    if !s.contains('+') && !s.contains('-') || s.starts_with('-') && s[1..].find(['+', '-']).is_none() {
        // E.g. "4i" or "-4i"
        let im = s.parse::<f64>().ok()?;
        return Some(Complex::new(0.0, im));
    }

    // Find the split point between real and imaginary parts.
    // We look for the last '+' or '-' that isn't at position 0 (sign of real).
    let bytes = s.as_bytes();
    let mut split = None;
    let start = if bytes[0] == b'-' || bytes[0] == b'+' { 1 } else { 0 };
    for i in (start + 1..bytes.len()).rev() {
        if bytes[i] == b'+' || bytes[i] == b'-' {
            split = Some(i);
            break;
        }
    }

    if let Some(idx) = split {
        let mut re_str = &s[..idx];
        let im_str = &s[idx..];

        // "3++4i": re_str="3+", im_str="+4". Strip a trailing operator from re_str.
        if !re_str.is_empty()
            && (re_str.ends_with('+') || re_str.ends_with('-'))
            && (re_str[..re_str.len()-1].parse::<f64>().is_ok() || re_str.len() == 1)
        {
            re_str = &re_str[..re_str.len()-1];
        }

        let re = if re_str.is_empty() { 0.0 } else { re_str.parse::<f64>().ok()? };
        let im = if im_str == "+" || im_str.is_empty() {
            1.0
        } else if im_str == "-" {
            -1.0
        } else {
            im_str.parse::<f64>().ok()?
        };
        Some(Complex::new(re, im))
    } else {
        // No split found; it's pure imaginary like "4i"
        let im = s.parse::<f64>().ok()?;
        Some(Complex::new(0.0, im))
    }
}

/// Format a complex number back to a string using the given suffix ('i' or 'j').
/// Always returns `Value::Text` — even for purely real results — to match
/// the Google Sheets contract that all IM* functions return a text string.
pub(super) fn format_complex(c: Complex, suffix: char) -> Value {
    let re = c.re;
    let im = c.im;

    if im == 0.0 {
        return Value::Text(format_num(re));
    }

    let re_str = if re == 0.0 {
        String::new()
    } else {
        format_num(re)
    };

    let im_str = if im == 1.0 {
        suffix.to_string()
    } else if im == -1.0 {
        format!("-{}", suffix)
    } else {
        format!("{}{}", format_num(im), suffix)
    };

    let result = if re == 0.0 {
        im_str
    } else if im > 0.0 {
        format!("{}+{}", re_str, im_str)
    } else {
        format!("{}{}", re_str, im_str)
    };

    Value::Text(result)
}

/// Format a float component using Google Sheets' 15-significant-figure rules:
/// - Whole numbers are printed without a decimal point.
/// - Very small (|x| < 1e-9) or very large (|x| >= 1e15) values use uppercase
///   scientific notation with up to 15 sig figs (e.g. `6.12323399573677E-17`).
/// - All other values use decimal notation with up to 15 sig figs, trailing
///   zeros stripped.
fn format_num(n: f64) -> String {
    if n == 0.0 {
        return "0".to_string();
    }
    if n.fract() == 0.0 && n.abs() < 1e15 {
        return format!("{}", n as i64);
    }

    let abs = n.abs();

    if !(1e-9..1e15).contains(&abs) {
        // Scientific notation: 14 decimal places = 15 significant figures.
        let s = format!("{:.14e}", n);
        let (mantissa, exp_part) = s.split_once('e').unwrap();
        let exp_num: i32 = exp_part.parse().unwrap();
        let mantissa = mantissa.trim_end_matches('0').trim_end_matches('.');
        // GS uses uppercase E with a sign and at least 2 digits in the exponent.
        format!("{}E{:+03}", mantissa, exp_num)
    } else {
        // Convert via 15-sig-fig scientific notation, then render as decimal.
        let s = format!("{:.14e}", n);
        let (mantissa, exp_part) = s.split_once('e').unwrap();
        let exp_num: i32 = exp_part.parse().unwrap();
        let mantissa_stripped = mantissa.trim_end_matches('0').trim_end_matches('.');
        let sign = if n < 0.0 { "-" } else { "" };
        let mantissa_abs = mantissa_stripped.trim_start_matches('-');
        let digits: String = mantissa_abs.chars().filter(|c| *c != '.').collect();

        if exp_num < 0 {
            let leading_zeros = (-exp_num - 1) as usize;
            format!("{}0.{}{}", sign, "0".repeat(leading_zeros), digits)
        } else {
            let int_part_len = (exp_num + 1) as usize;
            if int_part_len >= digits.len() {
                format!(
                    "{}{}{}",
                    sign,
                    digits,
                    "0".repeat(int_part_len - digits.len())
                )
            } else {
                let (int_part, frac_part) = digits.split_at(int_part_len);
                format!("{}{}.{}", sign, int_part, frac_part)
            }
        }
    }
}

/// Parse a Value as a complex number. Accepts Text or Number.
fn value_to_complex(v: Value) -> Result<Complex, Value> {
    match v {
        Value::Number(n) | Value::Date(n) => Ok(Complex::new(n, 0.0)),
        Value::Text(s) => {
            parse_complex(&s).ok_or(Value::Error(ErrorKind::Num))
        }
        Value::Error(_) => Err(v),
        // GS: booleans are NOT valid complex arguments -> #NUM!
        Value::Bool(_) => Err(Value::Error(ErrorKind::Num)),
        _ => {
            match to_number(v) {
                Ok(n) => Ok(Complex::new(n, 0.0)),
                Err(e) => Err(e),
            }
        }
    }
}

/// Extract the imaginary suffix ('i' or 'j') from a Value, defaulting to 'i'.
fn get_suffix(v: &Value) -> char {
    if let Value::Text(s) = v {
        if s.ends_with('j') { return 'j'; }
    }
    'i'
}

/// Determine the common suffix for a list of complex arguments.
/// Returns Ok('i') or Ok('j') if all text args use the same suffix (or there are none).
/// Returns Err(#NUM!) if any two text args have conflicting suffixes.
/// Non-text args (numbers/booleans) don't contribute a suffix.
fn determine_suffix(args: &[Value]) -> Result<char, Value> {
    let mut found: Option<char> = None;
    for arg in args {
        let s = match arg {
            Value::Text(s) => s,
            _ => continue,
        };
        // Only args that parse as complex with a suffix count
        let suffix = if s.ends_with('i') {
            'i'
        } else if s.ends_with('j') {
            'j'
        } else {
            continue; // pure real string — no suffix
        };
        match found {
            None => found = Some(suffix),
            Some(existing) if existing != suffix => {
                return Err(Value::Error(ErrorKind::Num));
            }
            _ => {}
        }
    }
    Ok(found.unwrap_or('i'))
}

// ── COMPLEX ───────────────────────────────────────────────────────────────────

/// `COMPLEX(real, imaginary, [suffix])` — create a complex number string.
pub fn complex_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 2, 3) {
        return err;
    }
    let re = match to_number(args[0].clone()) {
        Err(e) => return e,
        Ok(v) => v,
    };
    let im = match to_number(args[1].clone()) {
        Err(e) => return e,
        Ok(v) => v,
    };
    let suffix = if args.len() == 3 {
        match to_string_val(args[2].clone()) {
            Err(e) => return e,
            Ok(s) => {
                if s == "i" || s == "j" {
                    s.chars().next().unwrap()
                } else {
                    return Value::Error(ErrorKind::Value);
                }
            }
        }
    } else {
        'i'
    };
    format_complex(Complex::new(re, im), suffix)
}

// ── IMREAL / IMAGINARY ────────────────────────────────────────────────────────

/// `IMREAL(complex)` — return real part of complex number.
pub fn imreal_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => Value::Number(c.re),
    }
}

/// `IMAGINARY(complex)` — return imaginary part of complex number.
pub fn imaginary_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => Value::Number(c.im),
    }
}

// ── IMABS ─────────────────────────────────────────────────────────────────────

/// `IMABS(complex)` — return absolute value (modulus) of complex number.
pub fn imabs_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => Value::Number(c.abs()),
    }
}

// ── IMPRODUCT ─────────────────────────────────────────────────────────────────

/// `IMPRODUCT(complex1, ...)` — product of complex numbers.
pub fn improduct_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, usize::MAX) {
        return err;
    }
    // Determine suffix and check for mismatches.
    let suffix = match determine_suffix(args) {
        Err(e) => return e,
        Ok(s) => s,
    };
    let mut result = Complex::new(1.0, 0.0);
    for arg in args {
        match value_to_complex(arg.clone()) {
            Err(e) => return e,
            Ok(c) => result = result.mul(c),
        }
    }
    format_complex(result, suffix)
}

// ── IMSUB ────────────────────────────────────────────────────────────────────

/// `IMSUB(complex1, complex2)` — subtract complex numbers.
pub fn imsub_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 2, 2) {
        return err;
    }
    // Determine suffix and check for mismatches.
    let suffix = match determine_suffix(args) {
        Err(e) => return e,
        Ok(s) => s,
    };
    let a = match value_to_complex(args[0].clone()) {
        Err(e) => return e,
        Ok(c) => c,
    };
    let b = match value_to_complex(args[1].clone()) {
        Err(e) => return e,
        Ok(c) => c,
    };
    format_complex(Complex::new(a.re - b.re, a.im - b.im), suffix)
}

// ── IMSUM ────────────────────────────────────────────────────────────────────

/// `IMSUM(complex1, ...)` — sum of complex numbers.
pub fn imsum_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, usize::MAX) {
        return err;
    }
    // Determine suffix and check for mismatches.
    let suffix = match determine_suffix(args) {
        Err(e) => return e,
        Ok(s) => s,
    };
    let mut re = 0.0f64;
    let mut im = 0.0f64;
    for arg in args {
        match value_to_complex(arg.clone()) {
            Err(e) => return e,
            Ok(c) => {
                re += c.re;
                im += c.im;
            }
        }
    }
    format_complex(Complex::new(re, im), suffix)
}

// ── IMDIV ────────────────────────────────────────────────────────────────────

/// `IMDIV(complex1, complex2)` — divide complex numbers.
pub fn imdiv_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 2, 2) {
        return err;
    }
    // Determine suffix and check for mismatches.
    let suffix = match determine_suffix(args) {
        Err(e) => return e,
        Ok(s) => s,
    };
    let a = match value_to_complex(args[0].clone()) {
        Err(e) => return e,
        Ok(c) => c,
    };
    let b = match value_to_complex(args[1].clone()) {
        Err(e) => return e,
        Ok(c) => c,
    };
    let denom = b.re * b.re + b.im * b.im;
    if denom == 0.0 {
        return Value::Error(ErrorKind::DivByZero);
    }
    let re = (a.re * b.re + a.im * b.im) / denom;
    let im = (a.im * b.re - a.re * b.im) / denom;
    format_complex(Complex::new(re, im), suffix)
}

// ── IMCONJUGATE ───────────────────────────────────────────────────────────────

/// `IMCONJUGATE(complex)` — complex conjugate.
pub fn imconjugate_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => format_complex(Complex::new(c.re, -c.im), suffix),
    }
}

// ── IMARGUMENT ────────────────────────────────────────────────────────────────

/// `IMARGUMENT(complex)` — argument (angle) of complex number.
pub fn imargument_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            if c.re == 0.0 && c.im == 0.0 {
                Value::Error(ErrorKind::DivByZero)
            } else {
                Value::Number(c.arg())
            }
        }
    }
}

// ── IMLN ─────────────────────────────────────────────────────────────────────

/// `IMLN(complex)` — natural log of complex number.
/// GS always returns results with 'i' suffix, regardless of input notation.
pub fn imln_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => match c.ln() {
            None => Value::Error(ErrorKind::DivByZero),
            Some(result) => format_complex(result, 'i'),
        },
    }
}

// ── IMLOG10 / IMLOG2 / IMLOG ─────────────────────────────────────────────────

/// `IMLOG10(complex)` — base-10 log of complex number.
pub fn imlog10_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => match c.ln() {
            None => Value::Error(ErrorKind::DivByZero),
            Some(result) => {
                let ln10 = libm::log(10.0f64);
                format_complex(Complex::new(result.re / ln10, result.im / ln10), 'i')
            }
        },
    }
}

/// `IMLOG2(complex)` — base-2 log of complex number.
pub fn imlog2_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => match c.ln() {
            None => Value::Error(ErrorKind::DivByZero),
            Some(result) => {
                let ln2 = libm::log(2.0f64);
                format_complex(Complex::new(result.re / ln2, result.im / ln2), 'i')
            }
        },
    }
}

/// `IMLOG(complex, base)` — general log of complex number.
pub fn imlog_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 2, 2) {
        return err;
    }
    let c = match value_to_complex(args[0].clone()) {
        Err(e) => return e,
        Ok(v) => v,
    };
    let base = match to_number(args[1].clone()) {
        Err(e) => return e,
        Ok(v) => v,
    };
    if base <= 0.0 || base == 1.0 {
        return Value::Error(ErrorKind::Num);
    }
    match c.ln() {
        None => Value::Error(ErrorKind::DivByZero),
        Some(result) => {
            let ln_base = libm::log(base);
            format_complex(Complex::new(result.re / ln_base, result.im / ln_base), 'i')
        }
    }
}

// ── IMEXP ────────────────────────────────────────────────────────────────────

/// `IMEXP(complex)` — e raised to a complex power.
pub fn imexp_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let scale = libm::exp(c.re);
            format_complex(Complex::new(scale * libm::cos(c.im), scale * libm::sin(c.im)), suffix)
        }
    }
}

// ── IMPOWER ──────────────────────────────────────────────────────────────────

/// `IMPOWER(complex, number)` — complex number raised to a power.
pub fn impower_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 2, 2) {
        return err;
    }
    let base = match value_to_complex(args[0].clone()) {
        Err(e) => return e,
        Ok(c) => c,
    };
    // The exponent is always real. Use to_number so that:
    //   - TRUE/FALSE coerce to 1/0 (GS rows 1042/1043)
    //   - non-numeric text like "abc" returns #VALUE! not #NUM! (GS row 1047)
    let exp_n = match to_number(args[1].clone()) {
        Err(e) => return e,
        Ok(v) => v,
    };
    let exp = Complex::new(exp_n, 0.0);
    let suffix = get_suffix(&args[0]);
    match base.pow(exp) {
        None => Value::Error(ErrorKind::Num),
        Some(mut result) => {
            // Snap near-integer components to exact integers (FP rounding).
            // e.g. IMPOWER("5+2i",3) real part: 64.999...999 -> 65.
            // Only snap when the rounded value is non-zero: tiny residuals that
            // round to zero (e.g. 16·sin(2π) ≈ -3.9e-15) must be preserved —
            // Google Sheets includes them (rows 1039/1040/1053).
            if result.re.round() != 0.0
                && (result.re.round() - result.re).abs() < 1e-9 * result.re.abs().max(1.0)
            {
                result.re = result.re.round();
            }
            if result.im.round() != 0.0
                && (result.im.round() - result.im).abs() < 1e-9 * result.im.abs().max(1.0)
            {
                result.im = result.im.round();
            }
            format_complex(result, suffix)
        }
    }
}

// ── IMSQRT ───────────────────────────────────────────────────────────────────

/// `IMSQRT(complex)` — principal square root of complex number.
pub fn imsqrt_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => format_complex(c.sqrt(), suffix),
    }
}

// ── Trig functions ────────────────────────────────────────────────────────────

/// `IMSIN(complex)` — sine of complex number.
pub fn imsin_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let re = libm::sin(c.re) * libm::cosh(c.im);
            let im = libm::cos(c.re) * libm::sinh(c.im);
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMCOS(complex)` — cosine of complex number.
pub fn imcos_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let re = libm::cos(c.re) * libm::cosh(c.im);
            let im = -(libm::sin(c.re) * libm::sinh(c.im));
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMTAN(complex)` — tangent of complex number.
/// Uses double-angle formula for precision matching Google Sheets:
///   tan(a+bi) = sin(2a)/(cos(2a)+cosh(2b)) + i*sinh(2b)/(cos(2a)+cosh(2b))
pub fn imtan_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let a2 = 2.0 * c.re;
            let b2 = 2.0 * c.im;
            let denom = libm::cos(a2) + libm::cosh(b2);
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = libm::sin(a2) / denom;
            let im = libm::sinh(b2) / denom;
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMCOT(complex)` — cotangent of complex number.
/// Uses double-angle formula for precision matching Google Sheets:
///   cot(a+bi) = sin(2a)/(cosh(2b)-cos(2a)) - i*sinh(2b)/(cosh(2b)-cos(2a))
pub fn imcot_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let a2 = 2.0 * c.re;
            let b2 = 2.0 * c.im;
            let denom = libm::cosh(b2) - libm::cos(a2);
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = libm::sin(a2) / denom;
            let im = -(libm::sinh(b2) / denom);
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMCSC(complex)` — cosecant of complex number.
pub fn imcsc_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let sin_re = libm::sin(c.re) * libm::cosh(c.im);
            let sin_im = libm::cos(c.re) * libm::sinh(c.im);
            let denom = sin_re * sin_re + sin_im * sin_im;
            if denom == 0.0 {
                return Value::Error(ErrorKind::Num);
            }
            let re = sin_re / denom;
            let im = -sin_im / denom;
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMSEC(complex)` — secant of complex number.
pub fn imsec_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let cos_re = libm::cos(c.re) * libm::cosh(c.im);
            let cos_im = -(libm::sin(c.re) * libm::sinh(c.im));
            let denom = cos_re * cos_re + cos_im * cos_im;
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = cos_re / denom;
            let im = -cos_im / denom;
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

// ── Hyperbolic trig ────────────────────────────────────────────────────────────

/// `IMSINH(complex)` — hyperbolic sine of complex number.
pub fn imsinh_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let re = libm::sinh(c.re) * libm::cos(c.im);
            let im = libm::cosh(c.re) * libm::sin(c.im);
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMCOSH(complex)` — hyperbolic cosine of complex number.
pub fn imcosh_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let re = libm::cosh(c.re) * libm::cos(c.im);
            let im = libm::sinh(c.re) * libm::sin(c.im);
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMTANH(complex)` — hyperbolic tangent of complex number.
/// Uses double-angle formula for precision matching Google Sheets:
///   tanh(a+bi) = sinh(2a)/(cosh(2a)+cos(2b)) + i*sin(2b)/(cosh(2a)+cos(2b))
pub fn imtanh_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let a2 = 2.0 * c.re;
            let b2 = 2.0 * c.im;
            let denom = libm::cosh(a2) + libm::cos(b2);
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = libm::sinh(a2) / denom;
            let im = libm::sin(b2) / denom;
            if im == 0.0 {
                return Value::Text(format_num(re));
            }
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMCOTH(complex)` — hyperbolic cotangent of complex number.
/// Uses double-angle formula for precision matching Google Sheets:
///   coth(a+bi) = sinh(2a)/(cosh(2a)-cos(2b)) - i*sin(2b)/(cosh(2a)-cos(2b))
pub fn imcoth_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let a2 = 2.0 * c.re;
            let b2 = 2.0 * c.im;
            let denom = libm::cosh(a2) - libm::cos(b2);
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = libm::sinh(a2) / denom;
            let im = -(libm::sin(b2) / denom);
            if im == 0.0 {
                return Value::Text(format_num(re));
            }
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMCSCH(complex)` — hyperbolic cosecant of complex number.
pub fn imcsch_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let sinh_re = libm::sinh(c.re) * libm::cos(c.im);
            let sinh_im = libm::cosh(c.re) * libm::sin(c.im);
            let denom = sinh_re * sinh_re + sinh_im * sinh_im;
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = sinh_re / denom;
            let im = -sinh_im / denom;
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

/// `IMSECH(complex)` — hyperbolic secant of complex number.
pub fn imsech_fn(args: &[Value]) -> Value {
    if let Some(err) = check_arity(args, 1, 1) {
        return err;
    }
    let suffix = get_suffix(&args[0]);
    match value_to_complex(args[0].clone()) {
        Err(e) => e,
        Ok(c) => {
            let cosh_re = libm::cosh(c.re) * libm::cos(c.im);
            let cosh_im = libm::sinh(c.re) * libm::sin(c.im);
            let denom = cosh_re * cosh_re + cosh_im * cosh_im;
            if denom == 0.0 {
                return Value::Error(ErrorKind::DivByZero);
            }
            let re = cosh_re / denom;
            let im = -cosh_im / denom;
            format_complex(Complex::new(re, im), suffix)
        }
    }
}

#[cfg(test)]
mod tests;