ctxt.rs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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) { self.errors.borrow_mut().as_mut().unwrap().push(err); }
  21. pub fn check(self) -> Result<(), Vec<syn::Error>> {
  22. let errors = self.errors.borrow_mut().take().unwrap();
  23. match errors.len() {
  24. 0 => Ok(()),
  25. _ => Err(errors),
  26. }
  27. }
  28. }
  29. impl Drop for Ctxt {
  30. fn drop(&mut self) {
  31. if !thread::panicking() && self.errors.borrow().is_some() {
  32. panic!("forgot to check for errors");
  33. }
  34. }
  35. }