ctxt.rs 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. use quote::ToTokens;
  2. use std::{cell::RefCell, fmt::Display, thread};
  3. #[derive(Default)]
  4. pub struct Ctxt {
  5. errors: RefCell<Option<Vec<syn::Error>>>,
  6. }
  7. impl Ctxt {
  8. pub fn new() -> Self {
  9. Ctxt {
  10. errors: RefCell::new(Some(Vec::new())),
  11. }
  12. }
  13. pub fn error_spanned_by<A: ToTokens, T: Display>(&self, obj: A, msg: T) {
  14. self.errors
  15. .borrow_mut()
  16. .as_mut()
  17. .unwrap()
  18. .push(syn::Error::new_spanned(obj.into_token_stream(), msg));
  19. }
  20. pub fn syn_error(&self, err: syn::Error) {
  21. self.errors.borrow_mut().as_mut().unwrap().push(err);
  22. }
  23. pub fn check(self) -> Result<(), Vec<syn::Error>> {
  24. let errors = self.errors.borrow_mut().take().unwrap();
  25. match errors.len() {
  26. 0 => Ok(()),
  27. _ => Err(errors),
  28. }
  29. }
  30. }
  31. impl Drop for Ctxt {
  32. fn drop(&mut self) {
  33. if !thread::panicking() && self.errors.borrow().is_some() {
  34. panic!("forgot to check for errors");
  35. }
  36. }
  37. }