summaryrefslogtreecommitdiffstats
path: root/rust/pin-init/internal/src/diagnostics.rs
blob: 3bdb477c2f2b8c124153a1c21d4efcbfd98dac56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::fmt::Display;

use proc_macro2::TokenStream;
use syn::{spanned::Spanned, Error};

pub(crate) struct DiagCtxt(TokenStream);
pub(crate) struct ErrorGuaranteed(());

impl DiagCtxt {
    pub(crate) fn error(&mut self, span: impl Spanned, msg: impl Display) -> ErrorGuaranteed {
        let error = Error::new(span.span(), msg);
        self.0.extend(error.into_compile_error());
        ErrorGuaranteed(())
    }

    pub(crate) fn with(
        fun: impl FnOnce(&mut DiagCtxt) -> Result<TokenStream, ErrorGuaranteed>,
    ) -> TokenStream {
        let mut dcx = Self(TokenStream::new());
        match fun(&mut dcx) {
            Ok(mut stream) => {
                stream.extend(dcx.0);
                stream
            }
            Err(ErrorGuaranteed(())) => dcx.0,
        }
    }
}