ctxt.rs 969 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. use quote::ToTokens;
  2. use std::{cell::RefCell, fmt::Display, thread};
  3. #[derive(Default)]
  4. pub struct ASTResult {
  5. errors: RefCell<Option<Vec<syn::Error>>>,
  6. }
  7. impl ASTResult {
  8. pub fn new() -> Self {
  9. ASTResult {
  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
  15. .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) {
  22. self.errors.borrow_mut().as_mut().unwrap().push(err);
  23. }
  24. pub fn check(self) -> Result<(), Vec<syn::Error>> {
  25. let errors = self.errors.borrow_mut().take().unwrap();
  26. match errors.len() {
  27. 0 => Ok(()),
  28. _ => Err(errors),
  29. }
  30. }
  31. }
  32. impl Drop for ASTResult {
  33. fn drop(&mut self) {
  34. if !thread::panicking() && self.errors.borrow().is_some() {
  35. panic!("forgot to check for errors");
  36. }
  37. }
  38. }