esp_hal_procmacros/lib.rs
1//! ## Overview
2//!
3//! Procedural macros for use with the `esp-hal` family of HAL packages. In
4//! general, you should not need to depend on this package directly, as the
5//! relevant procmacros are re-exported by the various HAL packages.
6//!
7//! Provides macros for:
8//!
9//! - Placing statics and functions into RAM
10//! - Marking interrupt handlers
11//! - Blocking and Async `#[main]` macros
12//!
13//! These macros offer developers a convenient way to control memory placement
14//! and define interrupt handlers in their embedded applications, allowing for
15//! optimized memory usage and precise handling of hardware interrupts.
16//!
17//! Key Components:
18//! - [`handler`](macro@handler) - Attribute macro for marking interrupt handlers. Interrupt
19//! handlers are used to handle specific hardware interrupts generated by peripherals.
20//!
21//! - [`ram`](macro@ram) - Attribute macro for placing statics and functions into specific memory
22//! sections, such as SRAM or RTC RAM (slow or fast) with different initialization options. See
23//! its documentation for details.
24//!
25//! - [`esp_rtos::main`](macro@rtos_main) - Creates a new instance of `esp_rtos::embassy::Executor`
26//! and declares an application entry point spawning the corresponding function body as an async
27//! task.
28//!
29//! ## Examples
30//!
31//! #### `main` macro
32//!
33//! Requires the `embassy` feature to be enabled.
34//!
35//! ```rust,ignore
36//! #[main]
37//! async fn main(spawner: Spawner) {
38//! // Your application's entry point
39//! }
40//! ```
41//!
42//! ## Feature Flags
43#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
44#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/46717278")]
45
46use proc_macro::TokenStream;
47
48mod alert;
49mod blocking;
50mod builder;
51mod doc_replace;
52mod interrupt;
53#[cfg(any(
54 feature = "is-lp-core",
55 feature = "is-ulp-core",
56 feature = "has-lp-core",
57 feature = "has-ulp-core"
58))]
59mod lp_core;
60mod ram;
61mod rtos_main;
62
63/// Sets which segment of RAM to use for a function or static and how it should
64/// be initialized.
65///
66/// # Options
67///
68/// - `rtc_fast`: Use RTC fast RAM.
69/// - `rtc_slow`: Use RTC slow RAM. **Note**: not available on all targets.
70/// - `persistent`: Persist the contents of the `static` across resets. See [the section
71/// below](#persistent) for details.
72/// - `zeroed`: Initialize the memory of the `static` to zero. The initializer expression will be
73/// discarded. Types used must implement [`bytemuck::Zeroable`].
74/// - `reclaimed`: Memory reclaimed from the esp-idf bootloader.
75///
76/// Using both `rtc_fast` and `rtc_slow` or `persistent` and `zeroed` together
77/// is an error.
78///
79/// ## `persistent`
80///
81/// Initialize the memory to zero after the initial boot. Thereafter,
82/// initialization is skipped to allow communication across `software_reset()`,
83/// deep sleep, watchdog timeouts, etc.
84///
85/// Types used must implement [`bytemuck::AnyBitPattern`].
86///
87/// ### Warnings
88///
89/// - A system-level or lesser reset occurring before the ram has been zeroed *could* skip
90/// initialization and start the application with the static filled with random bytes.
91/// - There is no way to keep some kinds of resets from happening while updating a persistent
92/// static—not even a critical section.
93///
94/// If these are issues for your application, consider adding a checksum
95/// alongside the data.
96///
97/// # Examples
98///
99/// ```rust, ignore
100/// #[ram(unstable(rtc_fast))]
101/// static mut SOME_INITED_DATA: [u8; 2] = [0xaa, 0xbb];
102///
103/// #[ram(unstable(rtc_fast, persistent))]
104/// static mut SOME_PERSISTENT_DATA: [u8; 2] = [0; 2];
105///
106/// #[ram(unstable(rtc_fast, zeroed))]
107/// static mut SOME_ZEROED_DATA: [u8; 8] = [0; 8];
108/// ```
109///
110/// See the `ram` example in the qa-test folder of the esp-hal repository for a full usage example.
111///
112/// [`bytemuck::AnyBitPattern`]: https://docs.rs/bytemuck/1.9.0/bytemuck/trait.AnyBitPattern.html
113/// [`bytemuck::Zeroable`]: https://docs.rs/bytemuck/1.9.0/bytemuck/trait.Zeroable.html
114#[proc_macro_attribute]
115pub fn ram(args: TokenStream, input: TokenStream) -> TokenStream {
116 ram::ram(args.into(), input.into()).into()
117}
118
119/// Replaces placeholders in rustdoc doc comments.
120///
121/// The purpose of this macro is to enable us to extract boilerplate, while at
122/// the same time let rustfmt format code blocks. This macro rewrites the whole
123/// documentation of the annotated item.
124///
125/// Replacements can be placed in the documentation as `# {placeholder}`. Each
126/// replacement must be its own line, it's not possible to place a placeholder in the middle of a
127/// line. The `before_snippet` and `after_snippet` placeholders are expanded to the
128/// `esp_hal::before_snippet!()` and `esp_hal::after_snippet!()` macros, and are expected to be
129/// used in example code blocks.
130///
131/// You can also define custom replacements in the attribute. A replacement can be
132/// an unconditional literal (i.e. a string that is always substituted into the doc comment),
133/// or a conditional.
134///
135/// ## Examples
136///
137/// ```rust, ignore
138/// #[doc_replace(
139/// "literal_placeholder" => "literal value",
140/// "conditional_placeholder" => {
141/// cfg(condition1) => "value 1",
142/// cfg(condition2) => "value 2",
143/// _ => "neither value 1 nor value 2",
144/// }
145/// )]
146/// /// Here comes the documentation.
147/// ///
148/// /// The replacements are interpreted outside of code blocks, too:
149/// /// # {literal_placeholder}
150/// ///
151/// /// ```rust, no run
152/// /// // here is some code
153/// /// # {literal_placeholder}
154/// /// // here is some more code
155/// /// # {conditional_placeholder}
156/// /// ```
157/// fn my_function() {}
158/// ```
159#[proc_macro_attribute]
160pub fn doc_replace(args: TokenStream, input: TokenStream) -> TokenStream {
161 doc_replace::replace(args.into(), input.into()).into()
162}
163
164/// Mark a function as an interrupt handler.
165///
166/// Optionally a priority can be specified, e.g. `#[handler(priority =
167/// esp_hal::interrupt::Priority::Priority2)]`.
168///
169/// If no priority is given, `Priority::min()` is assumed
170#[proc_macro_attribute]
171pub fn handler(args: TokenStream, input: TokenStream) -> TokenStream {
172 interrupt::handler(args.into(), input.into()).into()
173}
174
175/// Load code to be run on the LP/ULP core.
176///
177/// ## Example
178/// ```rust, ignore
179/// let lp_core_code = load_lp_code!("path.elf");
180/// lp_core_code.run(&mut lp_core, lp_core::LpCoreWakeupSource::HpCpu, lp_pin);
181/// ````
182#[cfg(any(feature = "has-lp-core", feature = "has-ulp-core"))]
183#[proc_macro]
184pub fn load_lp_code(input: TokenStream) -> TokenStream {
185 lp_core::load_lp_code(input.into(), lp_core::RealFilesystem).into()
186}
187
188/// Marks the entry function of a LP core / ULP program.
189#[cfg(any(feature = "is-lp-core", feature = "is-ulp-core"))]
190#[proc_macro_attribute]
191pub fn entry(args: TokenStream, input: TokenStream) -> TokenStream {
192 lp_core::entry(args.into(), input.into()).into()
193}
194
195/// Creates a new instance of `esp_rtos::embassy::Executor` and declares an application entry point
196/// spawning the corresponding function body as an async task.
197///
198/// The following restrictions apply:
199///
200/// * The function must accept exactly 1 parameter, an `embassy_executor::Spawner` handle that it
201/// can use to spawn additional tasks.
202/// * The function must be declared `async`.
203/// * The function must not use generics.
204/// * Only a single `main` task may be declared.
205///
206/// ## Examples
207/// Spawning a task:
208///
209/// ```rust,ignore
210/// #[esp_rtos::main]
211/// async fn main(_s: embassy_executor::Spawner) {
212/// // Function body
213/// }
214/// ```
215#[proc_macro_attribute]
216pub fn rtos_main(args: TokenStream, item: TokenStream) -> TokenStream {
217 rtos_main::main(args.into(), item.into()).into()
218}
219
220/// Attribute to declare the entry point of the program
221///
222/// The specified function will be called by the reset handler *after* RAM has
223/// been initialized. If present, the FPU will also be enabled before the
224/// function is called.
225///
226/// The type of the specified function must be `[unsafe] fn() -> !` (never
227/// ending function)
228///
229/// # Properties
230///
231/// The entry point will be called by the reset handler. The program can't
232/// reference to the entry point, much less invoke it.
233///
234/// # Examples
235///
236/// - Simple entry point
237///
238/// ```ignore
239/// #[main]
240/// fn main() -> ! {
241/// loop { /* .. */ }
242/// }
243/// ```
244#[proc_macro_attribute]
245pub fn blocking_main(args: TokenStream, input: TokenStream) -> TokenStream {
246 let f = syn::parse_macro_input!(input as syn::ItemFn);
247 blocking::main(args.into(), f).into()
248}
249
250/// Automatically implement the [Builder Lite] pattern for a struct.
251///
252/// This will create an `impl` which contains methods for each field of a
253/// struct, allowing users to easily set the values. The generated methods will
254/// be the field name prefixed with `with_`, and calls to these methods can be
255/// chained as needed.
256///
257/// ## Example
258///
259/// ```rust, ignore
260/// #[derive(Default)]
261/// enum MyEnum {
262/// #[default]
263/// A,
264/// B,
265/// }
266///
267/// #[derive(Default, BuilderLite)]
268/// #[non_exhaustive]
269/// struct MyStruct {
270/// enum_field: MyEnum,
271/// bool_field: bool,
272/// option_field: Option<i32>,
273/// }
274///
275/// MyStruct::default()
276/// .with_enum_field(MyEnum::B)
277/// .with_bool_field(true)
278/// .with_option_field(-5);
279/// ```
280///
281/// [Builder Lite]: https://matklad.github.io/2022/05/29/builder-lite.html
282#[proc_macro_derive(BuilderLite, attributes(builder_lite))]
283pub fn builder_lite_derive(item: TokenStream) -> TokenStream {
284 builder::builder_lite_derive(item.into()).into()
285}
286
287/// Print a build error and terminate the process.
288///
289/// It should be noted that the error will be printed BEFORE the main function
290/// is called, and as such this should NOT be thought analogous to `println!` or
291/// similar utilities.
292///
293/// ## Example
294///
295/// ```rust, ignore
296/// esp_hal_procmacros::error! {"
297/// ERROR: something really bad has happened!
298/// "}
299/// // Process exits with exit code 1
300/// ```
301#[proc_macro]
302pub fn error(input: TokenStream) -> TokenStream {
303 alert::do_alert(termcolor::Color::Red, input);
304 panic!("Build failed");
305}
306
307/// Print a build warning.
308///
309/// It should be noted that the warning will be printed BEFORE the main function
310/// is called, and as such this should NOT be thought analogous to `println!` or
311/// similar utilities.
312///
313/// ## Example
314///
315/// ```rust
316/// esp_hal_procmacros::warning! {"
317/// WARNING: something unpleasant has happened!
318/// "};
319/// ```
320#[proc_macro]
321pub fn warning(input: TokenStream) -> TokenStream {
322 alert::do_alert(termcolor::Color::Yellow, input)
323}
324
325macro_rules! unwrap_or_compile_error {
326 ($($x:tt)*) => {
327 match $($x)* {
328 Ok(x) => x,
329 Err(e) => {
330 return e.into_compile_error()
331 }
332 }
333 };
334}
335
336pub(crate) use unwrap_or_compile_error;