error.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::io::{self, Error, ErrorKind, Write};
  19. pub(super) struct ErrorEmitter {
  20. namespace: String,
  21. file: String,
  22. lines: Vec<String>,
  23. }
  24. impl ErrorEmitter {
  25. pub fn new(namespace: &str, file: &str, lines: Vec<String>) -> Self {
  26. Self { namespace: namespace.to_string(), file: file.to_string(), lines }
  27. }
  28. fn fmt(&self, msg: String, ln: usize, col: usize) -> String {
  29. let (err_msg, dbg_msg, caret) = match ln {
  30. 0 => (msg, "".to_string(), "".to_string()),
  31. _ => {
  32. let err_msg = format!("{} (line {}, column {})", msg, ln, col);
  33. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  34. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 1;
  35. let caret = format!("{:width$}^", "", width = pad);
  36. (err_msg, dbg_msg, caret)
  37. }
  38. };
  39. format!("{}\n{}\n{}\n", err_msg, dbg_msg, caret)
  40. }
  41. pub fn abort(&self, msg: &str, ln: usize, col: usize) -> Error {
  42. let m = self.fmt(msg.to_string(), ln, col);
  43. self.emit("error", &m);
  44. Error::new(ErrorKind::Other, m)
  45. }
  46. pub fn warn(&self, msg: &str, ln: usize, col: usize) {
  47. let m = self.fmt(msg.to_string(), ln, col);
  48. self.emit("warning", &m);
  49. }
  50. pub fn emit(&self, typ: &str, msg: &str) {
  51. if std::env::var("ZKAS_SILENT").is_ok() {
  52. return
  53. }
  54. let stderr = io::stderr();
  55. let mut handle = stderr.lock();
  56. match typ {
  57. "error" => {
  58. write!(handle, "\x1b[31;1m{} error:\x1b[0m {}", self.namespace, msg).unwrap()
  59. }
  60. "warning" => {
  61. write!(handle, "\x1b[33;1m{} warning:\x1b[0m {}", self.namespace, msg).unwrap()
  62. }
  63. _ => unreachable!(),
  64. };
  65. handle.flush().unwrap();
  66. }
  67. }