Skip to main content

hazard3_executor/
lib.rs

1#![cfg_attr(not(any(feature = "platform-std", feature = "platform-wasm")), no_std)]
2#![allow(clippy::new_without_default)]
3#![allow(unsafe_op_in_unsafe_fn)]
4#![cfg_attr(
5    all(target_arch = "avr", feature = "executor-thread"),
6    feature(asm_experimental_arch)
7)]
8#![doc = include_str!("../README.md")]
9#![warn(missing_docs)]
10
11//! ## Tracing
12//!
13//! The `trace` feature enables hooks which report task and executor lifecycle events, for
14//! example to measure the run time of tasks.
15#![cfg_attr(
16    feature = "trace",
17    doc = "Implement [`raw::trace::Trace`] and register it with [`trace_impl!`]. See the [`raw::trace`] module for the lifecycles."
18)]
19
20//! ## Feature flags
21#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
22
23// This mod MUST go first, so that the others see its macros.
24pub(crate) mod fmt;
25
26// `#[macro_use]` so the platform modules can invoke the generated `pender_impl!` macro by its
27// bare name: macro-expanded `#[macro_export]` macros can't be invoked via `crate::` paths from
28// within the defining crate itself (rust-lang/rust#52234).
29#[macro_use]
30pub mod pender;
31
32pub use hazard3_executor_macros::task;
33
34macro_rules! check_at_most_one {
35    (@amo [$($feats:literal)*] [] [$($res:tt)*]) => {
36        #[cfg(any($($res)*))]
37        compile_error!(concat!("At most one of these features can be enabled at the same time:", $(" `", $feats, "`",)*));
38    };
39    (@amo $feats:tt [$curr:literal $($rest:literal)*] [$($res:tt)*]) => {
40        check_at_most_one!(@amo $feats [$($rest)*] [$($res)* $(all(feature=$curr, feature=$rest),)*]);
41    };
42    ($($f:literal),*$(,)?) => {
43        check_at_most_one!(@amo [$($f)*] [$($f)*] []);
44    };
45}
46check_at_most_one!(
47    "platform-avr",
48    "platform-cortex-m",
49    "platform-aarch32",
50    "platform-riscv32",
51    "platform-riscv64",
52    "platform-std",
53    "platform-wasm",
54    "platform-spin",
55);
56
57#[cfg(feature = "_platform")]
58#[cfg_attr(feature = "platform-avr", path = "platform/avr.rs")]
59#[cfg_attr(feature = "platform-cortex-m", path = "platform/cortex_m.rs")]
60#[cfg_attr(feature = "platform-aarch32", path = "platform/aarch32.rs")]
61#[cfg_attr(feature = "platform-riscv32", path = "platform/riscv.rs")]
62#[cfg_attr(feature = "platform-riscv64", path = "platform/riscv.rs")]
63#[cfg_attr(feature = "platform-std", path = "platform/std.rs")]
64#[cfg_attr(feature = "platform-wasm", path = "platform/wasm.rs")]
65#[cfg_attr(feature = "platform-spin", path = "platform/spin.rs")]
66mod platform;
67
68#[cfg(not(feature = "_platform"))]
69pub use hazard3_executor_macros::main_unspecified as main;
70#[cfg(feature = "_platform")]
71#[allow(unused_imports)] // don't warn if the module is empty.
72pub use platform::*;
73
74pub mod raw;
75
76/// Signal to the tracing system that the current thread/core is about to go idle.
77///
78/// Thread-mode executor implementations must call this right before putting the
79/// current thread/core to sleep (e.g. `wfe`/`wfi`). Do NOT call it from an
80/// interrupt executor, which returns to a preempted context after polling and
81/// is therefore not idle.
82///
83/// Note in multi-core chips, or when using threads under std or an RTOS, this
84/// doesn't mean the entire system is idle, it only means the current core/thread is.
85///
86/// This is a no-op unless the `trace` feature is enabled.
87#[inline]
88pub fn trace_idle() {
89    #[cfg(feature = "trace")]
90    raw::trace::TraceImpl::idle();
91}
92
93mod spawner;
94pub use spawner::*;
95
96mod metadata;
97pub use metadata::*;
98
99/// Implementation details for embassy macros.
100/// Do not use. Used for macros and HALs only. Not covered by semver guarantees.
101#[doc(hidden)]
102#[cfg(not(feature = "nightly"))]
103pub mod _export {
104    use core::cell::UnsafeCell;
105    use core::future::Future;
106    use core::mem::MaybeUninit;
107
108    use crate::raw::TaskPool;
109
110    trait TaskReturnValue {}
111    impl TaskReturnValue for () {}
112    impl TaskReturnValue for ! {}
113
114    #[diagnostic::on_unimplemented(
115        message = "task futures must resolve to `()` or `!`",
116        note = "use `async fn` or change the return type to `impl Future<Output = ()>`"
117    )]
118    #[allow(private_bounds)]
119    pub trait TaskFn<Args>: Copy {
120        type Fut: Future<Output: TaskReturnValue> + 'static;
121    }
122
123    macro_rules! task_fn_impl {
124        ($($Tn:ident),*) => {
125            impl<F, Fut, $($Tn,)*> TaskFn<($($Tn,)*)> for F
126            where
127                F: Copy + FnOnce($($Tn,)*) -> Fut,
128                Fut: Future<Output: TaskReturnValue> + 'static,
129            {
130                type Fut = Fut;
131            }
132        };
133    }
134
135    task_fn_impl!();
136    task_fn_impl!(T0);
137    task_fn_impl!(T0, T1);
138    task_fn_impl!(T0, T1, T2);
139    task_fn_impl!(T0, T1, T2, T3);
140    task_fn_impl!(T0, T1, T2, T3, T4);
141    task_fn_impl!(T0, T1, T2, T3, T4, T5);
142    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6);
143    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7);
144    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
145    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
146    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
147    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
148    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
149    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
150    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
151    task_fn_impl!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
152
153    #[allow(private_bounds)]
154    #[repr(C)]
155    pub struct TaskPoolHolder<const SIZE: usize, const ALIGN: usize>
156    where
157        Align<ALIGN>: Alignment,
158    {
159        data: UnsafeCell<[MaybeUninit<u8>; SIZE]>,
160        align: Align<ALIGN>,
161    }
162
163    unsafe impl<const SIZE: usize, const ALIGN: usize> Send for TaskPoolHolder<SIZE, ALIGN> where Align<ALIGN>: Alignment {}
164    unsafe impl<const SIZE: usize, const ALIGN: usize> Sync for TaskPoolHolder<SIZE, ALIGN> where Align<ALIGN>: Alignment {}
165
166    #[allow(private_bounds)]
167    impl<const SIZE: usize, const ALIGN: usize> TaskPoolHolder<SIZE, ALIGN>
168    where
169        Align<ALIGN>: Alignment,
170    {
171        pub const fn get(&self) -> *const u8 {
172            self.data.get().cast()
173        }
174    }
175
176    pub const fn task_pool_size<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
177    where
178        F: TaskFn<Args, Fut = Fut>,
179        Fut: Future + 'static,
180    {
181        size_of::<TaskPool<Fut, POOL_SIZE>>()
182    }
183
184    pub const fn task_pool_align<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
185    where
186        F: TaskFn<Args, Fut = Fut>,
187        Fut: Future + 'static,
188    {
189        align_of::<TaskPool<Fut, POOL_SIZE>>()
190    }
191
192    pub const fn task_pool_new<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> TaskPool<Fut, POOL_SIZE>
193    where
194        F: TaskFn<Args, Fut = Fut>,
195        Fut: Future + 'static,
196    {
197        TaskPool::new()
198    }
199
200    #[allow(private_bounds)]
201    #[repr(transparent)]
202    pub struct Align<const N: usize>([<Self as Alignment>::Archetype; 0])
203    where
204        Self: Alignment;
205
206    trait Alignment {
207        /// A zero-sized type of particular alignment.
208        type Archetype: Copy + Eq + PartialEq + Send + Sync + Unpin;
209    }
210
211    macro_rules! aligns {
212        ($($AlignX:ident: $n:literal,)*) => {
213            $(
214                #[derive(Copy, Clone, Eq, PartialEq)]
215                #[repr(align($n))]
216                struct $AlignX {}
217                impl Alignment for Align<$n> {
218                    type Archetype = $AlignX;
219                }
220            )*
221        };
222    }
223
224    aligns!(
225        Align1:         1,
226        Align2:         2,
227        Align4:         4,
228        Align8:         8,
229        Align16:        16,
230        Align32:        32,
231        Align64:        64,
232        Align128:       128,
233        Align256:       256,
234        Align512:       512,
235        Align1024:      1024,
236        Align2048:      2048,
237        Align4096:      4096,
238        Align8192:      8192,
239        Align16384:     16384,
240    );
241    #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
242    aligns!(
243        Align32768:     32768,
244        Align65536:     65536,
245        Align131072:    131072,
246        Align262144:    262144,
247        Align524288:    524288,
248        Align1048576:   1048576,
249        Align2097152:   2097152,
250        Align4194304:   4194304,
251        Align8388608:   8388608,
252        Align16777216:  16777216,
253        Align33554432:  33554432,
254        Align67108864:  67108864,
255        Align134217728: 134217728,
256        Align268435456: 268435456,
257        Align536870912: 536870912,
258    );
259}
260
261/// Implementation details for embassy macros.
262/// Do not use. Used for macros and HALs only. Not covered by semver guarantees.
263#[doc(hidden)]
264#[cfg(feature = "nightly")]
265pub mod _export {
266    #[diagnostic::on_unimplemented(
267        message = "task futures must resolve to `()` or `!`",
268        note = "use `async fn` or change the return type to `impl Future<Output = ()>`"
269    )]
270    pub trait TaskReturnValue {}
271    impl TaskReturnValue for () {}
272    impl TaskReturnValue for ! {}
273}