macros: cleanup, make work in stable.
This commit is contained in:
66
embassy-macros/src/macros/interrupt.rs
Normal file
66
embassy-macros/src/macros/interrupt.rs
Normal file
@ -0,0 +1,66 @@
|
||||
use darling::FromMeta;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use std::iter;
|
||||
use syn::ReturnType;
|
||||
use syn::{Type, Visibility};
|
||||
|
||||
use crate::util::ctxt::Ctxt;
|
||||
|
||||
#[derive(Debug, FromMeta)]
|
||||
struct Args {}
|
||||
|
||||
pub fn run(args: syn::AttributeArgs, mut f: syn::ItemFn) -> Result<TokenStream, TokenStream> {
|
||||
let _args = Args::from_list(&args).map_err(|e| e.write_errors())?;
|
||||
|
||||
let ident = f.sig.ident.clone();
|
||||
let ident_s = ident.to_string();
|
||||
|
||||
// XXX should we blacklist other attributes?
|
||||
|
||||
let valid_signature = f.sig.constness.is_none()
|
||||
&& f.vis == Visibility::Inherited
|
||||
&& f.sig.abi.is_none()
|
||||
&& f.sig.inputs.is_empty()
|
||||
&& f.sig.generics.params.is_empty()
|
||||
&& f.sig.generics.where_clause.is_none()
|
||||
&& f.sig.variadic.is_none()
|
||||
&& match f.sig.output {
|
||||
ReturnType::Default => true,
|
||||
ReturnType::Type(_, ref ty) => match **ty {
|
||||
Type::Tuple(ref tuple) => tuple.elems.is_empty(),
|
||||
Type::Never(..) => true,
|
||||
_ => false,
|
||||
},
|
||||
};
|
||||
|
||||
let ctxt = Ctxt::new();
|
||||
|
||||
if !valid_signature {
|
||||
ctxt.error_spanned_by(
|
||||
&f.sig,
|
||||
"`#[interrupt]` handlers must have signature `[unsafe] fn() [-> !]`",
|
||||
);
|
||||
}
|
||||
|
||||
ctxt.check()?;
|
||||
|
||||
f.block.stmts = iter::once(
|
||||
syn::parse2(quote! {{
|
||||
// Check that this interrupt actually exists
|
||||
let __irq_exists_check: interrupt::#ident;
|
||||
}})
|
||||
.unwrap(),
|
||||
)
|
||||
.chain(f.block.stmts)
|
||||
.collect();
|
||||
|
||||
let result = quote!(
|
||||
#[doc(hidden)]
|
||||
#[export_name = #ident_s]
|
||||
#[allow(non_snake_case)]
|
||||
#f
|
||||
);
|
||||
|
||||
Ok(result)
|
||||
}
|
37
embassy-macros/src/macros/interrupt_declare.rs
Normal file
37
embassy-macros/src/macros/interrupt_declare.rs
Normal file
@ -0,0 +1,37 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
pub fn run(name: syn::Ident) -> Result<TokenStream, TokenStream> {
|
||||
let name = format_ident!("{}", name);
|
||||
let name_interrupt = format_ident!("{}", name);
|
||||
let name_handler = format!("__EMBASSY_{}_HANDLER", name);
|
||||
|
||||
let result = quote! {
|
||||
#[allow(non_camel_case_types)]
|
||||
pub struct #name_interrupt(());
|
||||
unsafe impl ::embassy::interrupt::Interrupt for #name_interrupt {
|
||||
type Priority = crate::interrupt::Priority;
|
||||
fn number(&self) -> u16 {
|
||||
use cortex_m::interrupt::InterruptNumber;
|
||||
let irq = InterruptEnum::#name;
|
||||
irq.number() as u16
|
||||
}
|
||||
unsafe fn steal() -> Self {
|
||||
Self(())
|
||||
}
|
||||
unsafe fn __handler(&self) -> &'static ::embassy::interrupt::Handler {
|
||||
#[export_name = #name_handler]
|
||||
static HANDLER: ::embassy::interrupt::Handler = ::embassy::interrupt::Handler::new();
|
||||
&HANDLER
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl ::embassy::util::Unborrow for #name_interrupt {
|
||||
type Target = #name_interrupt;
|
||||
unsafe fn unborrow(self) -> #name_interrupt {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(result)
|
||||
}
|
36
embassy-macros/src/macros/interrupt_take.rs
Normal file
36
embassy-macros/src/macros/interrupt_take.rs
Normal file
@ -0,0 +1,36 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
pub fn run(name: syn::Ident) -> Result<TokenStream, TokenStream> {
|
||||
let name = format!("{}", name);
|
||||
let name_interrupt = format_ident!("{}", name);
|
||||
let name_handler = format!("__EMBASSY_{}_HANDLER", name);
|
||||
|
||||
let result = quote! {
|
||||
{
|
||||
#[allow(non_snake_case)]
|
||||
#[export_name = #name]
|
||||
pub unsafe extern "C" fn trampoline() {
|
||||
extern "C" {
|
||||
#[link_name = #name_handler]
|
||||
static HANDLER: ::embassy::interrupt::Handler;
|
||||
}
|
||||
|
||||
let func = HANDLER.func.load(::embassy::export::atomic::Ordering::Relaxed);
|
||||
let ctx = HANDLER.ctx.load(::embassy::export::atomic::Ordering::Relaxed);
|
||||
let func: fn(*mut ()) = ::core::mem::transmute(func);
|
||||
func(ctx)
|
||||
}
|
||||
|
||||
static TAKEN: ::embassy::export::atomic::AtomicBool = ::embassy::export::atomic::AtomicBool::new(false);
|
||||
|
||||
if TAKEN.compare_exchange(false, true, ::embassy::export::atomic::Ordering::AcqRel, ::embassy::export::atomic::Ordering::Acquire).is_err() {
|
||||
core::panic!("IRQ Already taken");
|
||||
}
|
||||
|
||||
let irq: interrupt::#name_interrupt = unsafe { ::core::mem::transmute(()) };
|
||||
irq
|
||||
}
|
||||
};
|
||||
Ok(result)
|
||||
}
|
135
embassy-macros/src/macros/main.rs
Normal file
135
embassy-macros/src/macros/main.rs
Normal file
@ -0,0 +1,135 @@
|
||||
use darling::FromMeta;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
|
||||
use crate::util::ctxt::Ctxt;
|
||||
use crate::util::path::ModulePrefix;
|
||||
|
||||
#[cfg(feature = "stm32")]
|
||||
const HAL: Option<&str> = Some("embassy_stm32");
|
||||
#[cfg(feature = "nrf")]
|
||||
const HAL: Option<&str> = Some("embassy_nrf");
|
||||
#[cfg(feature = "rp")]
|
||||
const HAL: Option<&str> = Some("embassy_rp");
|
||||
#[cfg(not(any(feature = "stm32", feature = "nrf", feature = "rp")))]
|
||||
const HAL: Option<&str> = None;
|
||||
|
||||
#[derive(Debug, FromMeta)]
|
||||
struct Args {
|
||||
#[darling(default)]
|
||||
embassy_prefix: ModulePrefix,
|
||||
|
||||
#[allow(unused)]
|
||||
#[darling(default)]
|
||||
config: Option<syn::LitStr>,
|
||||
}
|
||||
|
||||
pub fn run(args: syn::AttributeArgs, f: syn::ItemFn) -> Result<TokenStream, TokenStream> {
|
||||
let args = Args::from_list(&args).map_err(|e| e.write_errors())?;
|
||||
|
||||
let fargs = f.sig.inputs.clone();
|
||||
|
||||
let ctxt = Ctxt::new();
|
||||
|
||||
if f.sig.asyncness.is_none() {
|
||||
ctxt.error_spanned_by(&f.sig, "task functions must be async");
|
||||
}
|
||||
if !f.sig.generics.params.is_empty() {
|
||||
ctxt.error_spanned_by(&f.sig, "task functions must not be generic");
|
||||
}
|
||||
|
||||
if HAL.is_some() && fargs.len() != 2 {
|
||||
ctxt.error_spanned_by(&f.sig, "main function must have 2 arguments");
|
||||
}
|
||||
if HAL.is_none() && fargs.len() != 1 {
|
||||
ctxt.error_spanned_by(&f.sig, "main function must have 2 arguments");
|
||||
}
|
||||
|
||||
ctxt.check()?;
|
||||
|
||||
let embassy_prefix = args.embassy_prefix;
|
||||
let embassy_prefix_lit = embassy_prefix.literal();
|
||||
let embassy_path = embassy_prefix.append("embassy").path();
|
||||
let f_body = f.block;
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
let main = quote! {
|
||||
#[wasm_bindgen::prelude::wasm_bindgen(start)]
|
||||
pub fn main() -> Result<(), wasm_bindgen::JsValue> {
|
||||
static EXECUTOR: #embassy_path::util::Forever<#embassy_path::executor::Executor> = #embassy_path::util::Forever::new();
|
||||
let executor = EXECUTOR.put(#embassy_path::executor::Executor::new());
|
||||
|
||||
executor.start(|spawner| {
|
||||
spawner.spawn(__embassy_main(spawner)).unwrap();
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(all(feature = "std", not(feature = "wasm")))]
|
||||
let main = quote! {
|
||||
fn main() -> ! {
|
||||
let mut executor = #embassy_path::executor::Executor::new();
|
||||
let executor = unsafe { __make_static(&mut executor) };
|
||||
|
||||
executor.run(|spawner| {
|
||||
spawner.must_spawn(__embassy_main(spawner));
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(all(not(feature = "std"), not(feature = "wasm")))]
|
||||
let main = {
|
||||
let config = args
|
||||
.config
|
||||
.map(|s| s.parse::<syn::Expr>().unwrap())
|
||||
.unwrap_or_else(|| {
|
||||
syn::Expr::Verbatim(quote! {
|
||||
Default::default()
|
||||
})
|
||||
});
|
||||
|
||||
let (hal_setup, peris_arg) = match HAL {
|
||||
Some(hal) => {
|
||||
let embassy_hal_path = embassy_prefix.append(hal).path();
|
||||
(
|
||||
quote!(
|
||||
let p = #embassy_hal_path::init(#config);
|
||||
),
|
||||
quote!(p),
|
||||
)
|
||||
}
|
||||
None => (quote!(), quote!()),
|
||||
};
|
||||
|
||||
quote! {
|
||||
#[cortex_m_rt::entry]
|
||||
fn main() -> ! {
|
||||
#hal_setup
|
||||
|
||||
let mut executor = #embassy_path::executor::Executor::new();
|
||||
let executor = unsafe { __make_static(&mut executor) };
|
||||
|
||||
executor.run(|spawner| {
|
||||
spawner.must_spawn(__embassy_main(spawner, #peris_arg));
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let result = quote! {
|
||||
#[#embassy_path::task(embassy_prefix = #embassy_prefix_lit)]
|
||||
async fn __embassy_main(#fargs) {
|
||||
#f_body
|
||||
}
|
||||
|
||||
unsafe fn __make_static<T>(t: &mut T) -> &'static mut T {
|
||||
::core::mem::transmute(t)
|
||||
}
|
||||
|
||||
#main
|
||||
};
|
||||
|
||||
Ok(result)
|
||||
}
|
5
embassy-macros/src/macros/mod.rs
Normal file
5
embassy-macros/src/macros/mod.rs
Normal file
@ -0,0 +1,5 @@
|
||||
pub mod interrupt;
|
||||
pub mod interrupt_declare;
|
||||
pub mod interrupt_take;
|
||||
pub mod main;
|
||||
pub mod task;
|
90
embassy-macros/src/macros/task.rs
Normal file
90
embassy-macros/src/macros/task.rs
Normal file
@ -0,0 +1,90 @@
|
||||
use darling::FromMeta;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
use crate::util::ctxt::Ctxt;
|
||||
use crate::util::path::ModulePrefix;
|
||||
|
||||
#[derive(Debug, FromMeta)]
|
||||
struct Args {
|
||||
#[darling(default)]
|
||||
pool_size: Option<usize>,
|
||||
#[darling(default)]
|
||||
send: bool,
|
||||
#[darling(default)]
|
||||
embassy_prefix: ModulePrefix,
|
||||
}
|
||||
|
||||
pub fn run(args: syn::AttributeArgs, mut f: syn::ItemFn) -> Result<TokenStream, TokenStream> {
|
||||
let args = Args::from_list(&args).map_err(|e| e.write_errors())?;
|
||||
|
||||
let embassy_prefix = args.embassy_prefix.append("embassy");
|
||||
let embassy_path = embassy_prefix.path();
|
||||
|
||||
let pool_size: usize = args.pool_size.unwrap_or(1);
|
||||
|
||||
let ctxt = Ctxt::new();
|
||||
|
||||
if f.sig.asyncness.is_none() {
|
||||
ctxt.error_spanned_by(&f.sig, "task functions must be async");
|
||||
}
|
||||
if !f.sig.generics.params.is_empty() {
|
||||
ctxt.error_spanned_by(&f.sig, "task functions must not be generic");
|
||||
}
|
||||
if pool_size < 1 {
|
||||
ctxt.error_spanned_by(&f.sig, "pool_size must be 1 or greater");
|
||||
}
|
||||
|
||||
let mut arg_names: syn::punctuated::Punctuated<syn::Ident, syn::Token![,]> =
|
||||
syn::punctuated::Punctuated::new();
|
||||
let mut fargs = f.sig.inputs.clone();
|
||||
|
||||
for arg in fargs.iter_mut() {
|
||||
match arg {
|
||||
syn::FnArg::Receiver(_) => {
|
||||
ctxt.error_spanned_by(arg, "task functions must not have receiver arguments");
|
||||
}
|
||||
syn::FnArg::Typed(t) => match t.pat.as_mut() {
|
||||
syn::Pat::Ident(i) => {
|
||||
arg_names.push(i.ident.clone());
|
||||
i.mutability = None;
|
||||
}
|
||||
_ => {
|
||||
ctxt.error_spanned_by(
|
||||
arg,
|
||||
"pattern matching in task arguments is not yet supporteds",
|
||||
);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
ctxt.check()?;
|
||||
|
||||
let name = f.sig.ident.clone();
|
||||
|
||||
let visibility = &f.vis;
|
||||
f.sig.ident = format_ident!("task");
|
||||
let impl_ty = if args.send {
|
||||
quote!(impl ::core::future::Future + Send + 'static)
|
||||
} else {
|
||||
quote!(impl ::core::future::Future + 'static)
|
||||
};
|
||||
|
||||
let attrs = &f.attrs;
|
||||
|
||||
let result = quote! {
|
||||
#(#attrs)*
|
||||
#visibility fn #name(#fargs) -> #embassy_path::executor::SpawnToken<#impl_ty> {
|
||||
use #embassy_path::executor::raw::TaskStorage;
|
||||
#f
|
||||
type F = #impl_ty;
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
const NEW_TASK: TaskStorage<F> = TaskStorage::new();
|
||||
static POOL: [TaskStorage<F>; #pool_size] = [NEW_TASK; #pool_size];
|
||||
unsafe { TaskStorage::spawn_pool(&POOL, move || task(#arg_names)) }
|
||||
}
|
||||
};
|
||||
|
||||
Ok(result)
|
||||
}
|
Reference in New Issue
Block a user