bubba-macros 0.1.0

Procedural macros for the Bubba mobile framework (view! macro)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! # `view!` Procedural Macro
//!
//! Transforms declarative JSX-like UI syntax into Rust [`Element`] builder calls.
//!
//! ## Input (what you write)
//! ```rust,ignore
//! view! {
//!     <h1 class="title">"Welcome to Bubba"</h1>
//!     <button class="primary-btn" onclick=alert("Tapped!")>
//!         "Tap me"
//!     </button>
//!     <input class="text-input" oninput=log("Typing...") />
//! }
//! ```
//!
//! ## Output (what it expands to)
//! ```rust,ignore
//! {
//!     use bubba_core::ui::Element;
//!     use bubba_core::events::EventHandler;
//!
//!     let mut __root = Element::div();
//!     __root = __root.child(
//!         Element::h1()
//!             .class("title")
//!             .text("Welcome to Bubba")
//!     );
//!     __root = __root.child(
//!         Element::button()
//!             .class("primary-btn")
//!             .text("Tap me")
//!             .on(EventHandler::onclick(|_| { alert("Tapped!") }))
//!     );
//!     __root = __root.child(
//!         Element::input()
//!             .class("text-input")
//!             .on(EventHandler::oninput(|_| { log("Typing...") }))
//!     );
//!     bubba_core::ui::Screen::new(__root)
//! }
//! ```

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, quote_spanned};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    spanned::Spanned,
    Expr, Ident, LitStr, Result, Token,
};

// ── Public macro entry point ──────────────────────────────────────────────────

/// Declare a screen's UI declaratively using JSX-like syntax.
///
/// # Supported Tags
/// `<h1>`, `<h2>`, `<h3>`, `<p>`, `<button>`, `<img>`, `<input>`,
/// `<div>`, `<span>`, `<a>`
///
/// # Supported Attributes
/// - `class="..."` — CSS class name(s)
/// - `src="..."`, `alt="..."`, `placeholder="..."`, `href="..."` — generic attrs
/// - `onclick=expr` — tap/click handler
/// - `oninput=expr` — input change handler  
/// - `onkeypress=expr` — key press handler
/// - `onfocus=expr` — focus handler
/// - `onblur=expr` — blur handler
///
/// # Built-in Event Expressions
/// - `alert("message")` — show native alert
/// - `log("message")` — log to console
/// - `navigate(ScreenName)` — navigate to a screen
#[proc_macro]
pub fn view(input: TokenStream) -> TokenStream {
    let nodes = parse_macro_input!(input as NodeList);
    let expanded = codegen_screen(nodes);
    TokenStream::from(expanded)
}

// ── AST types ─────────────────────────────────────────────────────────────────

/// A list of top-level nodes inside `view! { ... }`.
struct NodeList {
    nodes: Vec<Node>,
}

impl Parse for NodeList {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut nodes = Vec::new();
        while !input.is_empty() {
            nodes.push(input.parse::<Node>()?);
        }
        Ok(NodeList { nodes })
    }
}

/// A single UI node — either a tag or a text literal.
enum Node {
    Element(ParsedElement),
    Text(LitStr),
}

impl Parse for Node {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(LitStr) {
            Ok(Node::Text(input.parse()?))
        } else {
            Ok(Node::Element(input.parse()?))
        }
    }
}

/// A parsed `<tag attr=val ...> children </tag>` or `<tag ... />`.
struct ParsedElement {
    span: Span,
    tag: Ident,
    attrs: Vec<ParsedAttr>,
    children: Vec<Node>,
}

impl Parse for ParsedElement {
    fn parse(input: ParseStream) -> Result<Self> {
        // `<`
        let lt: Token![<] = input.parse().map_err(|e| {
            syn::Error::new(e.span(), "Expected `<` to open a UI element.\n\nTip: every element starts with `<`, like `<button>` or `<h1>`.")
        })?;
        let span = lt.span();

        // tag name
        let tag: Ident = input.parse().map_err(|e| {
            syn::Error::new(e.span(), "Expected a tag name after `<`.\n\nSupported tags: h1, h2, h3, p, button, img, input, div, span, a")
        })?;

        // attributes
        let mut attrs = Vec::new();
        while !input.peek(Token![>]) && !input.peek(Token![/]) {
            attrs.push(input.parse::<ParsedAttr>()?);
        }

        // self-closing `/>` → return immediately; open `>` → parse children
        if input.peek(Token![/]) {
            input.parse::<Token![/]>()?;
            input.parse::<Token![>]>()?;
            return Ok(ParsedElement { span, tag, attrs, children: vec![] });
        }
        input.parse::<Token![>]>()?;

        // children
        let mut children = Vec::new();
        loop {
            // closing tag `</tag>`
            if input.peek(Token![<]) && input.peek2(Token![/]) {
                input.parse::<Token![<]>()?;
                input.parse::<Token![/]>()?;
                let closing_tag: Ident = input.parse().map_err(|e| {
                    syn::Error::new(e.span(), "Expected closing tag name.")
                })?;
                input.parse::<Token![>]>()?;

                if closing_tag != tag {
                    return Err(syn::Error::new(
                        closing_tag.span(),
                        format!(
                            "Mismatched tags: opened `<{}>` but closed with `</{}>`.\n\nTip: every opening tag needs a matching closing tag.",
                            tag, closing_tag
                        ),
                    ));
                }
                break;
            }
            if input.is_empty() {
                return Err(syn::Error::new(
                    span,
                    format!("Unclosed `<{}>` — missing `</{}>`.\n\nTip: add `</{}>` after the children.", tag, tag, tag),
                ));
            }
            children.push(input.parse::<Node>()?);
        }

        Ok(ParsedElement { span, tag, attrs, children })
    }
}

/// A single attribute: `class="..."`, `onclick=expr`, `src="..."`, etc.
struct ParsedAttr {
    name: Ident,
    value: AttrValue,
}

/// The value side of an attribute.
enum AttrValue {
    /// A string literal: `class="title"`
    Str(LitStr),
    /// A Rust expression: `onclick=alert("hi")` or `onclick=navigate(Profile)`
    Expr(Expr),
}

impl Parse for ParsedAttr {
    fn parse(input: ParseStream) -> Result<Self> {
        let name: Ident = input.parse().map_err(|e| {
            syn::Error::new(e.span(), "Expected an attribute name (e.g. `class`, `onclick`, `src`).")
        })?;
        input.parse::<Token![=]>().map_err(|e| {
            syn::Error::new(e.span(), format!("Attribute `{}` needs a value: `{}=\"...\"` or `{}=expr`.", name, name, name))
        })?;

        let value = if input.peek(LitStr) {
            AttrValue::Str(input.parse()?)
        } else {
            // Parse a call expression like `alert("msg")`, `navigate(Screen)`,
            // `log("x")`, or a closure `|e| { ... }`.
            //
            // We deliberately do NOT call `input.parse::<Expr>()` because that
            // would greedily consume past the closing `>` into the tag's children.
            // Instead we parse just the function name / path, then optionally
            // a parenthesised argument list or a closure body.
            let expr = parse_event_expr(input).map_err(|e| {
                syn::Error::new(
                    e.span(),
                    format!(
                        "Could not parse value for `{}`.\n\nExamples:\n  {}=\"some-class\"\n  {}=alert(\"message\")\n  {}=navigate(ScreenName)",
                        name, name, name, name
                    ),
                )
            })?;
            AttrValue::Expr(expr)
        };

        Ok(ParsedAttr { name, value })
    }
}

/// Parse an event-handler expression that must NOT consume past `>` or `/>`.
///
/// Accepted forms:
///   `ident(args...)`          — function call: alert("hi"), navigate(Home)
///   `|pat| expr`              — closure
///   `|pat| { block }`         — closure with block
///   `ident`                   — bare function reference
fn parse_event_expr(input: ParseStream) -> Result<Expr> {
    // Closure: |pat| ...
    if input.peek(Token![|]) {
        return input.parse::<Expr>();
    }

    // Parse a path (possibly multi-segment: foo::bar)
    let path: syn::ExprPath = input.parse()?;

    // If followed by `(`, parse the argument list
    if input.peek(syn::token::Paren) {
        let args_content;
        let paren = syn::parenthesized!(args_content in input);
        let args: syn::punctuated::Punctuated<Expr, Token![,]> =
            args_content.parse_terminated(Expr::parse, Token![,])?;

        Ok(Expr::Call(syn::ExprCall {
            attrs: vec![],
            func: Box::new(Expr::Path(path)),
            paren_token: paren,
            args,
        }))
    } else {
        // Bare path / function reference
        Ok(Expr::Path(path))
    }
}

// ── Code generation ───────────────────────────────────────────────────────────

fn codegen_screen(nodes: NodeList) -> TokenStream2 {
    let element_stmts: Vec<TokenStream2> = nodes.nodes.iter().map(codegen_node_as_child).collect();
    quote! {
        {
            let mut __bubba_root = ::bubba_core::ui::Element::div();
            #(#element_stmts)*
            ::bubba_core::ui::Screen::new(__bubba_root)
        }
    }
}

fn codegen_node_as_child(node: &Node) -> TokenStream2 {
    match node {
        Node::Text(lit) => {
            quote! {
                __bubba_root = __bubba_root.child(
                    ::bubba_core::ui::Element::span().text(#lit)
                );
            }
        }
        Node::Element(el) => {
            let el_expr = codegen_element(el);
            quote! {
                __bubba_root = __bubba_root.child(#el_expr);
            }
        }
    }
}

fn codegen_element(el: &ParsedElement) -> TokenStream2 {
    let tag = &el.tag;
    let tag_str = tag.to_string();
    let span = el.span;

    // Start with the constructor
    let mut builder = quote_spanned! { span =>
        ::bubba_core::ui::Element::new(#tag_str)
    };

    // Process attributes
    for attr in &el.attrs {
        let attr_name = attr.name.to_string();
        match &attr.value {
            AttrValue::Str(s) => {
                match attr_name.as_str() {
                    "class" => {
                        builder = quote! { #builder.class(#s) };
                    }
                    _ => {
                        builder = quote! { #builder.attr(#attr_name, #s) };
                    }
                }
            }
            AttrValue::Expr(expr) => {
                let event_name = match attr_name.as_str() {
                    "onclick"    => Some("click"),
                    "oninput"    => Some("input"),
                    "onkeypress" => Some("keypress"),
                    "onfocus"    => Some("focus"),
                    "onblur"     => Some("blur"),
                    "onchange"   => Some("change"),
                    other => {
                        // Unknown event — emit a compile_error pointing at the attribute
                        let msg = format!(
                            "Unknown event attribute `{}`. Did you mean `onclick`, `oninput`, or `onkeypress`?",
                            other
                        );
                        builder = quote! {
                            #builder
                            compile_error!(#msg)
                        };
                        None
                    }
                };

                if let Some(ev) = event_name {
                    let handler_expr = codegen_event_expr(expr, ev);
                    builder = quote! { #builder.on(#handler_expr) };
                }
            }
        }
    }

    // Process children
    for child in &el.children {
        match child {
            Node::Text(lit) => {
                builder = quote! { #builder.text(#lit) };
            }
            Node::Element(child_el) => {
                let child_expr = codegen_element(child_el);
                builder = quote! { #builder.child(#child_expr) };
            }
        }
    }

    builder
}

/// Transform a Bubba event expression into a Rust EventHandler.
///
/// `alert("msg")`          → `EventHandler::new("click", |_| { alert("msg") })`
/// `log("msg")`            → `EventHandler::new("click", |_| { log_msg("msg") })`
/// `navigate(ScreenName)`  → `EventHandler::new("click", |_| { navigate_to(stringify!(ScreenName), ScreenName) })`
/// `my_custom_fn()`        → `EventHandler::new("click", |_| { my_custom_fn() })`
fn codegen_event_expr(expr: &Expr, event: &str) -> TokenStream2 {
    // Pattern-match Bubba built-ins, fall back to user expr
    match expr {
        Expr::Call(call) => {
            if let Expr::Path(path) = call.func.as_ref() {
                let name = path.path.segments.last().map(|s| s.ident.to_string());
                match name.as_deref() {
                    Some("alert") => {
                        let args = &call.args;
                        return quote! {
                            ::bubba_core::events::EventHandler::new(#event, move |_| {
                                ::bubba_core::runtime::alert(#args);
                            })
                        };
                    }
                    Some("log") => {
                        let args = &call.args;
                        return quote! {
                            ::bubba_core::events::EventHandler::new(#event, move |_| {
                                ::bubba_core::runtime::log_msg(#args);
                            })
                        };
                    }
                    Some("navigate") => {
                        // navigate(Profile) → navigate_to("Profile", Profile)
                        if let Some(screen_arg) = call.args.first() {
                            return quote! {
                                ::bubba_core::events::EventHandler::new(#event, move |_| {
                                    ::bubba_core::navigation::navigate_to(
                                        stringify!(#screen_arg),
                                        #screen_arg,
                                    );
                                })
                            };
                        }
                    }
                    _ => {}
                }
            }
            // Generic call expression
            quote! {
                ::bubba_core::events::EventHandler::new(#event, move |_| { #expr; })
            }
        }
        // Closure passed directly: onclick=|_| { ... }
        Expr::Closure(closure) => {
            quote! {
                ::bubba_core::events::EventHandler::new(#event, #closure)
            }
        }
        // Any other expression
        _ => {
            quote! {
                ::bubba_core::events::EventHandler::new(#event, move |_| { #expr; })
            }
        }
    }
}