error.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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, 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!("{msg} (line {ln}, column {col})");
  33. let dbg_msg = format!("{}:{ln}:{col}: {}", self.file, 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!("{err_msg}\n{dbg_msg}\n{caret}\n")
  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::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" => write!(handle, "\x1b[31;1m{} error:\x1b[0m {msg}", self.namespace).unwrap(),
  58. "warning" => {
  59. write!(handle, "\x1b[33;1m{} warning:\x1b[0m {msg}", self.namespace).unwrap()
  60. }
  61. _ => unreachable!(),
  62. };
  63. handle.flush().unwrap();
  64. }
  65. }