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/// All styling on primitive `view!` elements and custom `#[derive(Props)]` components must converge strictly inside `style: { ... }`, `style: style! { ... }`, or `style: expr`; loose top-level style properties and CSS aliases are rejected at compile time:
71///
72/// ```compile_fail
73/// use euv::*;
74///
75/// fn invalid_loose_style() -> NodeId {
76/// view! {
77/// column {
78/// width: Length::Px(100.0)
79/// }
80/// }
81/// }
82/// ```
83///
84/// ```compile_fail
85/// use euv::*;
86///
87/// fn invalid_loose_css_alias() -> NodeId {
88/// view! {
89/// row {
90/// border_radius: 8.0
91/// }
92/// }
93/// }
94/// ```
95///
96/// ```compile_fail
97/// use euv::*;
98///
99/// #[derive(Props)]
100/// struct StyledCard {
101/// title: String,
102/// style: Option<Style>,
103/// }
104///
105/// #[component]
106/// impl StyledCard {
107/// fn render(&self) -> NodeId {
108/// let Self { title, style } = self;
109/// let st: Style = Style::default().with_overrides(*style);
110/// view! {
111/// column {
112/// style: st
113/// text { { title.as_str() } }
114/// }
115/// }
116/// }
117/// }
118///
119/// fn invalid_component_loose_style() -> NodeId {
120/// view! {
121/// StyledCard {
122/// title: "Demo"
123/// width: Length::Px(200.0)
124/// }
125/// }
126/// }
127/// ```
128///
129/// # Arguments
130///
131/// - `TokenStream` - Invocation tokens `view! { ... }`.
132///
133/// # Returns
134///
135/// - `TokenStream` - Expanded arena node construction and reactive binding tokens.
136#[proc_macro]
137pub fn view(input: TokenStream) -> TokenStream {
138 let parsed: ViewMacroInput = parse_macro_input!(input as ViewMacroInput);
139 expand_view(parsed).into()
140}
141
142/// Compile-time style macro compiling declarative newline-separated rules directly into typed `Style` constructor functions or inline `Style` expressions.
143///
144/// Every statement inside `style! { ... }` must occupy its own line without semicolons. Placing two rules on one line is a compile-time error:
145///
146/// ```compile_fail
147/// use euv::*;
148///
149/// let _bad: Style = style! {
150/// AlignItems::Center Overflow::Hidden
151/// };
152/// ```
153///
154/// Trailing semicolons are also rejected in favor of clean newline separation:
155///
156/// ```compile_fail
157/// use euv::*;
158///
159/// let _bad: Style = style! {
160/// AlignItems::Center;
161/// Overflow::Hidden;
162/// };
163/// ```
164///
165/// # Arguments
166///
167/// - `TokenStream` - Style rule block tokens.
168///
169/// # Returns
170///
171/// - `TokenStream` - Expanded typed `Style` functions or inline `Style` expression.
172#[proc_macro]
173pub fn style(input: TokenStream) -> TokenStream {
174 let parsed: StyleBlockInput = parse_macro_input!(input as StyleBlockInput);
175 expand_style(parsed).into()
176}
177
178/// Compile-time design token variable macro generating span-preserving typed `const` items.
179///
180/// ```
181/// use euv::*;
182///
183/// var! {
184/// const ACCENT_HEX: u32 = 0x2563EB;
185/// pub const SPACING_BASE: f32 = 8.0;
186/// }
187///
188/// assert_eq!(ACCENT_HEX, 0x2563EB);
189/// assert!((SPACING_BASE - 8.0).abs() < f32::EPSILON);
190/// ```
191///
192/// # Arguments
193///
194/// - `TokenStream` - Typed constant variable definition entries.
195///
196/// # Returns
197///
198/// - `TokenStream` - Expanded `#vis const #name: #ty = #value;` constant declarations.
199#[proc_macro]
200pub fn var(input: TokenStream) -> TokenStream {
201 let parsed: DesignTokenBlockInput = parse_macro_input!(input as DesignTokenBlockInput);
202 expand_var(parsed).into()
203}
204
205/// Ergonomic reactive side-effect macro watching one or more signals or a global state type.
206///
207/// # Arguments
208///
209/// - `TokenStream` - Signal list or `global Type` and effect closure tokens.
210///
211/// # Returns
212///
213/// - `TokenStream` - Expanded `Effect::new` or `GlobalState::watch` expression.
214#[proc_macro]
215pub fn watch(input: TokenStream) -> TokenStream {
216 let parsed: WatchInput = parse_macro_input!(input as WatchInput);
217 expand_watch(parsed).into()
218}
219
220/// Ergonomic memoized derived signal macro with equality short-circuiting.
221///
222/// # Arguments
223///
224/// - `TokenStream` - Signal list, return type, and computation closure tokens.
225///
226/// # Returns
227///
228/// - `TokenStream` - Expanded `Memo::new` expression.
229#[proc_macro]
230pub fn computed(input: TokenStream) -> TokenStream {
231 let parsed: ComputedInput = parse_macro_input!(input as ComputedInput);
232 expand_computed(parsed).into()
233}
234
235/// Unified cross-platform application entry-point attribute macro (`#[euv]` or `#[euv(title = "...", width = 1280, height = 800)]`).
236///
237/// Generates native desktop/TUI/CLI, WebAssembly/MiniApp/QuickApp, Android/WearOS, iOS/iPadOS,
238/// HarmonyOS, and wearable/spatial entry points from a single annotated root function.
239///
240/// # Arguments
241///
242/// - `TokenStream` - Optional window/runtime attribute options (`title`, `width`, `height`, `render`, `headless`, `fullscreen`).
243/// - `TokenStream` - Target root view, `App` builder, or `main` function item tokens.
244///
245/// # Returns
246///
247/// - `TokenStream` - Original entry function plus target-specific platform bootstrap entry points.
248#[proc_macro_attribute]
249pub fn euv(attr: TokenStream, item: TokenStream) -> TokenStream {
250 let args: EuvAttrArgs = parse_macro_input!(attr as EuvAttrArgs);
251 let func: ItemFn = parse_macro_input!(item as ItemFn);
252 expand_euv_attr(args, func).into()
253}
254
255/// Attribute macro marking a struct as a typed cross-component `CustomEvent` with ergonomic `::emit` and `::on` helpers.
256///
257/// # Arguments
258///
259/// - `TokenStream` - Unused attribute arguments.
260/// - `TokenStream` - Target struct item tokens.
261///
262/// # Returns
263///
264/// - `TokenStream` - Expanded struct plus `CustomEvent` implementation and helpers.
265#[proc_macro_attribute]
266pub fn event(_attr: TokenStream, item: TokenStream) -> TokenStream {
267 let parsed: ItemStruct = parse_macro_input!(item as ItemStruct);
268 expand_event_attr(parsed).into()
269}
270
271/// Dispatches a typed cross-component custom event through `EventBus`.
272///
273/// # Arguments
274///
275/// - `TokenStream` - Event value expression tokens.
276///
277/// # Returns
278///
279/// - `TokenStream` - Expanded `::euv::EventBus::emit(...)` call.
280#[proc_macro]
281pub fn emit(input: TokenStream) -> TokenStream {
282 let expr: Expr = parse_macro_input!(input as Expr);
283 expand_emit(expr).into()
284}
285
286/// Subscribes a scope-owned listener to a typed cross-component custom event (`on!(MyEvent => |ev| { ... })`).
287///
288/// ```
289/// use euv::*;
290///
291/// #[event]
292/// struct PingEvent {
293/// seq: u32,
294/// }
295///
296/// reset_reactive_runtime();
297/// let received: Signal<u32> = Signal::new(0);
298/// let _sub: Effect = on!(PingEvent => move |ev: &PingEvent| {
299/// let _: bool = received.set(ev.seq);
300/// });
301/// emit!(PingEvent { seq: 7 });
302/// assert_eq!(received.get_untracked(), 7);
303/// ```
304///
305/// # Arguments
306///
307/// - `TokenStream` - `EventType => handler` tokens.
308///
309/// # Returns
310///
311/// - `TokenStream` - Expanded `::euv::EventBus::on::<EventType, _>(handler)` returning `::euv::Effect`.
312#[proc_macro]
313pub fn on(input: TokenStream) -> TokenStream {
314 let parsed: OnEventInput = parse_macro_input!(input as OnEventInput);
315 expand_on(parsed).into()
316}
317
318/// Attribute macro turning a struct into a typed app-wide `GlobalState` store with `.provide()`, `::use_global()`, `::get_global()`, `::set_global()`, `::update_global()`, and `::watch_global()`.
319///
320/// ```
321/// use euv::*;
322///
323/// #[store]
324/// #[derive(Debug, Default, PartialEq)]
325/// struct CounterStore {
326/// count: u32,
327/// }
328///
329/// reset_reactive_runtime();
330/// let sig: Signal<CounterStore> = state!(global CounterStore = CounterStore { count: 2 });
331/// assert_eq!(CounterStore::get_global(), Some(CounterStore { count: 2 }));
332/// let _: bool = CounterStore::update_global(|s: &mut CounterStore| s.count += 3);
333/// assert_eq!(sig.get_untracked().count, 5);
334/// ```
335///
336/// # Arguments
337///
338/// - `TokenStream` - Unused attribute arguments.
339/// - `TokenStream` - Target struct item tokens.
340///
341/// # Returns
342///
343/// - `TokenStream` - Expanded struct plus global state store methods.
344#[proc_macro_attribute]
345pub fn store(_attr: TokenStream, item: TokenStream) -> TokenStream {
346 let parsed: ItemStruct = parse_macro_input!(item as ItemStruct);
347 expand_store_attr(parsed).into()
348}
349
350/// Unified reactive state macro for scoped local state and typed app-wide global state.
351///
352/// - `state!(init_expr)` creates a scope-owned `::euv::LocalState::new(init_expr)`
353/// - `state!(global Type)` looks up `::euv::GlobalState::use_state::<Type>()`
354/// - `state!(global Type = init_expr)` lazily initializes or looks up `::euv::GlobalState::use_or_init::<Type, _>(...)`
355///
356/// # Arguments
357///
358/// - `TokenStream` - Local initializer expression or `global Type [= init_expr]` tokens.
359///
360/// # Returns
361///
362/// - `TokenStream` - Expanded `LocalState` or `GlobalState` expression.
363#[proc_macro]
364pub fn state(input: TokenStream) -> TokenStream {
365 let parsed: StateInput = parse_macro_input!(input as StateInput);
366 expand_state(parsed).into()
367}
368
369/// Attribute macro splitting an `impl MyComponent { fn render(&self) -> NodeId { ... } ... }` block into clean `impl Lifecycle` and `impl Component` blocks.
370///
371/// # Arguments
372///
373/// - `TokenStream` - Optional `retention = Freeze | Destroy | Alive` options.
374/// - `TokenStream` - Target `impl` block tokens.
375///
376/// # Returns
377///
378/// - `TokenStream` - Expanded `Lifecycle`, `Component`, and optional inherent helper `impl` blocks.
379#[proc_macro_attribute]
380pub fn component(attr: TokenStream, item: TokenStream) -> TokenStream {
381 let args: ComponentAttrArgs = parse_macro_input!(attr as ComponentAttrArgs);
382 let parsed: ItemImpl = parse_macro_input!(item as ItemImpl);
383 expand_component_attr(args, parsed).into()
384}
385
386/// Derive macro implementing `ComponentProps` and span-preserving fluent named-prop setters for `view! { MyComp { prop: value } }`.
387///
388/// # Arguments
389///
390/// - `TokenStream` - Target struct definition tokens.
391///
392/// # Returns
393///
394/// - `TokenStream` - Generated `ComponentProps` and fluent setter implementations.
395#[proc_macro_derive(Props, attributes(prop))]
396pub fn derive_props(input: TokenStream) -> TokenStream {
397 let parsed: DeriveInput = parse_macro_input!(input as DeriveInput);
398 expand_props_derive(parsed).into()
399}