PrintLib/
error.rs

1use crate::colorize::Colorize;
2
3pub struct ErrorFactory {
4    ecode: String,
5    msg: String,
6    fmt_lines: Vec<String>,
7    before_len: usize,
8}
9
10impl ErrorFactory {
11    pub fn new(_ecode: String, _msg: String) -> Self {
12        ErrorFactory {
13            ecode: _ecode,
14            msg: _msg,
15            fmt_lines: Vec::new(),
16            before_len: 3,
17        }
18    }
19
20    pub fn add_code_line(
21        &mut self,
22        line: String,
23        display_line_no: bool,
24        line_no: usize,
25        display_add: bool,
26    ) {
27        let mut code_line = String::new();
28
29        if display_line_no {
30            code_line += line_no.to_string().as_str();
31        } else if display_add {
32            code_line += "+++";
33        }
34
35        code_line += " | ";
36
37        self.before_len = code_line.clone().len() - 1;
38
39        code_line += line.as_str();
40
41        self.fmt_lines.push(code_line);
42    }
43
44    pub fn add_where(
45        &mut self,
46        where_start: usize,
47        where_length: usize,
48        where_msg_b: bool,
49        where_msg: String,
50    ) {
51        let mut where_str = String::new();
52
53        where_str += " ".repeat(where_start + self.before_len).as_str();
54
55        if where_msg_b {
56            where_str += format!("^{}", where_msg).as_str();
57        } else {
58            where_str += "^".repeat(where_length).as_str();
59        }
60
61        self.fmt_lines.push(where_str);
62    }
63
64    pub fn add_arrow(&mut self, file: String, line: usize, where_start: usize) {
65        let arrow = format!("  -->{}:{}:{}", file, line, where_start);
66
67        self.fmt_lines.push(arrow);
68    }
69
70    pub fn add_arrow_w(&mut self, file: String, line: usize) {
71        let arrow = format!("  -->{}:{}", file, line);
72
73        self.fmt_lines.push(arrow);
74    }
75
76    pub fn print(&self) {
77        let fmt_error = format!("error[{}]", self.ecode).red();
78        println!("{}: {}", fmt_error, self.msg.bold());
79
80        //print out all elements of self.fmt_lines
81        for line in self.fmt_lines.iter() {
82            println!("{}", line);
83        }
84    }
85}