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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
#![feature(let_chains)]
#![feature(if_let_guard)]
#![feature(map_try_insert)]
#![forbid(unsafe_code)]
#![deny(clippy::pedantic)]
#![deny(clippy::nursery)]
#![forbid(clippy::enum_glob_use)]
#![forbid(clippy::unwrap_used)]
// #![allow(clippy::too_many_lines)]
// #![allow(clippy::cognitive_complexity)]
// #![allow(clippy::cast_precision_loss)]
// #![allow(clippy::cast_possible_truncation)]
// #![allow(clippy::cast_sign_loss)]
// #![allow(clippy::cast_possible_wrap)]

use std::{
    collections::HashMap,
    path::PathBuf,
    time::{Duration, Instant},
};

use colored::Colorize;
#[cfg(feature = "silly")]
use geocoding::Reverse;
use itertools::Itertools;
use strum::EnumCount;
use strum_macros::EnumCount as EnumCountMacro;

pub fn report_error(string: &str) -> ! {
    panic!("{}: {string}", "ERROR".bold().red());
}

pub fn report_warning(string: &str) {
    eprintln!("{}: {string}", "WARNING".bold().yellow());
}
#[derive(Clone, Debug, PartialEq)]
pub enum StackValue {
    Integer(i64),
    Float(f64),
    String(String),
    Bool(bool),
}

impl std::fmt::Display for StackValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Integer(int) => write!(f, "{int}"),
            Self::Float(float) => write!(f, "{float:.2}"),
            Self::String(string) => write!(f, "{string}"),
            Self::Bool(boolean) => write!(f, "{boolean}"),
        }
    }
}

impl std::ops::Add for StackValue {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        match self {
            Self::String(string) => Self::String(string + other.to_string().as_str()),
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(int + int2),
                Self::Float(float) => Self::Float(int as f64 + float),
                Self::String(string) => Self::String(int.to_string() + string.as_str()),
                Self::Bool(boolean) => Self::String(int.to_string() + boolean.to_string().as_str()),
            },
            Self::Float(float) => match other {
                Self::Integer(int) => Self::Float(float + int as f64),
                Self::Float(float2) => Self::Float(float + float2),
                Self::String(string) => Self::String(self.to_string() + string.as_str()),
                Self::Bool(boolean) => Self::String(self.to_string() + boolean.to_string().as_str()),
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => Self::Integer(i64::from(boolean) + i64::from(boolean2)),
                Self::String(string) => Self::String(boolean.to_string() + string.as_str()),
                Self::Float(_) => Self::String(boolean.to_string() + other.to_string().as_str()),
                Self::Integer(int) => Self::String(boolean.to_string() + int.to_string().as_str()),
            },
        }
    }
}

impl std::ops::Sub for StackValue {
    type Output = anyhow::Result<Self>;

    fn sub(self, other: Self) -> Self::Output {
        Ok(match self {
            Self::String(ref string) => match other {
                Self::Integer(int) => {
                    if int < 0 {
                        Self::String(string.to_string() + " ".repeat((-int) as usize).as_str())
                    } else if int as usize > string.len() {
                        anyhow::bail!("Tried to subtract int from string where the int is bigger than the strings length");
                    } else {
                        Self::String(string[..string.len() - int as usize].to_string())
                    }
                }
                Self::Float(float) => {
                    let int = float.round() as i64;
                    if int as usize > string.len() {
                        anyhow::bail!("Tried to subtract float from string where the float is bigger than the strings length");
                    }
                    (self - Self::Integer(int))?
                }

                Self::Bool(bool) => {
                    let int = i64::from(bool);
                    if int as usize > string.len() {
                        anyhow::bail!("Tried to subtract bool from string where the bool is bigger than the strings length");
                    }
                    Self::String(string[..string.len() - int as usize].to_string())
                }
                Self::String(string2) => Self::String(string.replace(string2.as_str(), "")),
            },
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(int - int2),
                Self::Float(float) => Self::Float(int as f64 - float),
                Self::String(string) => Self::String(int.to_string() + " - " + string.as_str()),
                Self::Bool(boolean) => Self::Integer(int - i64::from(boolean)),
            },
            Self::Float(float) => match other {
                Self::Integer(int) => Self::Float(float - int as f64),
                Self::Float(float2) => Self::Float(float - float2),
                Self::String(string) => Self::String(self.to_string() + " - " + string.as_str()),
                Self::Bool(boolean) => Self::Float(float - f64::from(boolean)),
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => Self::Integer(i64::from(boolean) - i64::from(boolean2)),
                Self::String(string) => Self::String(boolean.to_string() + " - " + string.as_str()),
                Self::Float(float) => Self::Float(f64::from(boolean) - float),
                Self::Integer(int) => Self::Integer(i64::from(boolean) - int),
            },
        })
    }
}

impl std::ops::Mul for StackValue {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        match self {
            Self::String(string) => match other {
                Self::Integer(int) => {
                    let temp = string.repeat(int.unsigned_abs() as usize);
                    Self::String(if int < 0 { temp.chars().rev().collect() } else { temp })
                }
                Self::Float(float) => {
                    let temp = string.repeat(float.abs().floor() as usize) + &string[0..(string.len() as f64 * float.abs().fract()).round() as usize];
                    Self::String(if float < 0.0 { temp.chars().rev().collect() } else { temp })
                }
                Self::Bool(boolean) => Self::String(if boolean { string } else { String::new() }),
                Self::String(string2) => Self::String(string2.chars().interleave(string.chars()).collect()),
            },
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(int * int2),
                Self::Float(float) => Self::Float(int as f64 * float),
                Self::String(_) => other * self,
                Self::Bool(boolean) => Self::Integer(int * i64::from(boolean)),
            },
            Self::Float(float) => match other {
                Self::Integer(int) => Self::Float(float * int as f64),
                Self::Float(float2) => Self::Float(float * float2),
                Self::String(_) => other * self,
                Self::Bool(boolean) => Self::Float(float * f64::from(boolean)),
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => Self::Integer(i64::from(boolean && boolean2)),
                _ => other * self,
            },
        }
    }
}

impl std::ops::Div for StackValue {
    type Output = anyhow::Result<either::Either<Self, Vec<Self>>>;

    fn div(self, other: Self) -> Self::Output {
        Ok(either::Either::Left(match self {
            Self::String(string) => match other {
                Self::Integer(int) => Self::String(string) * Self::Float(1.0 / int as f64),
                Self::Float(float) => Self::String(string) * Self::Float(1.0 / float),
                Self::Bool(boolean) => Self::String(if boolean { String::new() } else { string }),
                Self::String(string2) => return Ok(either::Either::Right(string.split(string2.as_str()).map(str::to_string).map(Self::String).collect::<Vec<_>>())),
            },
            Self::Integer(int) => match other {
                Self::Integer(int2) => {
                    if int2 == 0 {
                        anyhow::bail!("Tried to divide by 0");
                    }
                    Self::Float(int as f64 / int2 as f64)
                }
                Self::Float(float) => {
                    if float == 0.0 {
                        anyhow::bail!("Tried to divide by 0")
                    }
                    Self::Float(int as f64 / float)
                }
                Self::String(string) => Self::String(int.to_string() + " / " + string.as_str()),
                Self::Bool(boolean) => {
                    if !boolean {
                        anyhow::bail!("Tried to divide by false")
                    }
                    self
                }
            },
            Self::Float(float) => match other {
                Self::Integer(int) => {
                    if int == 0 {
                        anyhow::bail!("Tried to divide by 0")
                    }
                    Self::Float(float / int as f64)
                }
                Self::Float(float2) => {
                    if float2 == 0.0 {
                        anyhow::bail!("Tried to divide by 0");
                    }
                    Self::Float(float / float2)
                }
                Self::String(string) => Self::String(float.to_string() + " / " + string.as_str()),
                Self::Bool(boolean) => {
                    if !boolean {
                        anyhow::bail!("Tried to divide by false")
                    }
                    self
                }
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => {
                    if !boolean2 {
                        anyhow::bail!("Tried to divide by false")
                    }
                    self
                }
                Self::String(string) => Self::String(boolean.to_string() + " / " + string.as_str()),
                Self::Float(float) => {
                    if float == 0.0 {
                        anyhow::bail!("Tried to divide by 0")
                    }
                    Self::Float(f64::from(boolean) / float)
                }
                Self::Integer(int) => {
                    if int == 0 {
                        anyhow::bail!("Tried to divide by 0")
                    }
                    Self::Float(f64::from(boolean) / int as f64)
                }
            },
        }))
    }
}

impl StackValue {
    // I pulled 639.4 out of my ass 👍
    const EPSILON: f64 = 639.4 * std::f64::EPSILON;

    pub fn loose_equal(&self, other: &Self) -> bool {
        match self {
            Self::String(string) => string == &other.to_string(),
            Self::Integer(int) => match other {
                Self::Integer(int2) => int == int2,
                Self::Float(float) => int == &(float.round() as i64),
                Self::Bool(boolean) => *int == i64::from(*boolean),
                Self::String(_) => other.loose_equal(self),
            },
            Self::Float(float) => match other {
                Self::Float(float2) => float == float2,
                Self::Bool(boolean) => float.round() == f64::from(*boolean),
                _ => other.loose_equal(self),
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => boolean == boolean2,
                _ => other.loose_equal(self),
            },
        }
    }

    pub fn strict_equal(&self, other: &Self) -> bool {
        match self {
            Self::String(string) => matches!(other, Self::String(string2) if string == string2),
            Self::Integer(int) => match other {
                Self::Integer(int2) => int == int2,
                Self::Float(float) => ((*int as f64) - float).abs() < Self::EPSILON,
                Self::Bool(boolean) => int == &i64::from(*boolean),
                Self::String(_) => other.strict_equal(self),
            },
            Self::Float(float) => match other {
                Self::Float(float2) => (float - float2).abs() < Self::EPSILON,
                Self::Bool(_) => false,
                _ => other.strict_equal(self),
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => boolean == boolean2,
                _ => other.strict_equal(self),
            },
        }
    }
    // strict_strict_equal is just the derived PartialEq
}

impl std::ops::Shr for StackValue {
    type Output = anyhow::Result<Self>;

    fn shr(self, other: Self) -> Self::Output {
        Ok(match self {
            Self::String(_) => match other {
                Self::String(string2) => match string2.parse() {
                    Ok(int) => (self >> Self::Integer(int))?,
                    Err(_) => anyhow::bail!("Couldn't parse string as number"),
                },
                _ => {
                    (self - other)? // The behavior I intended is basically
                                    // the same as the subtraction
                }
            },
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(if int2 < 0 { int << (-int2) } else { int >> int2 }),
                Self::Float(float) => Self::Float(int as f64 * 0.5_f64.powf(float)),
                Self::String(string) => match string.parse::<i64>() {
                    Ok(int2) => (self >> Self::Integer(int2))?,
                    Err(_) => anyhow::bail!("Couldn't parse string as number"),
                },
                Self::Bool(boolean) => Self::Integer(int >> i64::from(boolean)),
            },
            Self::Float(float) => match other {
                Self::Integer(_) => (Self::Integer(i64::from_le_bytes(float.to_bits().to_le_bytes())) >> other)?,
                Self::Float(float2) => Self::Float(float * 0.5_f64.powf(float2)),
                Self::String(string) => match string.parse::<i64>() {
                    Ok(int) => (self >> Self::Integer(int))?,
                    Err(_) => anyhow::bail!("Couldn't parse string as number"),
                },
                Self::Bool(boolean) => Self::Float(if boolean { float / 2.0 } else { float }),
            },
            Self::Bool(boolean) => (Self::Integer(i64::from(boolean)) >> other)?,
        })
    }
}

impl std::ops::Shl for StackValue {
    type Output = anyhow::Result<Self>;

    fn shl(self, other: Self) -> Self::Output {
        Ok(match self {
            Self::Integer(int) => match other {
                Self::Integer(int2) => (self >> Self::Integer(-int2))?,
                Self::Float(float) => Self::Float(int as f64 * 2_f64.powf(float)),
                Self::String(string) => match string.parse::<i64>() {
                    Ok(int2) => (self << Self::Integer(int2))?,
                    Err(_) => anyhow::bail!("Couldn't parse string as number"),
                },
                Self::Bool(boolean) => Self::Integer(int << i64::from(boolean)),
            },
            Self::Float(float) => match other {
                Self::Integer(_) => (Self::Integer(i64::from_le_bytes(float.to_bits().to_le_bytes())) << other)?,
                Self::Float(float2) => Self::Float(float * 2.0_f64.powf(float2)),
                Self::String(string) => match string.parse::<i64>() {
                    Ok(int) => (self << Self::Integer(int))?,
                    Err(_) => anyhow::bail!("Couldn't parse string as number"),
                },
                Self::Bool(boolean) => Self::Float(if boolean { float * 2.0 } else { float }),
            },
            Self::String(_) => self + other,
            Self::Bool(boolean) => (Self::Integer(i64::from(boolean)) << other)?,
        })
    }
}

impl std::ops::BitOr for StackValue {
    type Output = Self;

    fn bitor(self, other: Self) -> Self::Output {
        use itertools::EitherOrBoth as E;
        match self {
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(int | int2),
                Self::Float(float) => Self::Integer(int | i64::from_le_bytes(float.to_le_bytes())),
                Self::String(_) => Self::String(format!("{int:064b}")) | other,
                Self::Bool(boolean) => Self::Bool((int.abs() > 0) || boolean),
            },
            Self::Float(float) => match other {
                Self::Integer(_) => other | self,
                Self::Float(float2) => Self::Integer(i64::from_be_bytes(float.to_be_bytes()) | i64::from_ne_bytes(float2.to_ne_bytes())),
                Self::String(_) => Self::String(format!("{:064b}", i64::from_le_bytes(float.to_le_bytes()))) | other,
                Self::Bool(boolean) => Self::Bool((float.abs() > 0.0) || boolean),
            },
            Self::String(ref string) => match other {
                Self::String(string2) => Self::String(
                    string
                        .chars()
                        .zip_longest(string2.chars())
                        .map(|v| match v {
                            E::Both(a, b) => a.max(b),
                            E::Left(a) => a,
                            E::Right(b) => b,
                        })
                        .collect(),
                ),
                Self::Bool(boolean) => Self::Bool(!string.is_empty() || boolean),
                _ => other | self,
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => Self::Bool(boolean || boolean2),
                _ => other | self,
            },
        }
    }
}

impl std::ops::BitAnd for StackValue {
    type Output = Self;

    fn bitand(self, other: Self) -> Self::Output {
        use itertools::EitherOrBoth as E;
        match self {
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(int & int2),
                Self::Float(float) => Self::Integer(int & i64::from_le_bytes(float.to_le_bytes())),
                Self::String(_) => Self::String(format!("{int:064b}")) & other,
                Self::Bool(boolean) => Self::Bool((int.abs() > 0) && boolean),
            },
            Self::Float(float) => match other {
                Self::Integer(_) => other & self,
                Self::Float(float2) => Self::Integer(i64::from_be_bytes(float.to_be_bytes()) & i64::from_ne_bytes(float2.to_ne_bytes())),
                Self::String(_) => Self::String(format!("{:064b}", i64::from_le_bytes(float.to_le_bytes()))) & other,
                Self::Bool(boolean) => Self::Bool((float.abs() > 0.0) && boolean),
            },
            Self::String(ref string) => match other {
                Self::String(string2) => Self::String(
                    string
                        .chars()
                        .zip_longest(string2.chars())
                        .map(|v| match v {
                            E::Both(a, b) => {
                                if a == b {
                                    a
                                } else {
                                    ' '
                                }
                            }
                            _ => ' ',
                        })
                        .collect(),
                ),
                Self::Bool(boolean) => Self::Bool(!string.is_empty() && boolean),
                _ => other & self,
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => Self::Bool(boolean && boolean2),
                _ => other & self,
            },
        }
    }
}

impl std::ops::BitXor for StackValue {
    type Output = Self;

    fn bitxor(self, other: Self) -> Self::Output {
        use itertools::EitherOrBoth as E;
        match self {
            Self::Integer(int) => match other {
                Self::Integer(int2) => Self::Integer(int ^ int2),
                Self::Float(float) => Self::Integer(int ^ i64::from_le_bytes(float.to_le_bytes())),
                Self::String(_) => Self::String(format!("{int:064b}")) ^ other,
                Self::Bool(boolean) => Self::Bool((int.abs() > 0) != boolean),
            },
            Self::Float(float) => match other {
                Self::Integer(_) => other ^ self,
                Self::Float(float2) => Self::Integer(i64::from_be_bytes(float.to_be_bytes()) ^ i64::from_ne_bytes(float2.to_ne_bytes())),
                Self::String(_) => Self::String(format!("{:064b}", i64::from_le_bytes(float.to_le_bytes()))) ^ other,
                Self::Bool(boolean) => Self::Bool((float.abs() > 0.0) != boolean),
            },
            Self::String(ref string) => match other {
                Self::String(string2) => Self::String(
                    string
                        .chars()
                        .zip_longest(string2.chars())
                        .map(|v| match v {
                            E::Both(a, b) => {
                                if a == ' ' {
                                    b
                                } else if b == ' ' {
                                    a
                                } else {
                                    ' '
                                }
                            }
                            E::Left(c) | E::Right(c) => c,
                        })
                        .collect(),
                ),
                Self::Bool(boolean) => Self::Bool(!string.is_empty() != boolean),
                _ => other ^ self,
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => Self::Bool(boolean != boolean2),
                _ => other ^ self,
            },
        }
    }
}

impl std::ops::Not for StackValue {
    type Output = Self;

    fn not(self) -> Self::Output {
        match self {
            Self::Integer(int) => Self::Integer(!int),
            Self::Float(float) => Self::Integer(!i64::from_be_bytes(float.to_be_bytes())),
            Self::String(string) => Self::String(
                string
                    .chars()
                    .map(|c| (c.to_ascii_lowercase(), c.is_uppercase()))
                    .map(|(c, b)| {
                        (
                            match c {
                                'a'..='z' => (((c as u8 - b'a' + 13) % 26) + b'a') as char,
                                _ => c,
                            },
                            b,
                        )
                    })
                    .map(|(c, b)| if b { c.to_ascii_uppercase() } else { c })
                    .collect(),
            ),
            Self::Bool(boolean) => Self::Bool(!boolean),
        }
    }
}

impl std::cmp::PartialOrd for StackValue {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match self {
            Self::String(string) => string.partial_cmp(&other.to_string()),
            Self::Integer(int) => match other {
                Self::Integer(int2) => int.partial_cmp(int2),
                Self::Float(float) => ((*int) as f64).partial_cmp(float),
                Self::Bool(boolean) => int.partial_cmp(&i64::from(*boolean)),
                Self::String(string) => int.to_string().partial_cmp(string),
            },
            Self::Float(float) => match other {
                Self::Float(float2) => float.partial_cmp(float2),
                Self::Integer(int) => float.partial_cmp(&(*int as f64)),
                Self::Bool(boolean) => float.partial_cmp(&(f64::from(*boolean))),
                Self::String(string) => float.to_string().partial_cmp(string),
            },
            Self::Bool(boolean) => match other {
                Self::Bool(boolean2) => boolean.partial_cmp(boolean2),
                Self::Integer(int) => i64::from(*boolean).partial_cmp(int),
                Self::Float(float) => f64::from(*boolean).partial_cmp(float),
                Self::String(string) => boolean.to_string().partial_cmp(string),
            },
        }
    }
}

#[derive(EnumCountMacro, Clone, PartialEq, Debug)]
pub enum Token {
    /// Just a fucking n̶u̶m̶b̶e̶r̶ value✨
    StackValue(StackValue),
    /// Addition. Often used to add numbers.
    Add,
    /// Subtraction. Nothin' more, Nothin' less.
    Subtract,
    /// Multiplication. Very similar to multiplication.
    Multiply,
    /// Division. Quoted in famous works such as "Math".
    Divide,
    /// Used to duplicate things, much like mitosis. a -- a a
    Dup,
    /// Drops the thing, much like I drop depth charges at 55°16'06.9"S
    /// 13°06'37.3"W (for legal reasons, this is a joke). a --
    Drop,
    /// Swaps the two things, much like the process of nurses swapping
    /// babies in hospitals. a b -- b a
    Swap,
    /// Lets the thing jump over. No good jokes here. a b -- a b a
    Over,
    /// Rotates three things, much like my testicles. a b c -- b c a
    Rot,
    /// Prints da thang, no matter what it is (least racist keyword). a --
    Print,
    /// Very similar to print, but with that sweet ln
    Println,
    /// if-condition, often used by white people. The u32 is an offset to
    /// jump to.
    If(usize),
    /// elif is like an elif,
    Elif(usize),
    /// else-condition exists but is non-existent in tokens because
    Else(usize),
    /// fi also exists, but non-existent in tokens because
    /// `MrBeast!` is a mixture between fi and elif:
    /// Once it is reached, one of the if/(el)ifs has already executed,
    /// meaning it will jump to fi.
    MrBeast(usize),
    /// Equality, much like the thing globally not yet reached.
    Eq,
    /// Strict equality, similar to javascripts strict equality thing.
    Seq,
    /// Even stricter equality, stricter than javascripts triple equal.
    Sseq,
    /// Inequality,
    Ineq,
    /// Strict inequality, similar to javascripts strict inequality thing.
    Sineq,
    /// Even stricter inequality, stricter than javascripts double inequal.
    Ssineq,
    /// Greater-than,
    Gt,
    /// Less-than,
    Lt,
    /// Greater-than or equal,
    Ge,
    /// Greater-than or strict equal,
    Gse,
    /// Greater-than or stricterer equal,
    Gsse,
    /// Less-than or equal,
    Le,
    /// Less-than or strict equal,
    Lse,
    /// Less-than or strict strict equal,
    Lsse,
    /// Shift right,
    Shr,
    /// Shift left,
    Shl,
    /// Or, both bool and integer
    Or,
    /// And, both bool and integer
    And,
    /// Not, both bool and integer
    Not,
    /// Xor, both bool and integer
    Xor,
    /// Does absolutely nothing, much like this programming language.
    Dummy,
}

pub fn parse_file(path: &PathBuf) -> anyhow::Result<Vec<Token>> {
    let contents = match std::fs::read_to_string(path) {
        Ok(string) => string,
        Err(err) => {
            report_error(format!("File could not be read because {err}").as_str());
        }
    };
    parse_string(contents)
}

pub fn parse_string(mut contents: String) -> anyhow::Result<Vec<Token>> {
    contents += " "; // This prevents a parser bug where the parser ignores the last token if it
                     // isn't followed by whitespace. No fix for this is planned.

    let mut tokens = Vec::new();
    let mut if_statements: Vec<usize> = Vec::with_capacity(4); // People are gonna wanna nest at least four times.
    let mut elif_statements: HashMap<usize, usize> = HashMap::new();
    let mut mr_beast_statements: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut else_statements: Vec<usize> = Vec::with_capacity(3);
    let mut is_commenting = false;
    let mut is_stringing = false;

    let mut word = String::new();
    let mut index = 0;

    let mut chars = contents.chars();
    while let Some(chr) = chars.next() {
        if chr == '\'' && !is_commenting {
            if is_stringing {
                tokens.push(Token::StackValue(StackValue::String(word)));
                word = String::new();
                index += 1;
            }
            is_stringing = !is_stringing;
            continue;
        }
        if is_stringing {
            if chr == '\\' {
                word.push(match chars.next() {
                    Some('n') => '\n',
                    Some('r') => '\r',
                    Some('t') => '\t',
                    Some('\\') => '\\',
                    Some('0') => '\0',
                    Some('\'') => '\'',
                    Some(x) => anyhow::bail!(format!("Unexpected escape character '{x}'")),
                    None => anyhow::bail!("Expected escape character, found end of file"),
                });
            } else {
                word.push(chr);
            }
            continue;
        }
        if !chr.is_whitespace() {
            word.push(chr);
            continue;
        }
        if chr.is_whitespace() && word.is_empty() {
            continue;
        }
        if !is_commenting {
            static_assertions::const_assert_eq!(Token::COUNT, 37);
            let token = match word.as_str() {
                "+" => Token::Add,
                "-" => Token::Subtract,
                "*" => Token::Multiply,
                "/" => Token::Divide,
                "=" => Token::Eq,
                "==" => Token::Seq,
                "===" => Token::Sseq,
                "!=" => Token::Ineq,
                "!==" => Token::Sineq,
                "!===" => Token::Ssineq,
                ">" => Token::Gt,
                "<" => Token::Lt,
                "=>" => Token::Ge,
                "==>" => Token::Gse,
                "===>" => Token::Gsse,
                "<=" => Token::Le,
                "<==" => Token::Lse,
                "<===" => Token::Lsse,
                ">>" => Token::Shr,
                "<<" => Token::Shl,
                "or" => Token::Or,
                "and" => Token::And,
                "not" => Token::Not,
                "xor" => Token::Xor,
                "if" => {
                    if_statements.push(index);
                    Token::If(usize::MAX)
                }
                "elif" => {
                    let Some(if_index) = if_statements.last() else {
                        anyhow::bail!("Found 'elif' without 'if'");
                    };
                    if elif_statements.try_insert(*if_index, index).is_err() {
                        anyhow::bail!("Found two 'elif's next to eachother without 'MrBeast' between them")
                    }
                    Token::Elif(usize::MAX)
                }
                "MrBeast!" => {
                    let Some(if_index) = if_statements.last() else {
                        anyhow::bail!("Found 'MrBeast' closing an if-statement that doesn't exist");
                    };

                    if let Some(mr_beasts) = mr_beast_statements.get_mut(if_index) {
                        mr_beasts.push(index);
                        if let Some(elif_index) = elif_statements.remove(if_index)
                            && let Some(Token::Elif(jump_addr)) = tokens.get_mut(elif_index)
                        {
                            *jump_addr = index + 1;
                        } else {
                            anyhow::bail!("This is embarrassing");
                        }
                    } else {
                        mr_beast_statements.insert(*if_index, vec![index]);
                        if let Some(Token::If(jump_addr)) = tokens.get_mut(*if_index) {
                            *jump_addr = index + 1;
                        } else {
                            anyhow::bail!("This is embarrassing");
                        }
                    }
                    Token::MrBeast(usize::MAX)
                }
                "else" => {
                    let Some(if_index) = if_statements.last() else {
                        anyhow::bail!("Found 'else' without match 'if'");
                    };
                    if let Some(elif_index) = elif_statements.remove(if_index) {
                        if let Some(Token::Elif(jump_addr)) = tokens.get_mut(elif_index) {
                            *jump_addr = index + 1;
                        } else {
                            anyhow::bail!("This is embarrassing");
                        }
                    } else if let Some(Token::If(jump_addr)) = tokens.get_mut(*if_index) {
                        *jump_addr = index + 1;
                    } else {
                        anyhow::bail!("This is embarrassing");
                    }

                    else_statements.push(index);
                    Token::Else(usize::MAX)
                }
                "fi" => {
                    let Some(if_index) = if_statements.pop() else {
                        anyhow::bail!("Found 'fi' closing an if-statement that doesn't exist");
                    };
                    if let Some(mr_beasts) = mr_beast_statements.remove(&if_index) {
                        for mr_beast_index in mr_beasts {
                            if let Some(Token::MrBeast(jump_addr)) = tokens.get_mut(mr_beast_index) {
                                *jump_addr = index;
                            }
                        }
                    } else if let Some(Token::If(jump_addr)) = tokens.get_mut(if_index) {
                        if *jump_addr == usize::MAX {
                            *jump_addr = index;
                        }
                    } else {
                        anyhow::bail!("This is embarrassing");
                    }

                    if let Some(else_index) = else_statements.pop() {
                        let Some(Token::Else(else_statement)) = tokens.get_mut(else_index) else {
                            anyhow::bail!("This is embarrassing");
                        };
                        *else_statement = index;
                    }
                    Token::Dummy
                }

                "dup" => Token::Dup,
                "drop" => Token::Drop,
                "swap" => Token::Swap,
                "over" => Token::Over,
                "rot" => Token::Rot,
                "print" => Token::Print,
                "println" => Token::Println,
                "comment" => {
                    is_commenting = true;
                    Token::Dummy // This will just chill in the tokens
                }
                x if let Ok(int) = x.parse::<i64>() => Token::StackValue(StackValue::Integer(int)),
                x if let Ok(float) = x.parse::<f64>() => Token::StackValue(StackValue::Float(float)),
                x if let Ok(boolean) = x.parse::<bool>() => Token::StackValue(StackValue::Bool(boolean)),
                x if x.len() == 3 && x.chars().next().is_some_and(|c| c == '"') && x.chars().last().is_some_and(|c| c == '"') => {
                    Token::StackValue(StackValue::Integer(x[1..x.len() - 1].chars().next().expect("This should work") as i64))
                }
                unrecognized => {
                    anyhow::bail!(format!("Unrecognized token {unrecognized}",));
                }
            };
            tokens.push(token);
        }
        if word == "no_comment" {
            is_commenting = false;
        }
        word.clear();
        index += 1;
    }
    if !if_statements.is_empty() {
        anyhow::bail!("Unclosed if-statement");
    }
    if !else_statements.is_empty() {
        anyhow::bail!("This shouldn't happen: Dangling else-statement");
    }
    if !mr_beast_statements.is_empty() {
        anyhow::bail!("This shouldn't happen: Dangling MrBeast-statements");
    }
    if is_commenting {
        anyhow::bail!("Unclosed comment");
    }

    Ok(tokens)
}

pub fn execute_tokens<T: std::io::Write>(tokens: &[Token], #[cfg(feature = "silly")] out_of_free_runs: bool, writable: &mut T, time_limit: Option<Duration>) -> anyhow::Result<Vec<StackValue>> {
    #[cfg(feature = "silly")]
    if out_of_free_runs {
        let local_ip = local_ip_address::local_ip().expect("I'm so done").to_string();
        let info = geolocation::find(local_ip.as_str()).expect("What");
        let (longitude, latitude) = (info.longitude.parse::<f64>().unwrap_or(180.0), info.latitude.parse::<f64>().unwrap_or(0.0));
        let openstreetmap = geocoding::Openstreetmap::new();
        let location = openstreetmap.reverse(&geocoding::Point::new(-longitude, 180.0 - latitude));
        println!(
            "Connecting to our servers in {}, our datacenter that is nearest to you!",
            location.unwrap_or_else(|_| Some("Antarctica".to_string())).unwrap_or_else(|| "Antarctica".to_string())
        );
        std::thread::sleep(std::time::Duration::from_secs(1));
    }

    let mut stack: Vec<StackValue> = Vec::new();
    let mut i: usize = 0;

    let start = Instant::now();
    while let Some(token) = tokens.get(i) {
        #[cfg(feature = "silly")]
        if out_of_free_runs {
            std::thread::sleep(std::time::Duration::from_millis(300));
        }
        if let Some(limit) = time_limit
            && start - Instant::now() > limit
        {
            anyhow::bail!("Exceeded time limit!");
        }
        static_assertions::const_assert_eq!(Token::COUNT, 37);
        // println!("{token:?}, {i}");
        match token {
            Token::Dummy => {}
            Token::StackValue(x) => stack.push(x.clone()),
            Token::Add => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(b + a);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for an addition to be made");
                }
            }
            Token::Subtract => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push((b - a)?);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for a subtraction to be made");
                }
            }
            Token::Multiply => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(a * b);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for a multiplication to be made");
                }
            }
            Token::Divide => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    match (b / a)? {
                        either::Either::Left(sv) => stack.push(sv),
                        either::Either::Right(svs) => stack.extend(svs),
                    }
                } else {
                    anyhow::bail!("The stack must contain at least two elements for a division to be made");
                }
            }
            Token::Eq => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(a.loose_equal(&b)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Ineq => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(!a.loose_equal(&b)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Seq => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(a.strict_equal(&b)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Sineq => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(!a.loose_equal(&b)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Sseq => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(a == b))
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Ssineq => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(a != b))
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Gt => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b > a));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Lt => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b < a));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Ge => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b > a || b.loose_equal(&a)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Le => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b < a || b.loose_equal(&a)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Gse => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b > a || b.strict_equal(&a)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Lse => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b < a || b.strict_equal(&a)));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Gsse => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b > a || b == a));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Lsse => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(StackValue::Bool(b < a || b == a));
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be compared");
                }
            }
            Token::Shr => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push((b >> a)?);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be manipulated");
                }
            }
            Token::Shl => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push((b << a)?);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be manipulated");
                }
            }
            Token::Or => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(b | a);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be manipulated");
                }
            }
            Token::And => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(b & a);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be manipulated");
                }
            }
            Token::Not => {
                if let Some(a) = stack.pop() {
                    stack.push(!a);
                } else {
                    anyhow::bail!("The stack must contain at least one element for it to be negated");
                }
            }
            Token::Xor => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(b ^ a);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be manipulated");
                }
            }
            Token::Dup => {
                if let Some(a) = stack.last() {
                    stack.push(a.clone());
                } else {
                    anyhow::bail!("The stack must contain at least one element for it to be duplicated");
                }
            }
            Token::Drop => {
                if stack.is_empty() {
                    anyhow::bail!("The stack must contain at least one element for it to be dropped");
                }
                let _ = stack.pop();
            }
            Token::Swap => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(a);
                    stack.push(b);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be swapped");
                }
            }
            Token::Over => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                {
                    stack.push(b.clone());
                    stack.push(a);
                    stack.push(b);
                } else {
                    anyhow::bail!("The stack must contain at least two elements for them to be overed");
                }
            }
            Token::Rot => {
                if let Some(a) = stack.pop()
                    && let Some(b) = stack.pop()
                    && let Some(c) = stack.pop()
                {
                    stack.push(b);
                    stack.push(a);
                    stack.push(c);
                } else {
                    anyhow::bail!("The stack must contain at least three elements for them to be roted");
                }
            }
            Token::Print => {
                if let Some(a) = stack.pop() {
                    if let Err(err) = write!(writable, "{a}") {
                        anyhow::bail!("Couldn't write to writable because {err}");
                    };
                } else {
                    anyhow::bail!("The stack must contain at least one element for it to be printed");
                }
            }
            Token::Println => {
                if let Some(a) = stack.pop() {
                    if let Err(err) = writeln!(writable, "{a}") {
                        anyhow::bail!("Couldn't write to writable because {err}");
                    }
                } else {
                    anyhow::bail!("The stack must contain at least one element for it to be printed");
                }
            }
            Token::If(jump_addr) | Token::Elif(jump_addr) => {
                if let Some(StackValue::Bool(boolean)) = stack.pop() {
                    if !boolean {
                        i = *jump_addr;
                        continue;
                    }
                } else {
                    anyhow::bail!("If needs one boolean to be on the stack");
                }
            }
            Token::MrBeast(jump_addr) | Token::Else(jump_addr) => {
                i = *jump_addr;
                continue;
            } // token => todo!("Not yet impld {token:?}"),
        }
        i += 1;
    }
    eprintln!();
    Ok(stack)
}