factorion-lib 6.0.5

A library used to create bots to recognize and calculate factorials and related concepts
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
934
935
936
//! Parses comments and generates the reply.

#[cfg(any(feature = "serde", test))]
use serde::{Deserialize, Serialize};

use crate::rug::integer::IntegerExt64;
use crate::rug::{Complete, Integer};

use crate::Consts;
use crate::calculation_results::{Calculation, FormatOptions};
use crate::calculation_tasks::{CalculationBase, CalculationJob};
use crate::parse::parse;

use std::fmt::Write;
use std::ops::*;
#[macro_export]
macro_rules! impl_bitwise {
    ($s_name:ident {$($s_fields:ident),*}, $t_name:ident, $fn_name:ident) => {
        impl $t_name for $s_name {
            type Output = Self;
            fn $fn_name(self, rhs: Self) -> Self {
                Self {
                    $($s_fields: self.$s_fields.$fn_name(rhs.$s_fields),)*
                }
            }
        }
    };
}
#[macro_export]
macro_rules! impl_all_bitwise {
    ($s_name:ident {$($s_fields:ident,)*}) => {impl_all_bitwise!($s_name {$($s_fields),*});};
    ($s_name:ident {$($s_fields:ident),*}) => {
        impl_bitwise!($s_name {$($s_fields),*}, BitOr, bitor);
        impl_bitwise!($s_name {$($s_fields),*}, BitXor, bitxor);
        impl_bitwise!($s_name {$($s_fields),*}, BitAnd, bitand);
        impl Not for $s_name {
            type Output = Self;
            fn not(self) -> Self {
                Self {
                    $($s_fields: self.$s_fields.not(),)*
                }
            }
        }
    };
}

/// The primary abstraction.
/// Construct -> Extract -> Calculate -> Get Reply
///
/// Uses a generic for Metadata (meta).
///
/// Uses three type-states exposed as the aliases [CommentConstructed], [CommentExtracted], and [CommentCalculated].
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
pub struct Comment<Meta, S> {
    /// Metadata (generic)
    pub meta: Meta,
    /// Data for the current step
    pub calculation_list: S,
    /// If Some will prepend a "Hey {string}!" to the reply.
    pub notify: Option<String>,
    pub status: Status,
    pub commands: Commands,
    /// How long the reply may at most be
    pub max_length: usize,
    pub locale: String,
}
/// Base [Comment], contains the comment text, if it might have a calculation. Use [extract](Comment::extract).
pub type CommentConstructed<Meta> = Comment<Meta, String>;
/// Extracted [Comment], contains the calculations to be done. Use [calc](Comment::calc).
pub type CommentExtracted<Meta> = Comment<Meta, Vec<CalculationJob>>;
/// Calculated [Comment], contains the results along with how we go to them. Use [get_reply](Comment::get_reply).
pub type CommentCalculated<Meta> = Comment<Meta, Vec<Calculation>>;

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct Status {
    pub already_replied_or_rejected: bool,
    pub not_replied: bool,
    pub number_too_big_to_calculate: bool,
    pub no_factorial: bool,
    pub reply_would_be_too_long: bool,
    pub factorials_found: bool,
    pub limit_hit: bool,
}

impl_all_bitwise!(Status {
    already_replied_or_rejected,
    not_replied,
    number_too_big_to_calculate,
    no_factorial,
    reply_would_be_too_long,
    factorials_found,
    limit_hit,
});
#[allow(dead_code)]
impl Status {
    pub const NONE: Self = Self {
        already_replied_or_rejected: false,
        not_replied: false,
        number_too_big_to_calculate: false,
        no_factorial: false,
        reply_would_be_too_long: false,
        factorials_found: false,
        limit_hit: false,
    };
    pub const ALREADY_REPLIED_OR_REJECTED: Self = Self {
        already_replied_or_rejected: true,
        ..Self::NONE
    };
    pub const NOT_REPLIED: Self = Self {
        not_replied: true,
        ..Self::NONE
    };
    pub const NUMBER_TOO_BIG_TO_CALCULATE: Self = Self {
        number_too_big_to_calculate: true,
        ..Self::NONE
    };
    pub const NO_FACTORIAL: Self = Self {
        no_factorial: true,
        ..Self::NONE
    };
    pub const REPLY_WOULD_BE_TOO_LONG: Self = Self {
        reply_would_be_too_long: true,
        ..Self::NONE
    };
    pub const FACTORIALS_FOUND: Self = Self {
        factorials_found: true,
        ..Self::NONE
    };
    pub const LIMIT_HIT: Self = Self {
        limit_hit: true,
        ..Self::NONE
    };
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct Commands {
    /// Turn all integers into scientific notiation if that makes them shorter.
    #[cfg_attr(any(feature = "serde", test), serde(default))]
    pub shorten: bool,
    /// Return all the intermediate results for nested calculations.
    #[cfg_attr(any(feature = "serde", test), serde(default))]
    pub steps: bool,
    /// Interpret multi-ops as nested ops.
    #[cfg_attr(any(feature = "serde", test), serde(default))]
    pub nested: bool,
    /// Parse and calculate termials.
    #[cfg_attr(any(feature = "serde", test), serde(default))]
    pub termial: bool,
    /// Disable the beginning note.
    #[cfg_attr(any(feature = "serde", test), serde(default))]
    pub no_note: bool,
    /// Write out the number as a word if possible.
    #[cfg_attr(any(feature = "serde", test), serde(default))]
    pub write_out: bool,
}
impl_all_bitwise!(Commands {
    shorten,
    steps,
    nested,
    termial,
    no_note,
    write_out,
});
#[allow(dead_code)]
impl Commands {
    pub const NONE: Self = Self {
        shorten: false,
        steps: false,
        nested: false,
        termial: false,
        no_note: false,
        write_out: false,
    };
    pub const SHORTEN: Self = Self {
        shorten: true,
        ..Self::NONE
    };
    pub const STEPS: Self = Self {
        steps: true,
        ..Self::NONE
    };
    pub const NESTED: Self = Self {
        nested: true,
        ..Self::NONE
    };
    pub const TERMIAL: Self = Self {
        termial: true,
        ..Self::NONE
    };
    pub const NO_NOTE: Self = Self {
        no_note: true,
        ..Self::NONE
    };
    pub const WRITE_OUT: Self = Self {
        write_out: true,
        ..Self::NONE
    };
}

impl Commands {
    fn contains_command_format(text: &str, command: &str) -> bool {
        let pattern1 = format!("\\[{command}\\]");
        let pattern2 = format!("[{command}]");
        let pattern3 = format!("!{command}");
        text.contains(&pattern1) || text.contains(&pattern2) || text.contains(&pattern3)
    }

    pub fn from_comment_text(text: &str) -> Self {
        Self {
            shorten: Self::contains_command_format(text, "short")
                || Self::contains_command_format(text, "shorten"),
            steps: Self::contains_command_format(text, "steps")
                || Self::contains_command_format(text, "all"),
            nested: Self::contains_command_format(text, "nest")
                || Self::contains_command_format(text, "nested"),
            termial: Self::contains_command_format(text, "termial")
                || Self::contains_command_format(text, "triangle"),
            no_note: Self::contains_command_format(text, "no note")
                || Self::contains_command_format(text, "no\\_note")
                || Self::contains_command_format(text, "no_note"),
            write_out: Self::contains_command_format(text, "write_out")
                || Self::contains_command_format(text, "write\\_out")
                || Self::contains_command_format(text, "write_num")
                || Self::contains_command_format(text, "write\\_num"),
        }
    }
    pub fn overrides_from_comment_text(text: &str) -> Self {
        Self {
            shorten: !Self::contains_command_format(text, "long"),
            steps: !(Self::contains_command_format(text, "no steps")
                || Self::contains_command_format(text, "no_steps")
                || Self::contains_command_format(text, "no\\_steps")),
            nested: !(Self::contains_command_format(text, "no_nest")
                || Self::contains_command_format(text, "no\\_nest")
                || Self::contains_command_format(text, "multi")),
            termial: !(Self::contains_command_format(text, "no termial")
                || Self::contains_command_format(text, "no_termial")
                || Self::contains_command_format(text, "no\\_termial")),
            no_note: !Self::contains_command_format(text, "note"),
            write_out: !(Self::contains_command_format(text, "dont_write_out")
                || Self::contains_command_format(text, "dont\\_write\\_out")
                || Self::contains_command_format(text, "normal num")
                || Self::contains_command_format(text, "normal\\_num")),
        }
    }
}

macro_rules! contains_comb {
    // top level (advance both separately)
    ($var:ident, [$start:tt,$($start_rest:tt),* $(,)?], [$end:tt,$($end_rest:tt),* $(,)?]) => {
        $var.contains(concat!($start, $end)) || contains_comb!($var, [$($start_rest),*], [$end,$($end_rest),*]) || contains_comb!(@inner $var, [$start,$($start_rest),*], [$($end_rest),*])
    };
    // inner (advance only end)
    (@inner $var:ident, [$start:tt,$($start_rest:tt),* $(,)?], [$end:tt,$($end_rest:tt),* $(,)?]) => {
        $var.contains(concat!($start,$end)) || contains_comb!(@inner $var, [$start,$($start_rest),*], [$($end_rest),*])
    };
    // top level (advance both separately) singular end (advance only start)
    ($var:ident, [$start:tt,$($start_rest:tt),* $(,)?], [$end:tt $(,)?]) => {
        $var.contains(concat!($start, $end)) || contains_comb!($var, [$($start_rest),*], [$end])
    };
    // top level (advance both separately) singular start (advance only end)
    ($var:ident, [$start:tt $(,)?], [$end:tt,$($end_rest:tt),* $(,)?]) => {
        $var.contains(concat!($start, $end)) || contains_comb!(@inner $var, [$start], [$($end_rest),*])
    };
    // inner (advance only end) singular end (advance only start, so nothing)
    (@inner $var:ident, [$start:tt,$($start_rest:tt),* $(,)?], [$end:tt $(,)?]) => {
        $var.contains(concat!($start,$end))
    };
    // inner (advance only end) singular end (advance only end)
    (@inner $var:ident, [$start:tt $(,)?], [$end:tt,$($end_rest:tt),* $(,)?]) => {
        $var.contains(concat!($start,$end)) || contains_comb!(@inner $var, [$start], [$($end_rest),*])
    };
    // top level (advance both separately) singular start and end (no advance)
    ($var:ident, [$start:tt $(,)?], [$end:tt $(,)?]) => {
        $var.contains(concat!($start, $end))
    };
    // inner (advance only end) singular start and end (no advance)
    (@inner $var:ident, [$start:tt $(,)?], [$end:tt $(,)?]) => {
        $var.contains(concat!($start,$end))
    };
}

impl<Meta> CommentConstructed<Meta> {
    /// Takes a raw comment, finds the factorials and commands, and packages it, also checks if it might have something to calculate.
    pub fn new(
        comment_text: &str,
        meta: Meta,
        pre_commands: Commands,
        max_length: usize,
        locale: &str,
    ) -> Self {
        let command_overrides = Commands::overrides_from_comment_text(comment_text);
        let commands: Commands =
            (Commands::from_comment_text(comment_text) | pre_commands) & command_overrides;

        let mut status: Status = Default::default();

        let text = if Self::might_have_factorial(comment_text) {
            comment_text.to_owned()
        } else {
            status.no_factorial = true;
            String::new()
        };

        Comment {
            meta,
            notify: None,
            calculation_list: text,
            status,
            commands,
            max_length,
            locale: locale.to_owned(),
        }
    }

    fn might_have_factorial(text: &str) -> bool {
        contains_comb!(
            text,
            [
                "0",
                "1",
                "2",
                "3",
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                ")",
                "e",
                "pi",
                "phi",
                "tau",
                "π",
                "ɸ",
                "τ",
                "infinity",
                "inf",
                "\u{303}",
                ""
            ],
            ["!", "?"]
        ) || contains_comb!(
            text,
            ["!"],
            [
                "0",
                "1",
                "2",
                "3",
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "(",
                "e",
                "pi",
                "phi",
                "tau",
                "π",
                "ɸ",
                "τ",
                "infinity",
                "inf",
                "\u{303}",
                ""
            ]
        )
    }

    /// Extracts the calculations using [parse](mod@crate::parse).
    pub fn extract(self, consts: &Consts) -> CommentExtracted<Meta> {
        let Comment {
            meta,
            calculation_list: comment_text,
            notify,
            mut status,
            commands,
            max_length,
            locale,
        } = self;
        let mut pending_list: Vec<CalculationJob> = parse(
            &comment_text,
            commands.termial,
            consts,
            &consts
                .locales
                .get(&locale)
                .unwrap_or(consts.locales.get(&consts.default_locale).unwrap())
                .format
                .number_format,
        );

        if commands.nested {
            for calc in &mut pending_list {
                Self::multi_to_nested(calc);
            }
        }

        if pending_list.is_empty() {
            status.no_factorial = true;
        }

        Comment {
            meta,
            calculation_list: pending_list,
            notify,
            status,
            commands,
            max_length,
            locale,
        }
    }

    fn multi_to_nested(mut calc: &mut CalculationJob) {
        loop {
            let level = calc.level.clamp(-1, 1);
            let depth = calc.level.abs();
            calc.level = level;
            for _ in 1..depth {
                let base = std::mem::replace(
                    &mut calc.base,
                    CalculationBase::Num(
                        crate::calculation_results::CalculationResult::ComplexInfinity,
                    ),
                );
                let new_base = CalculationBase::Calc(Box::new(CalculationJob {
                    base,
                    level,
                    negative: 0,
                }));
                let _ = std::mem::replace(&mut calc.base, new_base);
            }
            let CalculationBase::Calc(next) = &mut calc.base else {
                return;
            };
            calc = next;
        }
    }

    /// Constructs an empty comment with [Status] already_replied_or_rejected set.
    pub fn new_already_replied(meta: Meta, max_length: usize, locale: &str) -> Self {
        let text = String::new();
        let status: Status = Status {
            already_replied_or_rejected: true,
            ..Default::default()
        };
        let commands: Commands = Default::default();

        Comment {
            meta,
            notify: None,
            calculation_list: text,
            status,
            commands,
            max_length,
            locale: locale.to_owned(),
        }
    }
}
impl<Meta, S> Comment<Meta, S> {
    pub fn add_status(&mut self, status: Status) {
        self.status = self.status | status;
    }
}
impl<Meta> CommentExtracted<Meta> {
    /// Does the calculations using [calculation_tasks](crate::calculation_tasks).
    pub fn calc(self, consts: &Consts) -> CommentCalculated<Meta> {
        let Comment {
            meta,
            calculation_list: pending_list,
            notify,
            mut status,
            commands,
            max_length,
            locale,
        } = self;
        let mut calculation_list: Vec<Calculation> = pending_list
            .into_iter()
            .flat_map(|calc| calc.execute(commands.steps, consts))
            .filter_map(|x| {
                if x.is_none() {
                    status.number_too_big_to_calculate = true;
                };
                x
            })
            .collect();

        calculation_list.sort();
        calculation_list.dedup();
        calculation_list.sort_by_key(|x| x.steps.len());

        if calculation_list.is_empty() {
            status.no_factorial = true;
        } else {
            status.factorials_found = true;
        }
        Comment {
            meta,
            calculation_list,
            notify,
            status,
            commands,
            max_length,
            locale,
        }
    }
}
impl<Meta> CommentCalculated<Meta> {
    /// Does the formatting for the reply using [calculation_result](crate::calculation_results).
    pub fn get_reply(&self, consts: &Consts) -> String {
        let mut fell_back = false;
        let locale = consts.locales.get(&self.locale).unwrap_or_else(|| {
            fell_back = true;
            consts.locales.get(&consts.default_locale).unwrap()
        });
        let mut note = self
            .notify
            .as_ref()
            .map(|user| locale.notes.mention.replace("{mention}", user) + "\n\n")
            .unwrap_or_default();

        if fell_back {
            let _ = note.write_str("Sorry, I currently don't speak ");
            let _ = note.write_str(&self.locale);
            let _ = note.write_str(". Maybe you could [teach me](https://github.com/tolik518/factorion-bot/blob/master/CONTRIBUTING.md#translation)? \n\n");
        }

        let too_big_number = Integer::u64_pow_u64(10, self.max_length as u64).complete();
        let too_big_number = &too_big_number;

        let multiple = self.add_note(consts, locale, &mut note, too_big_number);

        // Add Factorials
        let mut reply = self.add_factorials(
            consts,
            locale,
            &note,
            too_big_number,
            FormatOptions {
                force_shorten: self.commands.shorten,
                write_out: self.commands.write_out,
                ..FormatOptions::NONE
            },
        );

        // If the reply was too long try force shortening all factorials
        if reply.len() + locale.bot_disclaimer.len() + 16 > self.max_length
            && !self.commands.shorten
            && !self
                .calculation_list
                .iter()
                .all(|fact| fact.is_too_long(too_big_number))
        {
            if note.is_empty() && !self.commands.no_note {
                if multiple {
                    let _ = note.write_str(&locale.notes.too_big_mult);
                } else {
                    let _ = note.write_str(&locale.notes.too_big);
                }
                let _ = note.write_str("\n\n");
            };
            reply = self.add_factorials(
                consts,
                locale,
                &note,
                too_big_number,
                FormatOptions {
                    write_out: self.commands.write_out,
                    ..FormatOptions::FORCE_SHORTEN
                },
            );
        }

        let note = if !self.commands.no_note {
            locale.notes.tetration.clone().into_owned() + "\n\n"
        } else {
            String::new()
        };
        // If the reply was too long try agressive shortening all factorials
        if reply.len() + locale.bot_disclaimer.len() + 16 > self.max_length && !self.commands.steps
        {
            reply = self.add_factorials(
                consts,
                locale,
                &note,
                too_big_number,
                FormatOptions {
                    write_out: self.commands.write_out,
                    ..{ FormatOptions::FORCE_SHORTEN | FormatOptions::AGRESSIVE_SHORTEN }
                },
            );
        }

        let note = if !self.commands.no_note {
            locale.notes.remove.clone().into_owned() + "\n\n"
        } else {
            String::new()
        };
        // Remove factorials until we can fit them in a comment
        self.add_factorials_to_fit(consts, locale, too_big_number, &mut reply, note);
        if !locale.bot_disclaimer.is_empty() {
            reply.push_str("\n*^(");
            reply.push_str(&locale.bot_disclaimer);
            reply.push_str(")*");
        }
        reply
    }

    fn add_factorials_to_fit(
        &self,
        consts: &Consts<'_>,
        locale: &crate::locale::Locale<'_>,
        too_big_number: &Integer,
        reply: &mut String,
        note: String,
    ) {
        if reply.len() + locale.bot_disclaimer.len() + 16 > self.max_length {
            let mut factorial_list: Vec<String> = self
                .calculation_list
                .iter()
                .map(|fact| {
                    let mut res = String::new();
                    let _ = fact.format(
                        &mut res,
                        FormatOptions {
                            agressive_shorten: !self.commands.steps,
                            write_out: self.commands.write_out,
                            ..FormatOptions::FORCE_SHORTEN
                        },
                        too_big_number,
                        consts,
                        &locale.format,
                    );
                    res
                })
                .collect();
            'drop_last: {
                while note.len()
                    + factorial_list.iter().map(|s| s.len()).sum::<usize>()
                    + locale.bot_disclaimer.len()
                    + 16
                    > self.max_length
                {
                    // remove last factorial (probably the biggest)
                    factorial_list.pop();
                    if factorial_list.is_empty() {
                        *reply = locale.notes.no_post.to_string();
                        break 'drop_last;
                    }
                }
                *reply = factorial_list.iter().fold(note, |mut acc, factorial| {
                    let _ = acc.write_str(factorial);
                    acc
                });
            }
        }
    }

    fn add_factorials(
        &self,
        consts: &Consts<'_>,
        locale: &crate::locale::Locale<'_>,
        note: &str,
        too_big_number: &Integer,
        format_options: FormatOptions,
    ) -> String {
        self.calculation_list
            .iter()
            .fold(note.to_owned(), |mut acc, factorial| {
                let _ = factorial.format(
                    &mut acc,
                    format_options.clone(),
                    too_big_number,
                    consts,
                    &locale.format,
                );
                acc
            })
    }

    fn add_note(
        &self,
        consts: &Consts<'_>,
        locale: &crate::locale::Locale<'_>,
        note: &mut String,
        too_big_number: &Integer,
    ) -> bool {
        let multiple = self.calculation_list.len() > 1;
        if !self.commands.no_note {
            if self.status.limit_hit {
                let _ = note.write_str(
                    locale
                        .notes
                        .limit_hit
                        .as_ref()
                        .map(AsRef::as_ref)
                        .unwrap_or(
                            "I have repeated myself enough, I won't do that calculation again.",
                        ),
                );
                let _ = note.write_str("\n\n");
            } else if self
                .calculation_list
                .iter()
                .any(Calculation::is_digit_tower)
            {
                if multiple {
                    let _ = note.write_str(&locale.notes.tower_mult);
                    let _ = note.write_str("\n\n");
                } else {
                    let _ = note.write_str(&locale.notes.tower);
                    let _ = note.write_str("\n\n");
                }
            } else if self
                .calculation_list
                .iter()
                .any(Calculation::is_aproximate_digits)
            {
                if multiple {
                    let _ = note.write_str(&locale.notes.digits_mult);
                    let _ = note.write_str("\n\n");
                } else {
                    let _ = note.write_str(&locale.notes.digits);
                    let _ = note.write_str("\n\n");
                }
            } else if self
                .calculation_list
                .iter()
                .any(Calculation::is_approximate)
            {
                if multiple {
                    let _ = note.write_str(&locale.notes.approx_mult);
                    let _ = note.write_str("\n\n");
                } else {
                    let _ = note.write_str(&locale.notes.approx);
                    let _ = note.write_str("\n\n");
                }
            } else if self.calculation_list.iter().any(Calculation::is_rounded) {
                if multiple {
                    let _ = note.write_str(&locale.notes.round_mult);
                    let _ = note.write_str("\n\n");
                } else {
                    let _ = note.write_str(&locale.notes.round);
                    let _ = note.write_str("\n\n");
                }
            } else if self
                .calculation_list
                .iter()
                .any(|c| c.is_too_long(too_big_number))
                && !(self.commands.write_out
                    && self
                        .calculation_list
                        .iter()
                        .all(|c| c.can_write_out(consts.float_precision)))
            {
                if multiple {
                    let _ = note.write_str(&locale.notes.too_big_mult);
                    let _ = note.write_str("\n\n");
                } else {
                    let _ = note.write_str(&locale.notes.too_big);
                    let _ = note.write_str("\n\n");
                }
            } else if self.commands.write_out && self.locale != "en" {
                let _ =
                    note.write_str("I can only write out numbers in english, so I will do that.");
                let _ = note.write_str("\n\n");
            }
        }
        multiple
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        calculation_results::Number,
        calculation_tasks::{CalculationBase, CalculationJob},
        locale::NumFormat,
    };

    const MAX_LENGTH: usize = 10_000;

    use super::*;

    type Comment<S> = super::Comment<(), S>;

    #[test]
    fn test_extraction_dedup() {
        let consts = Consts::default();
        let jobs = parse(
            "24! -24! 2!? (2!?)!",
            true,
            &consts,
            &NumFormat { decimal: '.' },
        );
        assert_eq!(
            jobs,
            [
                CalculationJob {
                    base: CalculationBase::Num(Number::Exact(24.into())),
                    level: 1,
                    negative: 0
                },
                CalculationJob {
                    base: CalculationBase::Num(Number::Exact(24.into())),
                    level: 1,
                    negative: 1
                },
                CalculationJob {
                    base: CalculationBase::Calc(Box::new(CalculationJob {
                        base: CalculationBase::Num(Number::Exact(2.into())),
                        level: 1,
                        negative: 0
                    })),
                    level: -1,
                    negative: 0
                },
                CalculationJob {
                    base: CalculationBase::Calc(Box::new(CalculationJob {
                        base: CalculationBase::Calc(Box::new(CalculationJob {
                            base: CalculationBase::Num(Number::Exact(2.into())),
                            level: 1,
                            negative: 0
                        })),
                        level: -1,
                        negative: 0
                    })),
                    level: 1,
                    negative: 0
                }
            ]
        );
    }

    #[test]
    fn test_commands_from_comment_text() {
        let cmd1 = Commands::from_comment_text("!shorten!all !triangle !no_note !nested");
        assert!(cmd1.shorten);
        assert!(cmd1.steps);
        assert!(cmd1.termial);
        assert!(cmd1.no_note);
        assert!(cmd1.nested);
        let cmd2 = Commands::from_comment_text("[shorten][all] [triangle] [no_note] [nest]");
        assert!(cmd2.shorten);
        assert!(cmd2.steps);
        assert!(cmd2.termial);
        assert!(cmd2.no_note);
        assert!(cmd2.nested);
        let comment = r"\[shorten\]\[all\] \[triangle\] \[no_note\] \[nest\]";
        let cmd3 = Commands::from_comment_text(comment);
        assert!(cmd3.shorten);
        assert!(cmd3.steps);
        assert!(cmd3.termial);
        assert!(cmd3.no_note);
        assert!(cmd3.nested);
        let cmd4 = Commands::from_comment_text("shorten all triangle no_note nest");
        assert!(!cmd4.shorten);
        assert!(!cmd4.steps);
        assert!(!cmd4.termial);
        assert!(!cmd4.no_note);
        assert!(!cmd4.nested);
    }

    #[test]
    fn test_commands_overrides_from_comment_text() {
        let cmd1 = Commands::overrides_from_comment_text("long no_steps no_termial note multi");
        assert!(cmd1.shorten);
        assert!(cmd1.steps);
        assert!(cmd1.termial);
        assert!(cmd1.no_note);
        assert!(cmd1.nested);
    }

    #[test]
    fn test_might_have_factorial() {
        assert!(Comment::might_have_factorial("5!"));
        assert!(Comment::might_have_factorial("3?"));
        assert!(!Comment::might_have_factorial("!?"));
    }

    #[test]
    fn test_new_already_replied() {
        let comment = Comment::new_already_replied((), MAX_LENGTH, "en");
        assert_eq!(comment.calculation_list, "");
        assert!(comment.status.already_replied_or_rejected);
    }

    #[test]
    fn test_locale_fallback_note() {
        let consts = Consts::default();
        let comment = Comment::new_already_replied((), MAX_LENGTH, "n/a")
            .extract(&consts)
            .calc(&consts);
        let reply = comment.get_reply(&consts);
        assert_eq!(
            reply,
            "Sorry, I currently don't speak n/a. Maybe you could [teach me](https://github.com/tolik518/factorion-bot/blob/master/CONTRIBUTING.md#translation)? \n\n\n*^(This action was performed by a bot | [Source code](http://f.r0.fyi))*"
        );
    }

    #[test]
    fn test_limit_hit_note() {
        let consts = Consts::default();
        let mut comment = Comment::new_already_replied((), MAX_LENGTH, "en")
            .extract(&consts)
            .calc(&consts);
        comment.add_status(Status::LIMIT_HIT);
        let reply = comment.get_reply(&consts);
        assert_eq!(
            reply,
            "I have repeated myself enough, I won't do that calculation again.\n\n\n*^(This action was performed by a bot | [Source code](http://f.r0.fyi))*"
        );
    }

    #[test]
    fn test_write_out_unsupported_note() {
        let consts = Consts::default();
        let comment = Comment::new("1!", (), Commands::WRITE_OUT, MAX_LENGTH, "de")
            .extract(&consts)
            .calc(&consts);
        let reply = comment.get_reply(&consts);
        assert_eq!(
            reply,
            "I can only write out numbers in english, so I will do that.\n\nFakultät von one ist one \n\n\n*^(Dieser Kommentar wurde automatisch geschrieben | [Quelltext](http://f.r0.fyi))*"
        );
    }
}