dark_vm/errors/
error.rs

1//! The Error struct maintains the errors that occur during execution.
2
3use super::error_kind::ErrorKind;
4
5pub struct Error {
6    kind: ErrorKind,
7    position: Option<usize>,
8}
9
10impl Error {
11    /// Constructs a new error with the error kind and the position.
12    ///
13    /// # Arguments
14    /// `kind` - The value of the error. Maintaining the value allows for the messages to be controlled across execution.
15    /// `position` - The position where the error occurred.
16    pub fn new(kind: ErrorKind, position: usize) -> Error {
17        Error {
18            kind,
19            position: Some(position),
20        }
21    }
22
23    /// Constructs a new error with the error kind and no position.
24    ///
25    /// # Arguments
26    /// `kind` - The value of the error. Maintaining the value allows for the messages to be controlled across execution.
27    pub fn message_only(kind: ErrorKind) -> Error {
28        Error {
29            kind,
30            position: None,
31        }
32    }
33
34    /// This function generates a pretty version of the error, with arrows pointing to the exact location of the error.
35    /// This function also consumes the error, therefore, it should be the last thing called.
36    ///
37    /// # Arguments
38    /// `input` - The input for the program. This is not maintained with every error because the input might be different.
39    pub fn prettify(self, input: &str) -> String {
40        if self.position.is_some() {
41            // Get the line and column number of where the error occurred.
42            let (line_number, column_number) = self.get_line_column_info(input);
43
44            // Check if a line is present. If not, the error is printed without the arrows.
45            // This should usually produce a line, but it may not.
46            let option_line = input.split_terminator('\n').nth(line_number - 1);
47
48            // Convert the kind into an error message.
49            let error_message: String = self.kind.into();
50            if let Some(line) = option_line {
51                let len = line_number.to_string().len();
52                format!(
53                    "{} |\n{} | {}\n{} | {}^-- {}\n",
54                    " ".repeat(len),
55                    line_number,
56                    line,
57                    " ".repeat(len),
58                    " ".repeat(column_number - 1),
59                    error_message,
60                )
61            } else {
62                format!(
63                    "An Error Occurred On Line {} And Column {}.\n{}",
64                    line_number, column_number, error_message,
65                )
66            }
67        } else {
68            // Convert the kind into an error message.
69            let error_message: String = self.kind.into();
70            format!("An Error Occurred.\n{}", error_message)
71        }
72    }
73
74    /// This function gets the line and column number of where the error occurred with respect to the input.
75    fn get_line_column_info(&self, input: &str) -> (usize, usize) {
76        let (mut line_number, mut column_number) = (1, 0);
77
78        // Go through the characters and find the index that matches the position given in the error struct.
79        input.chars().enumerate().find(|(idx, ch)| {
80            if ch == &'\n' {
81                line_number += 1;
82                column_number = 0;
83            } else {
84                column_number += 1;
85            }
86
87            idx == &(self.position.unwrap() - 1)
88        });
89
90        (line_number, column_number)
91    }
92}