1 // SPDX-License-Identifier: Apache-2.0 OR MIT 2 3 use std::fmt::Display; 4 5 use proc_macro2::TokenStream; 6 use syn::{spanned::Spanned, Error}; 7 8 pub(crate) struct DiagCtxt(TokenStream); 9 pub(crate) struct ErrorGuaranteed(()); 10 11 impl DiagCtxt { 12 pub(crate) fn error(&mut self, span: impl Spanned, msg: impl Display) -> ErrorGuaranteed { 13 let error = Error::new(span.span(), msg); 14 self.0.extend(error.into_compile_error()); 15 ErrorGuaranteed(()) 16 } 17 18 pub(crate) fn with( 19 fun: impl FnOnce(&mut DiagCtxt) -> Result<TokenStream, ErrorGuaranteed>, 20 ) -> TokenStream { 21 let mut dcx = Self(TokenStream::new()); 22 match fun(&mut dcx) { 23 Ok(mut stream) => { 24 stream.extend(dcx.0); 25 stream 26 } 27 Err(ErrorGuaranteed(())) => dcx.0, 28 } 29 } 30 } 31