Commit 26bd9402 authored by Benno Lossin's avatar Benno Lossin
Browse files

rust: pin-init: internal: add utility API for syn error handling



The API is similar to diagnostics handling in rustc and uses a
`ErrorGuaranteed` value to signify that an error has been emitted. It
supports both fatal errors (which abort the macro expansion immediately
by returning `Err(ErrorGuaranteed)`) and non-fatal ones at generation
time. These errors are appended to the token stream after generation has
finished normally. This allows giving good errors while still expanding
most of the code as expected to avoid the user encountering additional
errors (for example missing definitions).

Suggested-by: default avatarGary Guo <gary@garyguo.net>
Tested-by: default avatarAndreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: default avatarGary Guo <gary@garyguo.net>
[ remove duplicate word in commit message - Benno ]
Signed-off-by: default avatarBenno Lossin <lossin@kernel.org>
parent 514e4ed2
Loading
Loading
Loading
Loading
+32 −0
Original line number Diff line number Diff line
// 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 {
    #[expect(dead_code)]
    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(())
    }

    #[expect(dead_code)]
    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,
        }
    }
}
+1 −0
Original line number Diff line number Diff line
@@ -12,6 +12,7 @@

use proc_macro::TokenStream;

mod diagnostics;
mod helpers;
mod pin_data;
mod pinned_drop;