error.rs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use colour::{e_prnt_ln, e_red};
  2. pub struct LexerError {
  3. file: String,
  4. lines: Vec<String>,
  5. }
  6. impl LexerError {
  7. pub fn new(file: &str, lines: Vec<String>) -> Self {
  8. LexerError { file: file.to_string(), lines }
  9. }
  10. pub fn invalid_token(&self, t: char, ln: usize, col: usize) {
  11. let err_msg = format!("Invalid token `{}` on line {} (column {})\n", t, ln, col);
  12. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  13. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  14. let caret = format!("{:width$}^", "", width = pad);
  15. let msg = format!("{}\n{}\n{}", err_msg, dbg_msg, caret);
  16. LexerError::lexer_error(&msg);
  17. }
  18. pub fn invalid_string(&self, s: &str, ln: usize, col: usize) {
  19. let err_msg = format!("Invalid ending in string `{}` on line {} (column {})", s, ln, col);
  20. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  21. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  22. let caret = format!("{:width$}^", "", width = pad);
  23. let msg = format!("{}\n{}\n{}", err_msg, dbg_msg, caret);
  24. LexerError::lexer_error(&msg);
  25. }
  26. pub fn invalid_symbol(&self, s: &str, ln: usize, col: usize) {
  27. let err_msg = format!("Illegal char `{}` for symbol on line {} (column {})", s, ln, col);
  28. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  29. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  30. let caret = format!("{:width$}^", "", width = pad);
  31. let msg = format!("{}\n{}\n{}", err_msg, dbg_msg, caret);
  32. LexerError::lexer_error(&msg);
  33. }
  34. fn lexer_error(msg: &str) {
  35. e_red!("Lexer error: ");
  36. e_prnt_ln!("{}", msg);
  37. std::process::exit(1);
  38. }
  39. }
  40. pub struct ParserError {
  41. file: String,
  42. lines: Vec<String>,
  43. }
  44. impl ParserError {
  45. pub fn new(file: &str, lines: Vec<String>) -> Self {
  46. ParserError { file: file.to_string(), lines }
  47. }
  48. pub fn invalid_section_declaration(&self, s: &str, m: &str, ln: usize, col: usize) {
  49. let err_msg =
  50. format!("Invalid `{}` section declaration on line {} (column {})", s, ln, col);
  51. let err_msg = format!("{}\n{}", err_msg, m);
  52. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  53. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  54. let caret = format!("{:width$}^", "", width = pad);
  55. let msg = format!("{}\n{}\n{}", err_msg, dbg_msg, caret);
  56. ParserError::parser_error(&msg);
  57. }
  58. fn parser_error(msg: &str) {
  59. e_red!("Parser error: ");
  60. e_prnt_ln!("{}", msg);
  61. std::process::exit(1);
  62. }
  63. }