ctxt.rs 1.0 KB

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