ctxt.rs
This file
Path
serde_derive/src/internals/ctxt.rs
67 lines · 1.9 KiB · Rust
Last changed by
Merge pull request #3039 from cuiweixie/typoDavid Tolnaybefore adoption7893347
History of this fileTake it
1use quote::ToTokens;2use std::cell::RefCell;3use std::fmt::Display;4use std::thread;56/// A type to collect errors together and format them.7///8/// Dropping this object will cause a panic. It must be consumed using `check`.9///10/// References can be shared since this type uses run-time exclusive mut checking.11#[derive(Default)]12pub struct Ctxt {13 // The contents will be set to `None` during checking. This is so that checking can be14 // enforced.15 errors: RefCell<Option<Vec<syn::Error>>>,16}1718impl Ctxt {19 /// Create a new context object.20 ///21 /// This object contains no errors, but will still trigger a panic if it is not `check`ed.22 pub fn new() -> Self {23 Ctxt {24 errors: RefCell::new(Some(Vec::new())),25 }26 }2728 /// Add an error to the context object with a tokenizable object.29 ///30 /// The object is used for spanning in error messages.31 pub fn error_spanned_by<A: ToTokens, T: Display>(&self, obj: A, msg: T) {32 self.errors33 .borrow_mut()34 .as_mut()35 .unwrap()36 // Curb monomorphization from generating too many identical methods.37 .push(syn::Error::new_spanned(obj.into_token_stream(), msg));38 }3940 /// Add one of Syn's parse errors.41 pub fn syn_error(&self, err: syn::Error) {42 self.errors.borrow_mut().as_mut().unwrap().push(err);43 }4445 /// Consume this object, producing a formatted error string if there are errors.46 pub fn check(self) -> syn::Result<()> {47 let mut errors = self.errors.borrow_mut().take().unwrap().into_iter();4849 let Some(mut combined) = errors.next() else {50 return Ok(());51 };5253 for rest in errors {54 combined.combine(rest);55 }5657 Err(combined)58 }59}6061impl Drop for Ctxt {62 fn drop(&mut self) {63 if !thread::panicking() && self.errors.borrow().is_some() {64 panic!("forgot to check for errors");65 }66 }67}