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//! - [`main`](macro@main) - A unified entry point macro. For blocking functions it sets the
26//! bare-metal entry point; for async functions it creates an `esp_rtos::embassy::Executor` and
27//! spawns the function body as a task.
28//!
29//! ## Examples
30//!
31//! #### Blocking entry point
32//!
33//! ```rust,ignore
34//! #[main]
35//! fn main() -> ! {
36//! loop { /* .. */ }
37//! }
38//! ```
39//!
40//! #### Async entry point (requires the `embassy` feature in `esp-rtos`)
41//!
42//! ```rust,ignore
43//! #[main]
44//! async fn main(spawner: Spawner) {
45//! // Your application's async entry point
46//! }
47//! ```
48//!
49//! ## Feature Flags
50#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
51#![doc(html_logo_url = "https://docs.espressif.com/projects/rust/esp-rs-grey-bg.svg")]
52
53use proc_macro::TokenStream;
54
55mod alert;
56mod builder;
57mod doc_replace;
58mod interrupt;
59#[cfg(any(
60 feature = "is-lp-core",
61 feature = "is-ulp-core",
62 feature = "has-lp-core",
63 feature = "has-ulp-core"
64))]
65mod lp_core;
66mod ram;
67mod unified_main;
68
69/// Sets which segment of RAM to use for a function or static and how it should
70/// be initialized.
71///
72/// # Options
73///
74/// - `rtc_fast`: Use RTC fast RAM.
75/// - `rtc_slow`: Use RTC slow RAM. **Note**: not available on all targets.
76/// - `checked`: Place a function in the RAM section for code that runs while flash cannot be read,
77/// for example while the caches are suspended. The link fails if the function refers to code or
78/// constants in flash, or to RAM code without `checked`. GNU ld, the default linker for the
79/// ESP32, ESP32-S2, and ESP32-S3, finds only references to global symbols, for example
80/// `#[no_mangle]` functions.
81/// - `persistent`: Persist the contents of the `static` across resets. See [the section
82/// below](#persistent) for details.
83/// - `zeroed`: Initialize the memory of the `static` to zero. The initializer expression will be
84/// discarded. Types used must implement [`bytemuck::Zeroable`].
85/// - `reclaimed`: Memory reclaimed from the esp-idf bootloader.
86/// - `uncached`: Use internal SRAM through the L1-bypass address range. The CPU does not cache this
87/// memory. Only available on ESP32-P4.
88///
89/// Using both `rtc_fast` and `rtc_slow`, or `persistent` and `zeroed`, together is an error.
90/// `checked` on a `static`, or with `rtc_fast` or `rtc_slow`, is also an error.
91///
92/// ## `persistent`
93///
94/// Initialize the memory to zero after the initial boot. Thereafter,
95/// initialization is skipped to allow communication across `software_reset()`,
96/// deep sleep, watchdog timeouts, etc.
97///
98/// Types used must implement [`bytemuck::AnyBitPattern`].
99///
100/// ### Warnings
101///
102/// - A system-level or lesser reset occurring before the ram has been zeroed *could* skip
103/// initialization and start the application with the static filled with random bytes.
104/// - There is no way to keep some kinds of resets from happening while updating a persistent
105/// static—not even a critical section.
106///
107/// If these are issues for your application, consider adding a checksum
108/// alongside the data.
109///
110/// # Examples
111///
112/// ```rust, ignore
113/// #[ram(unstable(rtc_fast))]
114/// static mut SOME_INITED_DATA: [u8; 2] = [0xaa, 0xbb];
115///
116/// #[ram(unstable(rtc_fast, persistent))]
117/// static mut SOME_PERSISTENT_DATA: [u8; 2] = [0; 2];
118///
119/// #[ram(unstable(rtc_fast, zeroed))]
120/// static mut SOME_ZEROED_DATA: [u8; 8] = [0; 8];
121///
122/// #[ram(unstable(uncached))]
123/// static mut UNCACHE_DATA: [u8; 4] = [0x11, 0x22, 0x33, 0x44];
124///
125/// #[ram(unstable(uncached, zeroed))]
126/// static mut UNCACHE_BSS: [u8; 8] = [0; 8];
127/// ```
128///
129/// See the `ram` example in `examples/qa` of the esp-hal repository for a full usage example.
130///
131/// [`bytemuck::AnyBitPattern`]: https://docs.rs/bytemuck/1.9.0/bytemuck/trait.AnyBitPattern.html
132/// [`bytemuck::Zeroable`]: https://docs.rs/bytemuck/1.9.0/bytemuck/trait.Zeroable.html
133#[proc_macro_attribute]
134pub fn ram(args: TokenStream, input: TokenStream) -> TokenStream {
135 ram::ram(args.into(), input.into()).into()
136}
137
138/// Replaces placeholders in rustdoc doc comments.
139///
140/// The purpose of this macro is to enable us to extract boilerplate, while at
141/// the same time let rustfmt format code blocks. This macro rewrites the whole
142/// documentation of the annotated item.
143///
144/// Replacements can be placed in the documentation as `# {placeholder}`. Each
145/// replacement must be its own line. The `before_snippet` and `after_snippet` placeholders are
146/// expanded to the `esp_hal::before_snippet!()` and `esp_hal::after_snippet!()` macros, and are
147/// expected to be used in example code blocks.
148///
149/// In-line replacements can be placed in the middle of a line as `__placeholder__`. A line may
150/// contain any number of them. Should the replacements be conditional, the line is emitted for
151/// every combination of their values.
152///
153/// You can also define custom replacements in the attribute. A replacement can be
154/// an unconditional literal (i.e. a string that is always substituted into the doc comment),
155/// or a conditional.
156///
157/// A replacement does not have to be a literal: anything that expands to a string literal works,
158/// such as a call to a macro generated by esp-metadata. Lines containing such a replacement are
159/// assembled with `concat!`, which means the value only needs to be valid for the configuration the
160/// documentation is built for.
161///
162/// ## Examples
163///
164/// ```rust, ignore
165/// #[doc_replace(
166/// "literal_placeholder" => "literal value",
167/// "generated_placeholder" => gpio_for_signal!(USB_FS_DP),
168/// "conditional_placeholder" => {
169/// cfg(condition1) => "value 1",
170/// cfg(condition2) => "value 2",
171/// _ => "neither value 1 nor value 2",
172/// }
173/// )]
174/// /// Here comes the documentation.
175/// ///
176/// /// The replacements are interpreted outside of code blocks, too:
177/// /// # {literal_placeholder}
178/// ///
179/// /// ```rust, no run
180/// /// // here is some code
181/// /// # {literal_placeholder}
182/// /// // here is some more code
183/// /// # {conditional_placeholder}
184/// ///
185/// /// The macro even supports __conditional_placeholder__ replacements in-line.
186/// /// ```
187/// fn my_function() {}
188/// ```
189#[proc_macro_attribute]
190pub fn doc_replace(args: TokenStream, input: TokenStream) -> TokenStream {
191 doc_replace::replace(args.into(), input.into()).into()
192}
193
194/// Mark a function as an interrupt handler.
195///
196/// Optionally a priority can be specified, e.g. `#[handler(priority =
197/// esp_hal::interrupt::Priority::Priority2)]`.
198///
199/// If no priority is given, `Priority::min()` is assumed
200#[proc_macro_attribute]
201pub fn handler(args: TokenStream, input: TokenStream) -> TokenStream {
202 interrupt::handler(args.into(), input.into()).into()
203}
204
205/// Load code to be run on the LP/ULP core.
206///
207/// ## Example
208/// ```rust, ignore
209/// let lp_core_code = load_lp_code!("path.elf");
210/// lp_core_code.run(&mut lp_core, lp_core::LpCoreWakeupSource::HpCpu, lp_pin);
211/// ````
212#[cfg(any(feature = "has-lp-core", feature = "has-ulp-core"))]
213#[proc_macro]
214pub fn load_lp_code(input: TokenStream) -> TokenStream {
215 lp_core::load_lp_code(input.into(), lp_core::RealFilesystem).into()
216}
217
218/// Marks the entry function of a LP core / ULP program.
219#[cfg(any(feature = "is-lp-core", feature = "is-ulp-core"))]
220#[proc_macro_attribute]
221pub fn entry(args: TokenStream, input: TokenStream) -> TokenStream {
222 lp_core::entry(args.into(), input.into()).into()
223}
224
225/// Attribute to declare the entry point of the program.
226///
227/// Accepts both **blocking** and **async** main functions:
228///
229/// - A **blocking** function (`fn main() -> !`) is treated as a bare-metal entry point.
230/// - An **async** function (`async fn main(spawner: Spawner)`) is spawned inside an
231/// `esp_rtos::embassy::Executor`.
232///
233/// ## Examples
234///
235/// ### Blocking (bare-metal)
236///
237/// ```ignore
238/// #[main]
239/// fn main() -> ! {
240/// loop { /* .. */ }
241/// }
242/// ```
243///
244/// ### Async (embassy executor)
245///
246/// ```ignore
247/// #[main]
248/// async fn main(spawner: Spawner) {
249/// // spawn tasks, await futures, …
250/// }
251/// ```
252#[proc_macro_attribute]
253pub fn main(args: TokenStream, input: TokenStream) -> TokenStream {
254 unified_main::main(args.into(), input.into()).into()
255}
256
257/// Automatically implement the [Builder Lite] pattern for a struct.
258///
259/// This will create an `impl` which contains methods for each field of a
260/// struct, allowing users to easily set the values. The generated methods will
261/// be the field name prefixed with `with_`, and calls to these methods can be
262/// chained as needed.
263///
264/// ## Example
265///
266/// ```rust, ignore
267/// #[derive(Default)]
268/// enum MyEnum {
269/// #[default]
270/// A,
271/// B,
272/// }
273///
274/// #[derive(Default, BuilderLite)]
275/// #[non_exhaustive]
276/// struct MyStruct {
277/// enum_field: MyEnum,
278/// bool_field: bool,
279/// option_field: Option<i32>,
280/// }
281///
282/// MyStruct::default()
283/// .with_enum_field(MyEnum::B)
284/// .with_bool_field(true)
285/// .with_option_field(-5);
286/// ```
287///
288/// [Builder Lite]: https://matklad.github.io/2022/05/29/builder-lite.html
289#[proc_macro_derive(BuilderLite, attributes(builder_lite))]
290pub fn builder_lite_derive(item: TokenStream) -> TokenStream {
291 builder::builder_lite_derive(item.into()).into()
292}
293
294/// Print a build error and terminate the process.
295///
296/// It should be noted that the error will be printed BEFORE the main function
297/// is called, and as such this should NOT be thought analogous to `println!` or
298/// similar utilities.
299///
300/// ## Example
301///
302/// ```rust, ignore
303/// esp_hal_procmacros::error! {"
304/// ERROR: something really bad has happened!
305/// "}
306/// // Process exits with exit code 1
307/// ```
308#[proc_macro]
309pub fn error(input: TokenStream) -> TokenStream {
310 alert::do_alert(termcolor::Color::Red, input);
311 panic!("Build failed");
312}
313
314/// Print a build warning.
315///
316/// It should be noted that the warning will be printed BEFORE the main function
317/// is called, and as such this should NOT be thought analogous to `println!` or
318/// similar utilities.
319///
320/// ## Example
321///
322/// ```rust,no_run
323/// esp_hal_procmacros::warning! {"
324/// WARNING: something unpleasant has happened!
325/// "};
326/// ```
327#[proc_macro]
328pub fn warning(input: TokenStream) -> TokenStream {
329 alert::do_alert(termcolor::Color::Yellow, input)
330}
331
332macro_rules! unwrap_or_compile_error {
333 ($($x:tt)*) => {
334 match $($x)* {
335 Ok(x) => x,
336 Err(e) => {
337 return e.into_compile_error()
338 }
339 }
340 };
341}
342
343pub(crate) use unwrap_or_compile_error;