Skip to main content

euv_macros/
lib.rs

1//! euv-macros
2//!
3//! Zero-overhead native procedural macros for the cross-platform euv UI framework,
4//! compiling declarative `view!`, `style!`, `var!`, `watch!`, `computed!`,
5//! `state!`, `#[store]`, `#[component]`, `#[event]`, `emit!`, `on!`, and `#[euv]`
6//! directly into arena scene graph operations with span-preserving IDE completion
7//! and actionable compile-time diagnostics.
8
9mod component;
10mod diagnostic;
11mod entry;
12mod event;
13mod props;
14mod reactive;
15mod state;
16mod style;
17mod view;
18
19pub(crate) use {
20    component::*, diagnostic::*, entry::*, event::*, props::*, reactive::*, state::*, style::*,
21    view::*,
22};
23
24use std::{collections::HashSet, mem::take};
25
26use {
27    proc_macro::TokenStream,
28    proc_macro2::Span,
29    quote::{quote, quote_spanned},
30    syn::{
31        Attribute, Data, DeriveInput, Error, Expr, ExprRange, Field, Fields, FnArg,
32        GenericArgument, Ident, ImplGenerics, ImplItem, ImplItemFn, ItemFn, ItemImpl, ItemStruct,
33        LitBool, LitInt, LitStr, Meta, Pat, Path, PathArguments, PathSegment, RangeLimits, Result,
34        ReturnType, Stmt, Token, Type, TypeGenerics, Visibility, WhereClause, braced,
35        parenthesized,
36        parse::{Parse, ParseBuffer, ParseStream},
37        parse_macro_input,
38        punctuated::Punctuated,
39        spanned::Spanned,
40        token::{Brace, Paren},
41    },
42};
43
44/// Declarative zero-VDOM, zero-context UI construction macro managing `Context` automatically.
45///
46/// Component parameters must be passed as self-documenting named attributes inside `Component { prop: value }` blocks; positional `Component(...)` calls are rejected at compile time:
47///
48/// ```compile_fail
49/// use euv::*;
50///
51/// #[derive(Props)]
52/// struct DemoBtn {
53///     label: String,
54/// }
55///
56/// #[component]
57/// impl DemoBtn {
58///     fn render(&self) -> NodeId {
59///         view! { text { "ok" } }
60///     }
61/// }
62///
63/// fn invalid() -> NodeId {
64///     view! {
65///         DemoBtn("positional")
66///     }
67/// }
68/// ```
69///
70/// Inline style definitions (`style: { ... }`, `style: style! { ... }`, or `style: Style::default()...`) and loose style properties inside `view!` are rejected at compile time — define styles via keyless `style!` functions or pre-bound `Style` variables:
71///
72/// ```compile_fail
73/// use euv::*;
74///
75/// fn invalid_inline_style() -> NodeId {
76///     view! {
77///         column {
78///             style: {
79///                 Width(Length::Px(100.0))
80///             }
81///         }
82///     }
83/// }
84/// ```
85///
86/// ```compile_fail
87/// use euv::*;
88///
89/// fn invalid_loose_style() -> NodeId {
90///     view! {
91///         column {
92///             width: Length::Px(100.0)
93///         }
94///     }
95/// }
96/// ```
97///
98/// ```compile_fail
99/// use euv::*;
100///
101/// fn invalid_loose_css_alias() -> NodeId {
102///     view! {
103///         row {
104///             border_radius: 8.0
105///         }
106///     }
107/// }
108/// ```
109///
110/// ```compile_fail
111/// use euv::*;
112///
113/// #[derive(Props)]
114/// struct StyledCard {
115///     title: String,
116///     style: Option<Style>,
117/// }
118///
119/// #[component]
120/// impl StyledCard {
121///     fn render(&self) -> NodeId {
122///         let Self { title, style } = self;
123///         let card_style: Style = style! {
124///             *style
125///         };
126///         view! {
127///             column {
128///                 style: card_style
129///                 text { { title.as_str() } }
130///             }
131///         }
132///     }
133/// }
134///
135/// fn invalid_component_loose_style() -> NodeId {
136///     view! {
137///         StyledCard {
138///             title: "Demo"
139///             width: Length::Px(200.0)
140///         }
141///     }
142/// }
143/// ```
144///
145/// # Arguments
146///
147/// - `TokenStream` - Invocation tokens `view! { ... }`.
148///
149/// # Returns
150///
151/// - `TokenStream` - Expanded arena node construction and reactive binding tokens.
152#[proc_macro]
153pub fn view(input: TokenStream) -> TokenStream {
154    let parsed: ViewMacroInput = parse_macro_input!(input as ViewMacroInput);
155    expand_view(parsed).into()
156}
157
158/// Keyless compile-time style macro compiling newline-separated typed `StyleApply` structs and enums directly into zero-copy `Style` constructor functions or `Style` expressions.
159///
160/// Legacy `key: value` entries are rejected at compile time:
161///
162/// ```compile_fail
163/// use euv::*;
164///
165/// let _legacy: Style = style! {
166///     width: Length::Px(120.0)
167/// };
168/// ```
169///
170/// Every statement inside `style! { ... }` must occupy its own line without semicolons:
171///
172/// ```compile_fail
173/// use euv::*;
174///
175/// let _same_line: Style = style! {
176///     AlignItems::Center Overflow::Hidden
177/// };
178/// ```
179///
180/// ```compile_fail
181/// use euv::*;
182///
183/// let _semicolons: Style = style! {
184///     AlignItems::Center;
185///     Overflow::Hidden;
186/// };
187/// ```
188///
189/// # Arguments
190///
191/// - `TokenStream` - Keyless typed style rule block tokens.
192///
193/// # Returns
194///
195/// - `TokenStream` - Expanded typed `Style` functions or inline `Style` expression.
196#[proc_macro]
197pub fn style(input: TokenStream) -> TokenStream {
198    let parsed: StyleBlockInput = parse_macro_input!(input as StyleBlockInput);
199    expand_style(parsed).into()
200}
201
202/// Compile-time design token variable macro generating span-preserving typed `const` items.
203///
204/// ```
205/// use euv::*;
206///
207/// var! {
208///     const ACCENT_HEX: u32 = 0x2563EB;
209///     pub const SPACING_BASE: f32 = 8.0;
210/// }
211///
212/// assert_eq!(ACCENT_HEX, 0x2563EB);
213/// assert!((SPACING_BASE - 8.0).abs() < f32::EPSILON);
214/// ```
215///
216/// # Arguments
217///
218/// - `TokenStream` - Typed constant variable definition entries.
219///
220/// # Returns
221///
222/// - `TokenStream` - Expanded `#vis const #name: #ty = #value;` constant declarations.
223#[proc_macro]
224pub fn var(input: TokenStream) -> TokenStream {
225    let parsed: DesignTokenBlockInput = parse_macro_input!(input as DesignTokenBlockInput);
226    expand_var(parsed).into()
227}
228
229/// Ergonomic reactive side-effect macro watching one or more signals or a global state type.
230///
231/// # Arguments
232///
233/// - `TokenStream` - Signal list or `global Type` and effect closure tokens.
234///
235/// # Returns
236///
237/// - `TokenStream` - Expanded `Effect::new` or `GlobalState::watch` expression.
238#[proc_macro]
239pub fn watch(input: TokenStream) -> TokenStream {
240    let parsed: WatchInput = parse_macro_input!(input as WatchInput);
241    expand_watch(parsed).into()
242}
243
244/// Ergonomic memoized derived signal macro with equality short-circuiting.
245///
246/// # Arguments
247///
248/// - `TokenStream` - Signal list, return type, and computation closure tokens.
249///
250/// # Returns
251///
252/// - `TokenStream` - Expanded `Memo::new` expression.
253#[proc_macro]
254pub fn computed(input: TokenStream) -> TokenStream {
255    let parsed: ComputedInput = parse_macro_input!(input as ComputedInput);
256    expand_computed(parsed).into()
257}
258
259/// Unified cross-platform application entry-point attribute macro (`#[euv]` or `#[euv(title = "...", width = 1280, height = 800)]`).
260///
261/// Generates native desktop/TUI/CLI, WebAssembly/MiniApp/QuickApp, Android/WearOS, iOS/iPadOS,
262/// HarmonyOS, and wearable/spatial entry points from a single annotated root function.
263///
264/// # Arguments
265///
266/// - `TokenStream` - Optional window/runtime attribute options (`title`, `width`, `height`, `render`, `headless`, `fullscreen`).
267/// - `TokenStream` - Target root view, `App` builder, or `main` function item tokens.
268///
269/// # Returns
270///
271/// - `TokenStream` - Original entry function plus target-specific platform bootstrap entry points.
272#[proc_macro_attribute]
273pub fn euv(attr: TokenStream, item: TokenStream) -> TokenStream {
274    let args: EuvAttrArgs = parse_macro_input!(attr as EuvAttrArgs);
275    let func: ItemFn = parse_macro_input!(item as ItemFn);
276    expand_euv_attr(args, func).into()
277}
278
279/// Attribute macro marking a struct as a typed cross-component `CustomEvent` with ergonomic `::emit` and `::on` helpers.
280///
281/// # Arguments
282///
283/// - `TokenStream` - Unused attribute arguments.
284/// - `TokenStream` - Target struct item tokens.
285///
286/// # Returns
287///
288/// - `TokenStream` - Expanded struct plus `CustomEvent` implementation and helpers.
289#[proc_macro_attribute]
290pub fn event(_attr: TokenStream, item: TokenStream) -> TokenStream {
291    let parsed: ItemStruct = parse_macro_input!(item as ItemStruct);
292    expand_event_attr(parsed).into()
293}
294
295/// Dispatches a typed cross-component custom event through `EventBus`.
296///
297/// # Arguments
298///
299/// - `TokenStream` - Event value expression tokens.
300///
301/// # Returns
302///
303/// - `TokenStream` - Expanded `::euv::EventBus::emit(...)` call.
304#[proc_macro]
305pub fn emit(input: TokenStream) -> TokenStream {
306    let expr: Expr = parse_macro_input!(input as Expr);
307    expand_emit(expr).into()
308}
309
310/// Subscribes a scope-owned listener to a typed cross-component custom event (`on!(MyEvent => |event_payload| { ... })`).
311///
312/// ```
313/// use euv::*;
314///
315/// #[event]
316/// struct PingEvent {
317///     sequence: u32,
318/// }
319///
320/// reset_reactive_runtime();
321/// let received_sequence: Signal<u32> = Signal::new(0);
322/// let _subscription: Effect = on!(PingEvent => move |event_payload: &PingEvent| {
323///     let _: bool = received_sequence.set(event_payload.sequence);
324/// });
325/// emit!(PingEvent { sequence: 7 });
326/// assert_eq!(received_sequence.get_untracked(), 7);
327/// ```
328///
329/// # Arguments
330///
331/// - `TokenStream` - `EventType => handler` tokens.
332///
333/// # Returns
334///
335/// - `TokenStream` - Expanded `::euv::EventBus::on::<EventType, _>(handler)` returning `::euv::Effect`.
336#[proc_macro]
337pub fn on(input: TokenStream) -> TokenStream {
338    let parsed: OnEventInput = parse_macro_input!(input as OnEventInput);
339    expand_on(parsed).into()
340}
341
342/// Attribute macro turning a struct into a typed app-wide `GlobalState` store with `.provide()`, `::use_global()`, `::get_global()`, `::set_global()`, and `::watch_global()`.
343///
344/// ```
345/// use euv::*;
346///
347/// #[store]
348/// #[derive(Debug, Default, PartialEq)]
349/// struct CounterStore {
350///     count: u32,
351/// }
352///
353/// reset_reactive_runtime();
354/// let store_signal: Signal<CounterStore> = state!(global CounterStore = CounterStore { count: 2 });
355/// assert_eq!(CounterStore::get_global(), Some(CounterStore { count: 2 }));
356/// let _: bool = CounterStore::set_global(CounterStore { count: 5 });
357/// assert_eq!(store_signal.get_untracked().count, 5);
358/// ```
359///
360/// # Arguments
361///
362/// - `TokenStream` - Unused attribute arguments.
363/// - `TokenStream` - Target struct item tokens.
364///
365/// # Returns
366///
367/// - `TokenStream` - Expanded struct plus global state store methods.
368#[proc_macro_attribute]
369pub fn store(_attr: TokenStream, item: TokenStream) -> TokenStream {
370    let parsed: ItemStruct = parse_macro_input!(item as ItemStruct);
371    expand_store_attr(parsed).into()
372}
373
374/// Unified reactive state macro for scoped local state and typed app-wide global state.
375///
376/// - `state!(init_expr)` creates a scope-owned `::euv::LocalState::new(init_expr)`
377/// - `state!(global Type)` looks up `::euv::GlobalState::use_state::<Type>()`
378/// - `state!(global Type = init_expr)` lazily initializes or looks up `::euv::GlobalState::use_or_init::<Type, _>(...)`
379///
380/// # Arguments
381///
382/// - `TokenStream` - Local initializer expression or `global Type [= init_expr]` tokens.
383///
384/// # Returns
385///
386/// - `TokenStream` - Expanded `LocalState` or `GlobalState` expression.
387#[proc_macro]
388pub fn state(input: TokenStream) -> TokenStream {
389    let parsed: StateInput = parse_macro_input!(input as StateInput);
390    expand_state(parsed).into()
391}
392
393/// Attribute macro splitting an `impl MyComponent { fn render(&self) -> NodeId { ... } ... }` block into clean `impl Lifecycle` and `impl Component` blocks.
394///
395/// # Arguments
396///
397/// - `TokenStream` - Optional `retention = Freeze | Destroy | Alive` options.
398/// - `TokenStream` - Target `impl` block tokens.
399///
400/// # Returns
401///
402/// - `TokenStream` - Expanded `Lifecycle`, `Component`, and optional inherent helper `impl` blocks.
403#[proc_macro_attribute]
404pub fn component(attr: TokenStream, item: TokenStream) -> TokenStream {
405    let args: ComponentAttrArgs = parse_macro_input!(attr as ComponentAttrArgs);
406    let parsed: ItemImpl = parse_macro_input!(item as ItemImpl);
407    expand_component_attr(args, parsed).into()
408}
409
410/// Derive macro implementing `ComponentProps` and span-preserving fluent named-prop setters for `view! { MyComp { prop: value } }`.
411///
412/// # Arguments
413///
414/// - `TokenStream` - Target struct definition tokens.
415///
416/// # Returns
417///
418/// - `TokenStream` - Generated `ComponentProps` and fluent setter implementations.
419#[proc_macro_derive(Props, attributes(prop))]
420pub fn derive_props(input: TokenStream) -> TokenStream {
421    let parsed: DeriveInput = parse_macro_input!(input as DeriveInput);
422    expand_props_derive(parsed).into()
423}