whamm 0.1.0

A framework for 'Wasm Application Monitoring and Manipulation'
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
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
use crate::common::terminal::{blue, red, white, yellow};
use crate::parser::types::{Location, Rule};
use pest::error::ErrorVariant::ParsingError;
use pest::error::{Error, LineColLocation};
use std::borrow::Cow;
use std::{cmp, mem};
use termcolor::{Buffer, BufferWriter, ColorChoice, WriteColor};

const ERR_UNDERLINE_CHAR: char = '^';
const INFO_UNDERLINE_CHAR: char = '-';

pub struct ErrorGen {
    curr_match_rule: Option<String>,
    script_path: String,
    script_text: String,
    max_errors: i32,
    errors: Vec<WhammError>,
    warnings: Vec<WhammWarning>,
    num_errors: i32,
    pub too_many: bool,
    pub has_errors: bool,
    pub has_warnings: bool,
}
impl ErrorGen {
    pub fn new(script_path: String, script_text: String, max_errors: i32) -> Self {
        Self {
            curr_match_rule: None,
            script_path,
            script_text,
            max_errors,
            errors: vec![],
            warnings: vec![],
            num_errors: 0,
            too_many: false,
            has_errors: false,
            has_warnings: false,
        }
    }

    pub fn pull_errs(&self) -> Vec<WhammError> {
        self.errors.to_owned()
    }

    pub fn update_match_rule(&mut self, match_rule: Option<String>) {
        self.curr_match_rule = match_rule;
    }

    pub fn add_error(&mut self, mut error: WhammError) {
        error.match_rule = self.curr_match_rule.clone();
        self.errors.push(error);
        self.inc_errors();
    }

    pub fn add_errors(&mut self, errors: Vec<WhammError>) -> Result<(), ()> {
        for error in errors {
            self.add_error(error);
        }

        if self.too_many {
            Err(())
        } else {
            Ok(())
        }
    }

    pub fn set_script_text(&mut self, script_text: String) {
        self.script_text = script_text;
    }

    pub fn report_warnings(&mut self) {
        self.warnings.iter_mut().for_each(|warning| {
            warning.report(&self.script_text, &self.script_path);
        });
        self.warnings.clear();
    }

    pub fn report(&mut self) {
        self.report_warnings();
        // Report the most-recent error first
        self.errors.iter_mut().for_each(|error| {
            error.report(&self.script_text, &self.script_path);
        });
        self.errors.clear();
    }

    // ======================
    // == Error Generators ==
    // ======================

    fn get_error_loc(message: &str, loc: &Option<Location>) -> Option<CodeLocation> {
        loc.as_ref().map(|err_loc| CodeLocation {
            ty: LocType::Err,
            message: Some(message.to_string()),
            line_col: err_loc.line_col.clone(),
            line_str: None,
            line2_str: None,
        })
    }

    fn get_warn_loc(message: &str, loc: &Option<Location>) -> Option<CodeLocation> {
        loc.as_ref().map(|err_loc| CodeLocation {
            ty: LocType::Warn,
            message: Some(message.to_string()),
            line_col: err_loc.line_col.clone(),
            line_str: None,
            line2_str: None,
        })
    }

    pub fn get_unimplemented_error(message: &str, loc: &Option<Location>) -> WhammError {
        WhammError {
            match_rule: None,
            err_loc: Self::get_error_loc(message, loc),
            ty: ErrorType::UnimplementedError {
                message: message.to_string(),
            },
            info_loc: None,
        }
    }
    pub fn add_unimplemented_error(&mut self, msg: &str, loc: &Option<Location>) {
        self.add_error(Self::get_unimplemented_error(msg, loc));
    }

    pub fn get_internal_error(message: &str, loc: &Option<Location>) -> WhammError {
        WhammError {
            match_rule: None,
            err_loc: Self::get_error_loc(message, loc),
            ty: ErrorType::InternalError {
                message: message.to_string(),
            },
            info_loc: None,
        }
    }
    pub fn add_internal_error(&mut self, msg: &str, loc: &Option<Location>) {
        self.add_error(Self::get_internal_error(msg, loc));
    }

    pub fn get_instrumentation_error(message: &str) -> WhammError {
        WhammError {
            match_rule: None,
            ty: ErrorType::InstrumentationError {
                message: message.to_string(),
            },
            err_loc: None,
            info_loc: None,
        }
    }
    pub fn add_instr_error(&mut self, msg: &str) {
        self.add_error(Self::get_instrumentation_error(msg));
    }

    pub fn multiple_alt_matches(&mut self, instr_name: &str) {
        let msg = &format!(
            "Multiple `alt` probes matched same bytecode location for instr_name: {}",
            instr_name
        );
        self.add_error(Self::get_instrumentation_error(msg));
    }

    pub fn get_arithmetic_error(message: &str, loc: Option<Location>) -> WhammError {
        WhammError {
            match_rule: None,
            err_loc: Self::get_error_loc(message, &loc),
            ty: ErrorType::ArithmeticError {
                message: message.to_string(),
            },
            info_loc: None,
        }
    }

    pub fn div_by_zero(&mut self, loc: Option<Location>) {
        let err = Self::get_arithmetic_error("attempt to divide by zero", loc);
        self.add_error(err);
    }

    pub fn get_parse_error(
        message: Option<String>,
        line_col: Option<LineColLocation>,
        positives: Vec<Rule>,
        negatives: Vec<Rule>,
    ) -> WhammError {
        if let Some(line_col) = line_col {
            WhammError {
                match_rule: None,
                ty: ErrorType::ParsingError {
                    positives,
                    negatives,
                    message: message.clone(),
                },
                err_loc: Some(CodeLocation {
                    ty: LocType::Err,
                    message,
                    line_col,
                    line_str: None,
                    line2_str: None,
                }),
                info_loc: None,
            }
        } else {
            WhammError {
                match_rule: None,
                ty: ErrorType::ParsingError {
                    positives,
                    negatives,
                    message: message.clone(),
                },
                err_loc: None,
                info_loc: None,
            }
        }
    }
    pub fn parse_error_at_loc(&mut self, message: Option<String>, line_col: Option<Location>) {
        let err_loc = line_col.as_ref().map(|err_loc| err_loc.line_col.clone());
        let err = Self::get_parse_error(message, err_loc, vec![], vec![]);
        self.add_error(err);
    }

    pub fn parse_error(
        &mut self,
        message: Option<String>,
        line_col: Option<LineColLocation>,
        positives: Vec<Rule>,
        negatives: Vec<Rule>,
    ) {
        let err = Self::get_parse_error(message, line_col, positives, negatives);
        self.add_error(err);
    }

    pub fn get_duplicate_identifier_error(
        duplicated_id: String,
        err_line_col: Option<LineColLocation>,
        info_line_col: Option<LineColLocation>,
    ) -> WhammError {
        let err_loc = err_line_col.map(|err_line_col| CodeLocation {
            ty: LocType::Err,
            message: Some(format!("duplicate definitions for `{}`", duplicated_id)),
            line_col: err_line_col,
            line_str: None,
            line2_str: None,
        });
        let info_loc = info_line_col.map(|info_line_col| CodeLocation {
            ty: LocType::Info,
            message: Some(format!("other definition for `{}`", duplicated_id)),
            line_col: info_line_col,
            line_str: None,
            line2_str: None,
        });

        WhammError {
            match_rule: None,
            ty: ErrorType::DuplicateIdentifierError {
                duplicated_id: duplicated_id.clone(),
            },
            err_loc,
            info_loc,
        }
    }
    pub fn get_compiler_fn_overload_error(
        duplicated_id: String,
        loc: Option<LineColLocation>,
    ) -> WhammError {
        let err_loc = loc.map(|err_line_col| CodeLocation {
            ty: LocType::Err,
            message: Some(format!(
                "`{}` is an identifier used by compiler. Neither overloading nor overriding is supported",
                duplicated_id
            )),
            line_col: err_line_col,
            line_str: None,
            line2_str: None,
        });

        WhammError {
            match_rule: None,
            ty: ErrorType::DuplicateIdentifierError {
                duplicated_id: duplicated_id.clone(),
            },
            err_loc,
            info_loc: None,
        }
    }
    pub fn compiler_fn_overload_error(
        &mut self,
        duplicated_id: String,
        loc: Option<LineColLocation>,
    ) {
        let err = Self::get_compiler_fn_overload_error(duplicated_id, loc);
        self.add_error(err);
    }
    pub fn duplicate_identifier_error(
        &mut self,
        duplicated_id: String,
        err_line_col: Option<LineColLocation>,
        info_line_col: Option<LineColLocation>,
    ) {
        let err = Self::get_duplicate_identifier_error(duplicated_id, err_line_col, info_line_col);
        self.add_error(err);
    }
    pub fn get_type_check_error(message: String, loc: &Option<LineColLocation>) -> WhammError {
        let loc = loc.as_ref().map(|loc| CodeLocation {
            ty: LocType::Err,
            message: Some(message.clone()),
            line_col: loc.clone(),
            line_str: None,
            line2_str: None,
        });

        WhammError {
            match_rule: None,
            ty: ErrorType::TypeCheckError {
                message: message.clone(),
            },
            err_loc: loc,
            info_loc: None,
        }
    }

    pub fn type_check_error(&mut self, message: String, line_col: &Option<LineColLocation>) {
        let err = Self::get_type_check_error(message, line_col);
        self.add_error(err);
    }
    pub fn get_wei_error(message: String, loc: &Option<LineColLocation>) -> WhammError {
        let loc = loc.as_ref().map(|loc| CodeLocation {
            ty: LocType::Err,
            message: Some(message.clone()),
            line_col: loc.clone(),
            line_str: None,
            line2_str: None,
        });

        WhammError {
            match_rule: None,
            ty: ErrorType::WeiError {
                message: message.clone(),
            },
            err_loc: loc,
            info_loc: None,
        }
    }

    pub fn get_wei_error_from_loc(message: String, line_col: &Option<Location>) -> WhammError {
        let loc = line_col.as_ref().map(|loc| loc.line_col.clone());
        Self::get_wei_error(message, &loc)
    }

    pub fn wei_error(&mut self, message: String, loc: &Option<Location>) {
        let err = Self::get_wei_error_from_loc(message, loc);
        self.add_error(err);
    }

    pub fn pest_err(&mut self, e: Error<Rule>) {
        let line = e.line().to_string();

        // calculate `line2`
        let line2 = if let LineColLocation::Span(..) = &e.line_col {
            // pull out the `line2` from the error msg
            let orig_msg = e.to_string();
            // get last line that starts with a number
            // See code the following code for why we can do this:
            // https://github.com/pest-parser/pest/blob/master/pest/src/error.rs#L612
            let mut lines = orig_msg.lines();
            lines
                .rfind(|line| line.as_bytes()[0].is_ascii_digit())
                .map(|line| line.to_string())
        } else {
            None
        };

        let error = if let ParsingError {
            positives,
            negatives,
        } = &e.variant
        {
            WhammError {
                match_rule: self.curr_match_rule.clone(),
                ty: ErrorType::ParsingError {
                    positives: positives.clone(),
                    negatives: negatives.clone(),
                    message: None,
                },
                err_loc: Some(CodeLocation {
                    ty: LocType::Err,
                    message: None,
                    line_col: e.line_col.clone(),
                    line_str: Some(line),
                    line2_str: line2,
                }),
                info_loc: None,
            }
        } else {
            WhammError {
                match_rule: self.curr_match_rule.clone(),
                ty: ErrorType::Error { message: None },
                err_loc: Some(CodeLocation {
                    ty: LocType::Err,
                    message: None,
                    line_col: e.line_col.clone(),
                    line_str: Some(line),
                    line2_str: line2,
                }),
                info_loc: None,
            }
        };
        self.add_error(error);
    }

    fn inc_errors(&mut self) {
        self.num_errors += 1;
        self.has_errors = true;
        if self.num_errors >= self.max_errors {
            self.too_many = true;
        }
    }

    // ==================
    // ==== WARNINGS ====
    // ==================

    pub fn add_warn(&mut self, warn: WhammWarning) {
        self.warnings.push(warn);
        self.has_warnings = true;
    }
    pub fn get_probe_warning(message: &str, loc: &Option<Location>) -> WhammWarning {
        WhammWarning {
            match_rule: None,
            ty: WarnType::ProbeWarning {
                message: message.to_string(),
            },
            warn_loc: Self::get_warn_loc(message, loc),
            info_loc: None,
        }
    }
    pub fn add_probe_warn(&mut self, message: &str, loc: &Option<Location>) {
        self.add_warn(Self::get_probe_warning(message, loc));
    }
    pub fn add_typecheck_warn(&mut self, message: String, loc: Option<LineColLocation>) {
        let loc = loc.as_ref().map(|loc| CodeLocation {
            ty: LocType::Warn,
            message: Some(message.clone()),
            line_col: loc.clone(),
            line_str: None,
            line2_str: None,
        });
        let warn = WhammWarning {
            match_rule: self.curr_match_rule.clone(),
            ty: WarnType::TypeCheckWarning { message },
            warn_loc: loc,
            info_loc: None,
        };
        self.add_warn(warn);
    }
}

#[derive(Clone, Debug)]
enum LocType {
    /// Is an error-causing code location
    Err,
    /// Is a warning-causing code location
    Warn,
    /// Is just informational
    Info,
}
#[derive(Clone, Debug)]
pub struct CodeLocation {
    ty: LocType,
    // The message associated with this location in the source code
    pub message: Option<String>,
    // The line/column in the source code
    pub line_col: LineColLocation,
    // The line in the source code containing the error
    pub line_str: Option<String>,
    // Possibly a second line if the line_col spans multiple lines
    pub line2_str: Option<String>,
}
impl CodeLocation {
    pub fn is_span(&self) -> bool {
        matches!(self.line_col, LineColLocation::Span(..))
    }
    pub fn lines_are_defined(&self) -> bool {
        self.line_str.is_some()
    }

    // report this error to the console, including color highlighting
    pub fn print(&mut self, script: &str, spacing: &str, buffer: &mut Buffer) {
        if !self.lines_are_defined() {
            self.define_lines(script);
        }

        if let Some(line) = &self.line_str {
            // define common vars for printing
            let (ls, _) = self.start();
            if let (LineColLocation::Span(_, (le, _)), Some(ref line2)) =
                (&self.line_col, &self.line2_str)
            {
                let has_line_gap = le - ls > 1;

                if has_line_gap {
                    self.print_numbered_line(ls, line, spacing, buffer);
                    self.print_norm("...", spacing, buffer);
                    self.print_numbered_line(le, line2, spacing, buffer);
                } else {
                    self.print_numbered_line(ls, line, spacing, buffer);
                    self.print_numbered_line(le, line2, spacing, buffer);
                }
            } else {
                self.print_numbered_line(ls, line, spacing, buffer);
            };

            self.print_underline(spacing, buffer);
        }
    }

    fn define_lines(&mut self, script: &str) {
        match &self.line_col {
            LineColLocation::Pos((line_no, ..)) => {
                if let Some(script_line) = script.lines().nth(line_no - 1) {
                    self.line_str = Some(script_line.to_string());
                }
            }
            LineColLocation::Span((s0_line, ..), (s1_line, ..)) => {
                if let Some(script_line) = script.lines().nth(s0_line - 1) {
                    self.line_str = Some(script_line.to_string());
                }
                if s0_line != s1_line {
                    if let Some(script_line) = script.lines().nth(s1_line - 1) {
                        self.line2_str = Some(script_line.to_string());
                    }
                }
            }
        }
    }

    fn print_numbered_line(&self, l: &usize, line: &String, s: &str, buffer: &mut Buffer) {
        let w = s.len();
        blue(false, format!("{l:w$} | "), buffer);
        white(false, format!("{line}\n"), buffer);
    }

    fn print_line_start(&self, s: &str, buffer: &mut Buffer) {
        blue(false, format!("{s} | "), buffer);
    }

    fn print_underline(&self, s: &str, buffer: &mut Buffer) {
        let (_, col) = self.start();
        let underline = self.underline(col);
        let message = if let Some(msg) = &self.message {
            msg.clone()
        } else {
            "".to_string()
        };

        self.print_line_start(s, buffer);
        let color = match self.ty {
            LocType::Err => red,
            LocType::Warn => yellow,
            LocType::Info => blue,
        };
        color(false, format!("{underline} {message}\n"), buffer);
    }

    fn print_norm(&self, line: &str, s: &str, buffer: &mut Buffer) {
        self.print_line_start(s, buffer);
        white(false, format!("{line}\n"), buffer);
    }

    fn underline(&self, start_col: &usize) -> String {
        let mut underline = String::new();

        let mut start_col = *start_col;
        let end = match &self.line_col {
            LineColLocation::Span(_, (_, mut end)) => {
                let inverted_cols = start_col > end;
                if inverted_cols {
                    mem::swap(&mut start_col, &mut end);
                    start_col -= 1;
                    end += 1;
                }

                Some(end)
            }
            _ => None,
        };
        let offset = start_col - 1;

        if let Some(line) = &self.line_str {
            let line_chars = line.chars();

            for c in line_chars.take(offset) {
                match c {
                    '\t' => underline.push('\t'),
                    _ => underline.push(' '),
                }
            }
        }

        if let Some(end) = end {
            let u_char = match self.ty {
                LocType::Err => ERR_UNDERLINE_CHAR,
                LocType::Warn | LocType::Info => INFO_UNDERLINE_CHAR,
            };

            underline.push(u_char);
            if end - start_col > 1 {
                for _ in 2..(end - start_col) {
                    underline.push(u_char);
                }
                underline.push(u_char);
            }
        } else {
            underline.push_str("^---")
        }

        underline
    }

    fn start(&self) -> &(usize, usize) {
        match &self.line_col {
            LineColLocation::Pos(line_col) => line_col,
            LineColLocation::Span(start_line_col, _) => start_line_col,
        }
    }
}
#[derive(Clone, Debug)]
pub struct WhammError {
    pub match_rule: Option<String>,
    /// The location within the input string causing the error
    pub err_loc: Option<CodeLocation>,
    /// A location within the input string that can add context to the error
    pub info_loc: Option<CodeLocation>,
    pub ty: ErrorType,
}

impl From<std::io::Error> for Box<WhammError> {
    fn from(e: std::io::Error) -> Self {
        Box::new(WhammError {
            match_rule: None,
            err_loc: None,
            info_loc: None,
            ty: ErrorType::Error {
                message: Some(e.to_string()),
            },
        })
    }
}

pub struct WhammWarning {
    pub match_rule: Option<String>,
    pub ty: WarnType,
    pub warn_loc: Option<CodeLocation>,
    pub info_loc: Option<CodeLocation>,
}
impl WhammWarning {
    pub fn report(&mut self, script: &str, script_path: &String) {
        let spacing = self.spacing();
        let message = self.ty.message();

        let writer = BufferWriter::stderr(ColorChoice::Always);
        let mut buffer = writer.buffer();

        let preamble = if let Some(rule) = &self.match_rule {
            format!("warning[{}]@{rule}", self.ty.name())
        } else {
            format!("warning[{}]", self.ty.name())
        };
        yellow(true, preamble, &mut buffer);
        white(true, format!(": {}\n", message), &mut buffer);

        if let Some(warn_loc) = &mut self.warn_loc {
            if warn_loc.message.is_none() {
                warn_loc.message = Some(message.clone().to_string());
            }

            print_preamble(&warn_loc.line_col, script_path, &spacing, &mut buffer);
            print_empty(&spacing, &mut buffer);
            let warn_start = match &warn_loc.line_col {
                LineColLocation::Pos((line, _)) => line,
                LineColLocation::Span((start_line, _), ..) => start_line,
            };
            if let Some(info_loc) = &mut self.info_loc {
                let info_start = match &info_loc.line_col {
                    LineColLocation::Pos((line, _)) => line,
                    LineColLocation::Span((start_line, _), ..) => start_line,
                };

                if info_start < warn_start {
                    // print info first
                    info_loc.print(script, &spacing, &mut buffer);
                    warn_loc.print(script, &spacing, &mut buffer);
                } else {
                    // print err first
                    warn_loc.print(script, &spacing, &mut buffer);
                    info_loc.print(script, &spacing, &mut buffer);
                }
            } else {
                // only print err
                warn_loc.print(script, &spacing, &mut buffer);
            }
            print_empty(&spacing, &mut buffer);
        } else {
            // This error isn't tied to a specific code location
            blue(false, " --> ".to_string(), &mut buffer);
            blue(false, format!("{script_path}\n\n"), &mut buffer);
        }
        writer
            .print(&buffer)
            .expect("Uh oh, something went wrong while printing to terminal");
        buffer
            .reset()
            .expect("Uh oh, something went wrong while printing to terminal");
    }
    fn spacing(&self) -> String {
        let largest_err_line_no = if let Some(warn_loc) = &self.warn_loc {
            match &warn_loc.line_col {
                LineColLocation::Pos((line, _)) => line,
                LineColLocation::Span((start_line, _), (end_line, _)) => {
                    cmp::max(start_line, end_line)
                }
            }
        } else {
            // No err_line, return empty string
            return "".to_string();
        };
        let largest_info_line_no = if let Some(info_loc) = &self.info_loc {
            match &info_loc.line_col {
                LineColLocation::Pos((line, _)) => line,
                LineColLocation::Span((start_line, _), (end_line, _)) => {
                    cmp::max(start_line, end_line)
                }
            }
        } else {
            // Assuming if we get here, there IS an err_line_no set; just
            // return a "short" number
            &0
        };
        let largest_line_no = cmp::max(largest_err_line_no, largest_info_line_no);

        // calculate the length of the longest line number (in chars)
        let line_str_len = format!("{}", largest_line_no).len();

        let mut spacing = String::new();
        for _ in 0..line_str_len {
            spacing.push(' ');
        }

        spacing
    }
}
impl WhammError {
    /// report this error to the console, including color highlighting
    pub fn report(&mut self, script: &str, script_path: &String) {
        let spacing = self.spacing();
        let message = self.ty.message();

        let writer = BufferWriter::stderr(ColorChoice::Always);
        let mut buffer = writer.buffer();

        let preamble = if let Some(rule) = &self.match_rule {
            format!("error[{}]@{rule}", self.ty.name())
        } else {
            format!("error[{}]", self.ty.name())
        };
        red(true, preamble, &mut buffer);
        white(true, format!(": {}\n", message), &mut buffer);

        if let Some(err_loc) = &mut self.err_loc {
            if err_loc.message.is_none() {
                err_loc.message = Some(message.clone().to_string());
            }

            print_preamble(&err_loc.line_col, script_path, &spacing, &mut buffer);
            print_empty(&spacing, &mut buffer);
            let err_start = match &err_loc.line_col {
                LineColLocation::Pos((line, _)) => line,
                LineColLocation::Span((start_line, _), ..) => start_line,
            };
            if let Some(info_loc) = &mut self.info_loc {
                let info_start = match &info_loc.line_col {
                    LineColLocation::Pos((line, _)) => line,
                    LineColLocation::Span((start_line, _), ..) => start_line,
                };

                if info_start < err_start {
                    // print info first
                    info_loc.print(script, &spacing, &mut buffer);
                    err_loc.print(script, &spacing, &mut buffer);
                } else {
                    // print err first
                    err_loc.print(script, &spacing, &mut buffer);
                    info_loc.print(script, &spacing, &mut buffer);
                }
            } else {
                // only print err
                err_loc.print(script, &spacing, &mut buffer);
            }
            print_empty(&spacing, &mut buffer);
        } else {
            // This error isn't tied to a specific code location
            blue(false, " --> ".to_string(), &mut buffer);
            blue(false, format!("{script_path}\n\n"), &mut buffer);
        }
        writer
            .print(&buffer)
            .expect("Uh oh, something went wrong while printing to terminal");
        buffer
            .reset()
            .expect("Uh oh, something went wrong while printing to terminal");
    }

    fn spacing(&self) -> String {
        let largest_err_line_no = if let Some(err_loc) = &self.err_loc {
            match &err_loc.line_col {
                LineColLocation::Pos((line, _)) => line,
                LineColLocation::Span((start_line, _), (end_line, _)) => {
                    cmp::max(start_line, end_line)
                }
            }
        } else {
            // No err_line, return empty string
            return "".to_string();
        };
        let largest_info_line_no = if let Some(info_loc) = &self.info_loc {
            match &info_loc.line_col {
                LineColLocation::Pos((line, _)) => line,
                LineColLocation::Span((start_line, _), (end_line, _)) => {
                    cmp::max(start_line, end_line)
                }
            }
        } else {
            // Assuming if we get here, there IS an err_line_no set; just
            // return a "short" number
            &0
        };
        let largest_line_no = cmp::max(largest_err_line_no, largest_info_line_no);

        // calculate the length of the longest line number (in chars)
        let line_str_len = format!("{}", largest_line_no).len();

        let mut spacing = String::new();
        for _ in 0..line_str_len {
            spacing.push(' ');
        }

        spacing
    }
}
pub enum WarnType {
    ProbeWarning { message: String },
    TypeCheckWarning { message: String },
}
impl WarnType {
    pub fn name(&self) -> &str {
        match self {
            WarnType::ProbeWarning { .. } => "ProbeWarning",
            WarnType::TypeCheckWarning { .. } => "TypeCheckWarning",
        }
    }
    pub fn message(&self) -> Cow<'_, str> {
        match self {
            WarnType::ProbeWarning { ref message } | WarnType::TypeCheckWarning { ref message } => {
                Cow::Borrowed(message)
            }
        }
    }
}
#[derive(Clone, Debug)]
pub enum ErrorType {
    UnimplementedError {
        message: String,
    },
    InternalError {
        message: String,
    },
    InstrumentationError {
        message: String,
    },
    DuplicateIdentifierError {
        duplicated_id: String,
    },
    /// Generated parsing error with expected and unexpected `Rule`s
    ParsingError {
        /// Positive attempts
        positives: Vec<Rule>,
        /// Negative attempts
        negatives: Vec<Rule>,
        message: Option<String>,
    },
    /// Error during type checking
    TypeCheckError {
        message: String,
    },
    /// Error when compiling to wei target
    WeiError {
        message: String,
    },
    Error {
        message: Option<String>,
    },
    ArithmeticError {
        message: String,
    },
}
impl ErrorType {
    pub fn name(&self) -> &str {
        match self {
            ErrorType::UnimplementedError { .. } => "Unimplemented",
            ErrorType::InternalError { .. } => "InternalError",
            ErrorType::InstrumentationError { .. } => "InstrumentationError",
            ErrorType::DuplicateIdentifierError { .. } => "DuplicateIdentifierError",
            ErrorType::ParsingError { .. } => "ParsingError",
            ErrorType::TypeCheckError { .. } => "TypeCheckError",
            ErrorType::WeiError { .. } => "WeiError",
            ErrorType::Error { .. } => "GeneralError",
            ErrorType::ArithmeticError { .. } => "ArithmeticError",
        }
    }
    pub fn message(&self) -> Cow<'_, str> {
        match self {
            ErrorType::UnimplementedError { ref message }
            | ErrorType::InternalError { ref message }
            | ErrorType::ArithmeticError { ref message }
            | ErrorType::InstrumentationError { ref message } => Cow::Borrowed(message),
            ErrorType::ParsingError {
                ref positives,
                ref negatives,
                ref message,
            } => Cow::Owned(Self::parsing_error_message(
                message,
                positives,
                negatives,
                |r| format!("{:?}", r),
            )),
            ErrorType::TypeCheckError { ref message } | ErrorType::WeiError { ref message } => {
                Cow::Borrowed(message)
            }
            ErrorType::DuplicateIdentifierError { ref duplicated_id } => {
                Cow::Owned(format!("duplicate definitions with name `{duplicated_id}`"))
            }
            ErrorType::Error { ref message } => {
                if let Some(msg) = message {
                    Cow::Borrowed(msg)
                } else {
                    Cow::Borrowed("An error occurred.")
                }
            }
        }
    }

    fn parsing_error_message<F>(
        message: &Option<String>,
        positives: &[Rule],
        negatives: &[Rule],
        mut f: F,
    ) -> String
    where
        F: FnMut(&Rule) -> String,
    {
        let preamble = if let Some(msg) = message {
            let mut s = msg.to_string();
            if !negatives.is_empty() && !positives.is_empty() {
                s += " -- ";
            }
            s
        } else {
            "".to_string()
        };
        match (negatives.is_empty(), positives.is_empty()) {
            (false, false) => format!(
                "{}unexpected {}; expected {}",
                preamble,
                ErrorType::enumerate(negatives, &mut f),
                ErrorType::enumerate(positives, &mut f)
            ),
            (false, true) => format!(
                "{}unexpected {}",
                preamble,
                ErrorType::enumerate(negatives, &mut f)
            ),
            (true, false) => format!(
                "{}expected {}",
                preamble,
                ErrorType::enumerate(positives, &mut f)
            ),
            (true, true) => {
                if preamble.is_empty() {
                    "unknown parsing error".to_owned()
                } else {
                    preamble
                }
            }
        }
    }

    fn enumerate<F>(rules: &[Rule], f: &mut F) -> String
    where
        F: FnMut(&Rule) -> String,
    {
        match rules.len() {
            1 => f(&rules[0]),
            2 => format!("{} or {}", f(&rules[0]), f(&rules[1])),
            l => {
                let non_separated = f(&rules[l - 1]);
                let separated = rules
                    .iter()
                    .take(l - 1)
                    .map(f)
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{}, or {}", separated, non_separated)
            }
        }
    }
}

fn print_preamble(
    line_col: &LineColLocation,
    script_path: &String,
    s: &String,
    buffer: &mut Buffer,
) {
    let (ls, c) = match line_col {
        LineColLocation::Pos(line_col) => line_col,
        LineColLocation::Span(start_line_col, _) => start_line_col,
    };

    blue(false, format!("{s}--> "), buffer);
    blue(false, format!("{script_path}:"), buffer);
    blue(false, format!("{ls}:{c}\n"), buffer);
}

fn print_line(line: &str, is_err: bool, s: &String, buffer: &mut Buffer) {
    blue(false, format!("{s} | "), buffer);
    if is_err {
        red(false, format!("{line}\n"), buffer);
    } else {
        white(false, format!("{line}\n"), buffer);
    }
}

fn print_empty(s: &String, buffer: &mut Buffer) {
    print_line("", false, s, buffer);
}