Skip to content

Commit

Permalink
riot-rs-macros: make thread macro support both riot-rs and `riot-…
Browse files Browse the repository at this point in the history
…rs-threads` as deps (#303)
  • Loading branch information
kaspar030 authored May 24, 2024
2 parents 38a57fb + 413c971 commit aa5296c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
12 changes: 10 additions & 2 deletions src/riot-rs-macros/src/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub fn thread(args: TokenStream, item: TokenStream) -> TokenStream {

use quote::quote;

use crate::utils::find_crate;

let mut attrs = Attributes::default();
let thread_parser = syn::meta::parser(|meta| attrs.parse(&meta));
syn::parse_macro_input!(args with thread_parser);
Expand All @@ -62,13 +64,19 @@ pub fn thread(args: TokenStream, item: TokenStream) -> TokenStream {
priority,
} = Parameters::from(attrs);

let riot_rs_crate = utils::riot_rs_crate();
let thread_crate = {
match (find_crate("riot-rs"), find_crate("riot-rs-threads")) {
(Some(riot_rs), _) => quote! { #riot_rs::thread },
(None, Some(riot_rs_threads)) => quote! { #riot_rs_threads },
_ => panic!(r#"neither "riot-rs" nor "riot-rs-threads" found in dependencies!"#),
}
};

let expanded = quote! {
#no_mangle_attr
#thread_function

#riot_rs_crate::thread::autostart_thread!(#fn_name, stacksize = #stack_size, priority = #priority);
#thread_crate::autostart_thread!(#fn_name, stacksize = #stack_size, priority = #priority);
};

TokenStream::from(expanded)
Expand Down
26 changes: 17 additions & 9 deletions src/riot-rs-macros/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,24 @@ const RIOT_RS_CRATE_NAME: &str = "riot-rs";
/// this function is called.
/// - Panics if `riot-rs` is used as a dependency of itself.
pub fn riot_rs_crate() -> syn::Ident {
let riot_rs_crate = proc_macro_crate::crate_name(RIOT_RS_CRATE_NAME)
.unwrap_or_else(|_| panic!("{RIOT_RS_CRATE_NAME} should be present in `Cargo.toml`"));
find_crate(RIOT_RS_CRATE_NAME)
.unwrap_or_else(|| panic!("{RIOT_RS_CRATE_NAME} should be present in `Cargo.toml`"))
}

match riot_rs_crate {
proc_macro_crate::FoundCrate::Itself => {
panic!(
"{} cannot be used as a dependency of itself",
env!("CARGO_CRATE_NAME"),
);
/// Returns a [`struct@syn::Ident`] identifying the `name` dependency (or `None`).
///
/// # Panics
///
/// - Panics if `name` is used as a dependency of itself.
pub fn find_crate(name: &str) -> Option<syn::Ident> {
if let Ok(crate_) = proc_macro_crate::crate_name(name) {
match crate_ {
proc_macro_crate::FoundCrate::Itself => {
panic!("{name} cannot be used as a dependency of itself");
}
proc_macro_crate::FoundCrate::Name(crate_) => Some(format_ident!("{crate_}")),
}
proc_macro_crate::FoundCrate::Name(riot_rs_crate) => format_ident!("{riot_rs_crate}"),
} else {
None
}
}

0 comments on commit aa5296c

Please sign in to comment.