Skip to main content

swiftui_native_macros/
lib.rs

1//! `swiftui! { … }` — SwiftUI's declarative syntax, lowered to this crate's DSL.
2//!
3//! The DSL underneath is already chainable, so what a macro adds is the part
4//! Rust has no syntax for: a *body* of children written one after another, with
5//! `if` and `for` inside it. Written by hand that is a `vec![]` of views with
6//! `conditional(…)` and `for_each_items(…)` spliced in, and the shape of the
7//! tree stops being visible.
8//!
9//! ```ignore
10//! swiftui! {
11//!     VStack(spacing: 8) {
12//!         Text("Title").font(.large_title)
13//!         if show_detail {
14//!             Text(&detail)
15//!         }
16//!         ForEach(items) { item in
17//!             Text(item)
18//!         }
19//!     }
20//! }
21//! ```
22//!
23//! # What it does not do
24//!
25//! It is a *lowering*, not a Swift parser. Names go through camelCase to
26//! snake_case and then have to exist in the DSL — `Text` becomes
27//! [`text`](../swiftui_native/view/fn.text.html), `.foregroundStyle` becomes
28//! `.foreground_style`.
29//!
30//! That is deliberate rather than a shortcut: because the spans of the original
31//! tokens are kept, a name that does not exist gets rustc's own diagnostic
32//! underlining the SwiftUI spelling and naming the Rust function it looked for
33//! — and for a near miss, rustc's "there is a method `padding` with a similar
34//! name" does the rest. A macro that tried to validate names itself would have
35//! to carry a copy of the DSL's surface and would go stale.
36//!
37//! Containers are a table: the stacks know `spacing:` and `alignment:`,
38//! `Section` knows `header:` and `footer:`, and the rest take a body. A name
39//! not in the table falls through to `snake_case(body)`, which is right for a
40//! container taking one view and reports a missing function otherwise.
41//!
42//! Leading-dot syntax works: `.large_title` becomes
43//! `swiftui_native::dot::LargeTitle.into()`, and *type checking* picks the enum
44//! from the parameter's type — the same inference Swift does, reached a
45//! different way. A proc macro sees tokens and not types, so it cannot resolve
46//! this itself, but it does not have to. See
47//! [`swiftui_native::dot`](../swiftui_native/dot/index.html).
48
49use proc_macro::TokenStream;
50use proc_macro2::TokenStream as TokenStream2;
51use quote::quote;
52use syn::parse::{discouraged::Speculative, Parse, ParseStream};
53use syn::{braced, parenthesized, Expr, Ident, Result, Token};
54
55mod actions;
56
57/// Lower SwiftUI-shaped syntax to the `swiftui-native` DSL.
58#[proc_macro]
59pub fn swiftui(input: TokenStream) -> TokenStream {
60    let body = syn::parse_macro_input!(input as Node);
61    quote!(#body).into()
62}
63
64/// One element of a view body.
65enum Node {
66    /// `Name(args) { children }` or `Name(args)`.
67    Call(CallNode),
68    /// `expr.modifier(args)…` — anything that is not a call with a body.
69    Plain(Expr),
70    /// `if cond { … } else { … }`.
71    If(Box<IfNode>),
72    /// `ForEach(items) { binding in … }`.
73    ForEach(Box<ForEachNode>),
74    Match(Box<MatchNode>),
75    /// A `let` binding, which is a statement rather than a child.
76    Let(syn::Stmt),
77}
78
79struct CallNode {
80    name: Ident,
81    args: Vec<Arg>,
82    children: Option<Vec<Node>>,
83    /// `Button`'s brace, which is an action rather than children.
84    ///
85    /// Parsed as Rust statements, not as view nodes, so it can hold a `let` or
86    /// anything else a closure body can. Parsing it as children meant the
87    /// action was limited to things that looked like views, and a `let` in one
88    /// reported that it was not a view — which is true and unhelpful.
89    action: Option<Vec<syn::Stmt>>,
90    /// Trailing `.foo(…)` applied to the whole thing.
91    modifiers: TokenStream2,
92}
93
94/// `label: value` or a bare value.
95struct Arg {
96    label: Option<Ident>,
97    value: Expr,
98}
99
100struct IfNode {
101    /// `Some` for `if let PAT = expr`, `None` for a plain condition.
102    pattern: Option<syn::Pat>,
103    cond: Expr,
104    then: Vec<Node>,
105    otherwise: Option<Vec<Node>>,
106}
107
108struct ForEachNode {
109    items: Expr,
110    binding: Ident,
111    body: Vec<Node>,
112}
113
114/// `match subject { PAT if GUARD => { … } … }` — Swift's `switch` in a
115/// `@ViewBuilder`.
116struct MatchNode {
117    subject: Expr,
118    arms: Vec<MatchArm>,
119}
120
121struct MatchArm {
122    pat: syn::Pat,
123    guard: Option<Expr>,
124    body: Vec<Node>,
125}
126
127// ── Parsing ─────────────────────────────────────────────────────────────────
128
129impl Parse for Node {
130    fn parse(input: ParseStream) -> Result<Self> {
131        // A `let` in a body is a statement, not a child — SwiftUI allows one in
132        // a `@ViewBuilder` block for the same reason, to name something the
133        // children below use.
134        if input.peek(Token![let]) {
135            return Ok(Node::Let(input.parse()?));
136        }
137        if input.peek(Token![if]) {
138            return Ok(Node::If(Box::new(input.parse()?)));
139        }
140        if input.peek(Token![match]) {
141            return Ok(Node::Match(Box::new(input.parse()?)));
142        }
143        // A capitalised identifier followed by `(` or `{` is a view; anything
144        // else is an ordinary Rust expression and is left alone.
145        //
146        // Rust's own tuple constructors are capitalised too, and they turn up in
147        // modifier arguments for real — an `Option<CGFloat>` bound is written
148        // `Some(180.0)`. Lowering one as a view produced `view::some(180.0)`
149        // and an error naming a function nobody wrote. None of the three is a
150        // SwiftUI view, so excluding them costs nothing.
151        if input.peek(Ident) {
152            let ahead = input.fork();
153            let name: Ident = ahead.parse()?;
154            let text = name.to_string();
155            let capitalised = text.chars().next().is_some_and(char::is_uppercase);
156            let rust_constructor = matches!(text.as_str(), "Some" | "Ok" | "Err");
157            if capitalised
158                && !rust_constructor
159                && (ahead.peek(syn::token::Paren) || ahead.peek(syn::token::Brace))
160            {
161                if name == "ForEach" {
162                    return Ok(Node::ForEach(Box::new(input.parse()?)));
163                }
164                return Ok(Node::Call(input.parse()?));
165            }
166        }
167        Ok(Node::Plain(input.parse()?))
168    }
169}
170
171impl Parse for MatchNode {
172    fn parse(input: ParseStream) -> Result<Self> {
173        input.parse::<Token![match]>()?;
174        let subject = Expr::parse_without_eager_brace(input)?;
175        let inner;
176        braced!(inner in input);
177        let mut arms = Vec::new();
178        while !inner.is_empty() {
179            let pat = syn::Pat::parse_multi_with_leading_vert(&inner)?;
180            let guard = if inner.peek(Token![if]) {
181                inner.parse::<Token![if]>()?;
182                Some(inner.parse::<Expr>()?)
183            } else {
184                None
185            };
186            inner.parse::<Token![=>]>().map_err(|e| {
187                syn::Error::new(e.span(), "expected `=>` after a match pattern")
188            })?;
189            // An arm is either a braced body of children or a single view.
190            let body = if inner.peek(syn::token::Brace) {
191                parse_body(&inner)?
192            } else {
193                vec![inner.parse::<Node>()?]
194            };
195            arms.push(MatchArm { pat, guard, body });
196            if inner.is_empty() {
197                break;
198            }
199            if inner.peek(Token![,]) {
200                inner.parse::<Token![,]>()?;
201            }
202        }
203        if arms.is_empty() {
204            return Err(input.error("a `match` in a view body needs at least one arm"));
205        }
206        Ok(Self { subject, arms })
207    }
208}
209
210/// Does this modifier's trailing brace hold an action rather than content?
211///
212/// Swift reads that off the parameter's type. A macro has only the name, so
213/// the answer is read off the signatures instead and generated into
214/// [`actions`]: every chainable whose last parameter is a callback.
215///
216/// A name rule was tried first — `on_*`, plus `task` and `refreshable` — and
217/// it was wrong in both directions: it missed `accessibility_action`,
218/// `rename_action` and `transaction`, and would have claimed `on_drag_item`,
219/// whose trailing argument is a view.
220fn takes_an_action(method: &Ident) -> bool {
221    actions::ACTION_MODIFIERS.binary_search(&method.to_string().as_str()).is_ok()
222}
223
224/// The `x in` or `a, b in` at the head of a Swift closure, if there is one.
225fn closure_params(input: ParseStream) -> Result<Vec<Ident>> {
226    // Only a run of identifiers followed by `in` is a parameter list; anything
227    // else is the body starting with an expression.
228    let fork = input.fork();
229    let mut names = Vec::new();
230    loop {
231        let Ok(name) = fork.parse::<Ident>() else { return Ok(Vec::new()) };
232        names.push(name);
233        if fork.peek(Token![,]) {
234            fork.parse::<Token![,]>()?;
235            continue;
236        }
237        break;
238    }
239    if !fork.peek(Token![in]) {
240        return Ok(Vec::new());
241    }
242    fork.parse::<Token![in]>()?;
243    input.advance_to(&fork);
244    Ok(names)
245}
246
247/// Parse a braced body into its children.
248fn parse_body(input: ParseStream) -> Result<Vec<Node>> {
249    let inner;
250    braced!(inner in input);
251    let mut out = Vec::new();
252    while !inner.is_empty() {
253        // syn's own message for a failed child is whatever token it choked on,
254        // which for a typo in a body reads as `expected ,` and points nowhere
255        // useful. Saying what a body may contain is the difference between
256        // fixing it and guessing.
257        out.push(inner.parse().map_err(|e| {
258            let msg = e.to_string();
259            // Only syn's own message needs the context. Ours already say what
260            // was expected, and appending a list to those reads as two
261            // unrelated complaints about one typo.
262            if msg.contains(" — ") {
263                return e;
264            }
265            syn::Error::new(
266                e.span(),
267                format!(
268                    "{msg} — a view body holds views (`Text(\"x\")`, `VStack {{ … }}`), \
269                     `if` / `if let`, `ForEach(items) {{ x in … }}`, `let` bindings, \
270                     and ordinary Rust expressions that evaluate to a `View`",
271                ),
272            )
273        })?);
274        // Children are written one per line; a separating comma or semicolon is
275        // accepted but not required, so both a Swift body and a Rust `vec!`
276        // habit parse.
277        let _ = inner.parse::<Token![,]>();
278        let _ = inner.parse::<Token![;]>();
279    }
280    Ok(out)
281}
282
283impl Parse for CallNode {
284    fn parse(input: ParseStream) -> Result<Self> {
285        let name: Ident = input.parse()?;
286        let mut args = Vec::new();
287        if input.peek(syn::token::Paren) {
288            let inner;
289            parenthesized!(inner in input);
290            while !inner.is_empty() {
291                args.push(inner.parse()?);
292                if inner.is_empty() {
293                    break;
294                }
295                inner.parse::<Token![,]>()?;
296            }
297        }
298        let is_action_body = name == "Button";
299        let mut action = None;
300        let children = if input.peek(syn::token::Brace) {
301            if is_action_body {
302                let inner;
303                braced!(inner in input);
304                action = Some(inner.call(syn::Block::parse_within)?);
305                None
306            } else {
307                Some(parse_body(input)?)
308            }
309        } else {
310            None
311        };
312        // Swift's further trailing closures, each with a label:
313        // `Button { … } label: { … }`, `Section { … } header: { … }`. They
314        // become labelled arguments, so whatever reads `header:` out of the
315        // parentheses reads this too and the lowering needs no second spelling.
316        let mut args = args;
317        while input.peek(Ident) && input.peek2(Token![:]) && !input.peek2(Token![::]) {
318            let label: Ident = input.parse()?;
319            input.parse::<Token![:]>()?;
320            if !input.peek(syn::token::Brace) {
321                return Err(syn::Error::new(
322                    label.span(),
323                    format!(
324                        "`{label}:` after a body is one of Swift's further trailing \
325                         closures, so it needs a brace — `{label}: {{ … }}`"
326                    ),
327                ));
328            }
329            let body = parse_body(input)?;
330            let view = body_view(&body);
331            args.push(Arg { label: Some(label), value: syn::parse2(view)? });
332        }
333        // Trailing modifiers: `.font(…)` and so on, taken verbatim and replayed
334        // onto the built view.
335        let mut modifiers = TokenStream2::new();
336        while input.peek(Token![.]) {
337            let dot: Token![.] = input.parse()?;
338            if !input.peek(Ident) {
339                return Err(input.error(
340                    "expected a modifier name after `.` — `.padding(4.0)`, `.bold()`",
341                ));
342            }
343            let method: Ident = input.parse()?;
344            let mut call_args = TokenStream2::new();
345            if input.peek(syn::token::Paren) {
346                let inner;
347                parenthesized!(inner in input);
348                call_args = modifier_args(&inner)?;
349            }
350            // A trailing brace is the last argument, the way Swift writes
351            // `.overlay { … }` rather than `.overlay(…)`.
352            //
353            // Swift decides what that brace *is* from the parameter's type: it
354            // is content for `.overlay`, and an action for `.onTapGesture`.
355            // There is no type here to ask, so the name decides — see
356            // [`takes_an_action`].
357            if input.peek(syn::token::Brace) {
358                let last = if takes_an_action(&method) {
359                    let inner;
360                    braced!(inner in input);
361                    // Swift writes the parameters inside the brace:
362                    // `.onHover { hovering in … }`. No `in` means no
363                    // parameters, which is most of them.
364                    let params = closure_params(&inner)?;
365                    let stmts = inner.call(syn::Block::parse_within)?;
366                    quote!(move |#(#params),*| { #(#stmts)* })
367                } else {
368                    let body = parse_body(input)?;
369                    body_view(&body)
370                };
371                if call_args.is_empty() {
372                    call_args = quote!(#last);
373                } else {
374                    call_args.extend(quote!(, #last));
375                }
376            }
377            // Swift's `.padding()` takes no argument and means "the system's
378            // own inset". Rust has no overloading, so that binding is a
379            // separate name — and this is the one place a Swift spelling is
380            // mapped to a different one, rather than a rule.
381            let method = if method == "padding" && call_args.is_empty() {
382                Ident::new("padding_default", method.span())
383            } else {
384                method
385            };
386            modifiers.extend(quote!(#dot #method (#call_args)));
387        }
388        Ok(CallNode { name, args, children, action, modifiers })
389    }
390}
391
392impl Parse for Arg {
393    fn parse(input: ParseStream) -> Result<Self> {
394        // `label: value`, but not `Type::assoc` — a single `:` is a label.
395        let label = if input.peek(Ident) && input.peek2(Token![:]) && !input.peek2(Token![::]) {
396            let label: Ident = input.parse()?;
397            input.parse::<Token![:]>()?;
398            Some(label)
399        } else {
400            None
401        };
402        // A leading dot names a case, here as much as in a modifier's
403        // arguments: `VStack(alignment: .leading)` is the same `.leading` that
404        // `.frame(alignment: .leading)` takes, and only the modifier side used
405        // to resolve it.
406        if input.peek(Token![.]) {
407            let dot = leading_dot(input)?;
408            return Ok(Arg { label, value: syn::parse2(dot)? });
409        }
410        if input.peek(Token![$]) {
411            let b = binding_sigil(input)?;
412            return Ok(Arg { label, value: syn::parse2(b)? });
413        }
414        Ok(Arg { label, value: input.parse()? })
415    }
416}
417
418/// Swift's `$name`, which passes a property's *projection* rather than its
419/// value — `Toggle("x", isOn: $flag)`.
420///
421/// Here the projection of a `BoundState` is a borrow of it, so this lowers to
422/// `&name`. The sigil is worth accepting rather than asking for `&`: it is what
423/// SwiftUI's own documentation writes, and `$` is a token Rust's lexer passes
424/// through untouched, so the spelling costs nothing.
425fn binding_sigil(input: ParseStream) -> Result<TokenStream2> {
426    input.parse::<Token![$]>()?;
427    let Ok(name) = input.parse::<Ident>() else {
428        return Err(input.error("expected a name after `$` — `$flag`, the binding to pass"));
429    };
430    Ok(quote!(&#name))
431}
432
433/// `.some_case` as the marker the `dot` module turns back into a value.
434///
435/// Resolution is deferred to type checking, which is the same inference Swift
436/// does by a different route: the marker is a zero-size type with a `From` for
437/// every enum that has a case of that name, so the expected type picks one.
438fn leading_dot(input: ParseStream) -> Result<TokenStream2> {
439    input.parse::<Token![.]>()?;
440    let Ok(case) = input.parse::<Ident>() else {
441        return Err(input.error("expected a case name after `.` — `.leading`, `.large_title`"));
442    };
443    let marker = Ident::new(&upper_camel(&case.to_string()), case.span());
444    Ok(quote!(::core::convert::Into::into(::swiftui_native::dot::#marker)))
445}
446
447impl Parse for IfNode {
448    fn parse(input: ParseStream) -> Result<Self> {
449        input.parse::<Token![if]>()?;
450        let pattern = if input.peek(Token![let]) {
451            input.parse::<Token![let]>()?;
452            let pat = syn::Pat::parse_multi_with_leading_vert(input)?;
453            input.parse::<Token![=]>()?;
454            Some(pat)
455        } else {
456            None
457        };
458        let cond = Expr::parse_without_eager_brace(input)?;
459        let then = parse_body(input)?;
460        let otherwise = if input.peek(Token![else]) {
461            input.parse::<Token![else]>()?;
462            Some(parse_body(input)?)
463        } else {
464            None
465        };
466        Ok(IfNode { pattern, cond, then, otherwise })
467    }
468}
469
470impl Parse for ForEachNode {
471    fn parse(input: ParseStream) -> Result<Self> {
472        let kw: Ident = input.parse()?; // ForEach
473        const SHAPE: &str = "expected `ForEach(items) { item in … }`";
474        if !input.peek(syn::token::Paren) {
475            return Err(syn::Error::new(kw.span(), format!("{SHAPE} — no `(items)`")));
476        }
477        let inner;
478        parenthesized!(inner in input);
479        let items: Expr = inner.parse().map_err(|e| {
480            syn::Error::new(e.span(), format!("{SHAPE} — `{e}`"))
481        })?;
482        if !inner.is_empty() {
483            // `ForEach(items, id: \.self)` is the usual Swift spelling when the
484            // element is not `Identifiable`. There is nothing to say here:
485            // identity is the binding's own, so the label has no counterpart
486            // and silently ignoring it would be worse than saying so.
487            inner.parse::<Token![,]>()?;
488            let extra = inner.parse::<Ident>().ok();
489            let msg = if extra.as_ref().is_some_and(|i| i == "id") {
490                format!(
491                    "{SHAPE} — `id:` has no counterpart here: identity comes from the \
492                     binding, so `ForEach(items) {{ item in … }}` is the whole spelling"
493                )
494            } else {
495                format!("{SHAPE} — one collection or range, not several")
496            };
497            return Err(syn::Error::new(kw.span(), msg));
498        }
499        if !input.peek(syn::token::Brace) {
500            return Err(syn::Error::new(kw.span(), format!("{SHAPE} — no body")));
501        }
502        let body_outer;
503        braced!(body_outer in input);
504        let binding: Ident = body_outer.parse().map_err(|e| {
505            syn::Error::new(e.span(), format!("{SHAPE} — the body starts with the binding"))
506        })?;
507        // Swift writes `{ item in … }`; `in` is a Rust keyword, so it is matched
508        // as one rather than as an identifier.
509        body_outer.parse::<Token![in]>().map_err(|_| {
510            syn::Error::new(
511                binding.span(),
512                format!("{SHAPE} — `{binding}` must be followed by `in`"),
513            )
514        })?;
515        let mut body = Vec::new();
516        while !body_outer.is_empty() {
517            body.push(body_outer.parse()?);
518            let _ = body_outer.parse::<Token![,]>();
519            let _ = body_outer.parse::<Token![;]>();
520        }
521        Ok(ForEachNode { items, binding, body })
522    }
523}
524
525// ── Leading-dot arguments ───────────────────────────────────────────────────
526
527/// Parse a modifier's arguments.
528///
529/// Three things happen here that do not happen to an ordinary Rust call.
530///
531/// **Leading dots.** Swift infers the enum from the parameter. A proc macro
532/// sees tokens, not types, so it cannot — but it does not have to:
533/// `dot::LargeTitle.into()` defers the choice to type checking, which knows the
534/// parameter type and picks the one `From` impl that fits. One marker serves
535/// every enum with a variant of that name.
536///
537/// **Views.** An argument may itself be a view — `.overlay(Text("o"))` — so
538/// arguments are parsed as nodes and lowered like any other.
539///
540/// **Labels.** `.frame(width: 100, height: 50)` keeps SwiftUI's labels, which
541/// Rust has no syntax for. They are dropped and the values passed in order, so
542/// the label has to be in the parameter's position — which it is for the
543/// modifiers whose Rust signature was named after the Swift one. Where it is
544/// not, the type error names the parameter.
545fn modifier_args(input: ParseStream) -> Result<TokenStream2> {
546    let mut out = TokenStream2::new();
547    let mut first = true;
548    while !input.is_empty() {
549        if !first {
550            out.extend(quote!(,));
551        }
552        first = false;
553        // `label: value` — the label is a comment as far as Rust is concerned.
554        if input.peek(Ident) && input.peek2(Token![:]) && !input.peek2(Token![::]) {
555            input.parse::<Ident>()?;
556            input.parse::<Token![:]>()?;
557        }
558        if input.peek(Token![.]) {
559            out.extend(leading_dot(input)?);
560        } else if input.peek(Token![$]) {
561            out.extend(binding_sigil(input)?);
562        } else {
563            let node: Node = input.parse()?;
564            // A plain string literal in a modifier argument gets the same
565            // interpolation as one in a view's, so `.help("\(n) left")` works
566            // wherever a string does.
567            // A string literal in a modifier argument interpolates the same
568            // way one in a view's does, so `.help("{n} left")` works wherever a
569            // string does.
570            match &node {
571                Node::Plain(e) => out.extend(lower_args(std::slice::from_ref(e)).remove(0)),
572                _ => out.extend(quote!(#node)),
573            }
574        }
575        if input.is_empty() {
576            break;
577        }
578        input.parse::<Token![,]>()?;
579    }
580    Ok(out)
581}
582
583
584/// Does this literal need `format!`?
585///
586/// Any brace at all, escaped or not. The rule is one line — *a string literal
587/// in the macro is a format string* — and it has to hold both ways: a literal
588/// with only `{{` escapes still has to go through `format!`, or the doubling
589/// survives into the text and the escape means nothing.
590fn is_format_string(raw: &str) -> bool {
591    raw.contains('{') || raw.contains('}')
592}
593
594/// Rewrite `{expr}` holes that `format!` will not take into positional ones.
595///
596/// Rust's inline syntax only accepts a bare name, so `{s.count}` is "field
597/// access isn't supported" — and `s.count` is exactly what a body interpolates,
598/// since that is where the macro puts every property. Swift writes
599/// `\(s.count)`; this makes `{s.count}` mean the same thing by pulling the
600/// expression out and leaving `format!` a positional hole.
601///
602/// Only done when the caller passed no arguments of their own, so every hole
603/// belongs to this rewrite and the order cannot be disturbed. A bare name is
604/// left alone — `format!` captures it, which is what it is for — and so is a
605/// hole with an explicit index.
606fn hoist_holes(raw: &str) -> Option<(String, Vec<Expr>)> {
607    let mut fmt = String::with_capacity(raw.len());
608    let mut args = Vec::new();
609    let mut chars = raw.char_indices().peekable();
610    while let Some((i, c)) = chars.next() {
611        if c == '{' && chars.peek().map(|(_, c)| *c) == Some('{') {
612            chars.next();
613            fmt.push_str("{{");
614            continue;
615        }
616        if c == '}' && chars.peek().map(|(_, c)| *c) == Some('}') {
617            chars.next();
618            fmt.push_str("}}");
619            continue;
620        }
621        if c != '{' {
622            fmt.push(c);
623            continue;
624        }
625        // A hole: take up to the matching `}`.
626        let rest = &raw[i + 1..];
627        let end = rest.find('}')?;
628        let inside = &rest[..end];
629        for _ in 0..inside.chars().count() + 1 {
630            chars.next();
631        }
632        // Split the format spec off, taking care not to cut a `::` path.
633        let spec_at = {
634            let b = inside.as_bytes();
635            (0..b.len()).find(|&j| b[j] == b':' && b.get(j + 1) != Some(&b':') && (j == 0 || b[j - 1] != b':'))
636        };
637        let (expr_src, spec) = match spec_at {
638            Some(j) => (&inside[..j], &inside[j..]),
639            None => (inside, ""),
640        };
641        let trimmed = expr_src.trim();
642        let plain_name = !trimmed.is_empty()
643            && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_')
644            && !trimmed.chars().next().is_some_and(|c| c.is_ascii_digit());
645        if trimmed.is_empty() || plain_name {
646            // `format!` handles both: a positional hole and a captured name.
647            fmt.push('{');
648            fmt.push_str(inside);
649            fmt.push('}');
650            continue;
651        }
652        let expr: Expr = syn::parse_str(trimmed).ok()?;
653        args.push(expr);
654        fmt.push('{');
655        fmt.push_str(spec);
656        fmt.push('}');
657    }
658    (!args.is_empty()).then_some((fmt, args))
659}
660
661/// Lower a view's or modifier's arguments, interpolating the leading string.
662///
663/// Swift writes values into the string itself — `Text("\(count) of \(total)")`
664/// — and the Rust spelling of that had to break the string away from its
665/// values through `format!`. Rust's own inline syntax says the same thing:
666///
667/// ```ignore
668/// Text("{count} of {total}")          // instead of &format!("{} of {}", count, total)
669/// Text("{:.2} left", remaining)       // positional arguments work too
670/// ```
671///
672/// Swift's literal `\(…)` is not reachable — `\(` is an invalid escape and
673/// Rust's lexer rejects it before a macro sees the token — so this is as close
674/// as the spelling gets. Everything inside the braces is `format!`'s, including
675/// width and precision, and a name that is not in scope is `format!`'s error to
676/// report rather than one invented here.
677///
678/// A literal with no braces stays the `&'static str` it was, so nothing that
679/// worked before pays for a `format!`. One that has a brace goes through it,
680/// which makes a lone `{` a "invalid format string" error — the price of the
681/// rule being one line rather than two.
682fn lower_args(args: &[Expr]) -> Vec<TokenStream2> {
683    let formats = matches!(
684        args.first(),
685        Some(Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(s), .. })) if is_format_string(&s.value())
686    );
687    if formats {
688        let rest = &args[1..];
689        let lit = &args[0];
690        if rest.is_empty() {
691            if let Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(sl), .. }) = lit {
692                if let Some((fmt, hoisted)) = hoist_holes(&sl.value()) {
693                    let fmt = syn::LitStr::new(&fmt, sl.span());
694                    return vec![quote!(&::std::format!(#fmt #(, #hoisted)*))];
695                }
696            }
697        }
698        return vec![quote!(&::std::format!(#lit #(, #rest)*))];
699    }
700    // More than one argument with no interpolation is the caller's own
701    // spelling; pass it through and let the function complain if it is wrong.
702    args.iter().map(|e| quote!(#e)).collect()
703}
704
705/// `large_title` or `largeTitle` to `LargeTitle`.
706fn upper_camel(s: &str) -> String {
707    let mut out = String::with_capacity(s.len());
708    let mut up = true;
709    for c in s.chars() {
710        if c == '_' {
711            up = true;
712        } else if up {
713            out.extend(c.to_uppercase());
714            up = false;
715        } else {
716            out.push(c);
717        }
718    }
719    out
720}
721
722/// `VStack` to `vstack`, `foregroundStyle` to `foreground_style`.
723fn snake(s: &str) -> String {
724    let mut out = String::with_capacity(s.len() + 4);
725    for (i, c) in s.chars().enumerate() {
726        if c.is_uppercase() {
727            if i > 0 {
728                out.push('_');
729            }
730            out.extend(c.to_lowercase());
731        } else {
732            out.push(c);
733        }
734    }
735    out
736}
737
738// ── Lowering ────────────────────────────────────────────────────────────────
739
740impl quote::ToTokens for Node {
741    fn to_tokens(&self, tokens: &mut TokenStream2) {
742        tokens.extend(match self {
743            Node::Plain(e) => quote!(#e),
744            Node::Match(n) => {
745                // Swift's `switch` in a `@ViewBuilder` nests
746                // `_ConditionalContent`, and so does this: each arm becomes one
747                // `conditional`, wrapped around the rest. Lowering to a plain
748                // Rust `match` would build whichever arm won and hand SwiftUI a
749                // *replacement* rather than a branch that changed, which is the
750                // same identity loss `if` avoids by not being a Rust `if`.
751                //
752                // Each arm is matched against a borrow of the subject, so the
753                // patterns bind by reference — `Status::Ready(name)` gives a
754                // `&String`, which is what reading it wants anyway.
755                let subject = &n.subject;
756                let mut slots = Vec::new();
757                let mut names = Vec::new();
758                for (i, arm) in n.arms.iter().enumerate() {
759                    let name = Ident::new(&format!("__arm{i}"), proc_macro2::Span::call_site());
760                    let pat = &arm.pat;
761                    let body = body_view(&arm.body);
762                    let guard = match &arm.guard {
763                        Some(g) => quote!(if #g),
764                        None => quote!(),
765                    };
766                    slots.push(quote! {
767                        let #name = match __subject {
768                            #pat #guard => ::core::option::Option::Some(#body),
769                            #[allow(unreachable_patterns)]
770                            _ => ::core::option::Option::None,
771                        };
772                    });
773                    names.push(name);
774                }
775                // Fold from the last arm back, so the first written wins.
776                let mut chain = quote!(::swiftui_native::view::empty());
777                for name in names.iter().rev() {
778                    chain = quote!(::swiftui_native::view::conditional(
779                        #name.is_some(),
780                        #name.unwrap_or_else(::swiftui_native::view::empty),
781                        #chain,
782                    ));
783                }
784                quote!({
785                    let __subject = &#subject;
786                    #(#slots)*
787                    #chain
788                })
789            }
790            Node::If(n) => {
791                let cond = &n.cond;
792                let then = body_view(&n.then);
793                // A branch that is missing is an `EmptyView`, which is what
794                // SwiftUI's `_ConditionalContent` puts there. `conditional`
795                // takes both, so the tree stays one Swift type either way —
796                // which is the whole reason not to lower this to a plain Rust
797                // `if`, where each branch would be a different type and
798                // SwiftUI would lose the view's identity across the change.
799                let other = match &n.otherwise {
800                    Some(b) => body_view(b),
801                    None => quote!(::swiftui_native::view::empty()),
802                };
803                match &n.pattern {
804                    None => quote!(::swiftui_native::view::conditional(#cond, #then, #other)),
805                    // `if let` binds a name the false branch cannot see, so the
806                    // body is built inside the match and its presence is what
807                    // `conditional` is told about.
808                    Some(pat) => quote!({
809                        let __bound = if let #pat = #cond { Some(#then) } else { None };
810                        let __present = __bound.is_some();
811                        ::swiftui_native::view::conditional(
812                            __present,
813                            __bound.unwrap_or_else(::swiftui_native::view::empty),
814                            #other,
815                        )
816                    }),
817                }
818            }
819            Node::ForEach(n) => {
820                let items = &n.items;
821                let binding = &n.binding;
822                let body = body_view(&n.body);
823                // Swift spells both of these `ForEach`, and so does this: a
824                // range counts, anything else is a collection. `0..5` is the
825                // same half-open range Swift writes `0..<5`.
826                if matches!(items, Expr::Range(_)) {
827                    quote!(::swiftui_native::view::for_each(
828                        #items,
829                        move |#binding| #body,
830                    ))
831                } else {
832                    quote!(::swiftui_native::view::for_each_items(
833                        &#items,
834                        move |#binding| #body,
835                    ))
836                }
837            }
838            Node::Call(c) => c.lower(),
839            // Reached only if a `let` is used where a view is expected; in a
840            // body it is pulled out by `split_body` before this runs.
841            Node::Let(s) => syn::Error::new_spanned(
842                s,
843                "a `let` here is not a view — put it inside a container's body, \
844                 where it binds a name the children below can use",
845            )
846            .to_compile_error(),
847        });
848    }
849}
850
851/// Several children become one view: a tuple, which is what a `@ViewBuilder`
852/// block is. One child is itself.
853///
854/// Any `let` statements in the body come first, inside a block, so the children
855/// below can name what they bound.
856fn body_view(nodes: &[Node]) -> TokenStream2 {
857    let (stmts, kids) = split_body(nodes);
858    let core = if kids.len() == 1 {
859        let only = kids[0];
860        quote!(#only)
861    } else {
862        quote!(::swiftui_native::view::tuple_view(&[#(#kids),*]))
863    };
864    if stmts.is_empty() {
865        core
866    } else {
867        quote!({ #(#stmts)* #core })
868    }
869}
870
871/// Split a body into its `let` statements and its children, in order.
872fn split_body(nodes: &[Node]) -> (Vec<&syn::Stmt>, Vec<&Node>) {
873    let mut stmts = Vec::new();
874    let mut kids = Vec::new();
875    for n in nodes {
876        match n {
877            Node::Let(s) => stmts.push(s),
878            other => kids.push(other),
879        }
880    }
881    (stmts, kids)
882}
883
884impl CallNode {
885    fn lower(&self) -> TokenStream2 {
886        let modifiers = &self.modifiers;
887        let base = self.lower_base();
888        quote!(#base #modifiers)
889    }
890
891    fn lower_base(&self) -> TokenStream2 {
892        let name = self.name.to_string();
893        let positional: Vec<&Expr> = self.args.iter().filter(|a| a.label.is_none()).map(|a| &a.value).collect();
894        let labelled = |want: &str| {
895            self.args
896                .iter()
897                .find(|a| a.label.as_ref().is_some_and(|l| l == want))
898                .map(|a| &a.value)
899        };
900
901        // Containers: a body of children, and the argument set picks which
902        // constructor. These are spelled out because their Rust names are not a
903        // mechanical transform of the Swift ones — `VStack(spacing:)` is
904        // `vstack_spacing`, not `vstack`.
905        // `Button`'s brace is an action rather than children, so it is handled
906        // before the containers: there is nothing to gate on.
907        if name == "Button" {
908            let action = self.action.as_deref().unwrap_or_default();
909            return match labelled("label") {
910                Some(l) => quote!(::swiftui_native::view::button_labelled(
911                    #l,
912                    move || { #(#action)* },
913                )),
914                None => {
915                    let label = positional.first();
916                    quote!(::swiftui_native::view::button(#label, move || { #(#action)* }))
917                }
918            };
919        }
920
921        if let Some(children) = &self.children {
922            let (stmts, kid_nodes) = split_body(children);
923            let kids = quote!(&[#(#kid_nodes),*]);
924            let spacing = labelled("spacing");
925            let alignment = labelled("alignment");
926            let ctor = match (name.as_str(), spacing, alignment) {
927                ("VStack", None, None) => quote!(::swiftui_native::view::vstack(#kids)),
928                ("VStack", Some(s), None) => quote!(::swiftui_native::view::vstack_spacing(#kids, #s)),
929                ("VStack", None, Some(a)) => quote!(::swiftui_native::view::vstack_aligned(#kids, #a)),
930                ("VStack", Some(s), Some(a)) => {
931                    quote!(::swiftui_native::view::vstack_aligned_spacing(#kids, #a, Some(#s)))
932                }
933                ("HStack", None, _) => quote!(::swiftui_native::view::hstack(#kids)),
934                ("HStack", Some(s), _) => quote!(::swiftui_native::view::hstack_spacing(#kids, #s)),
935                ("ZStack", _, None) => quote!(::swiftui_native::view::zstack(#kids)),
936                ("ZStack", _, Some(a)) => quote!(::swiftui_native::view::zstack_aligned(#kids, #a)),
937                ("List", ..) => {
938                    let body = body_view(children);
939                    quote!(::swiftui_native::view::list(#body))
940                }
941                ("Form", ..) => {
942                    let body = body_view(children);
943                    quote!(::swiftui_native::view::form(#body))
944                }
945                ("Group", ..) => {
946                    let body = body_view(children);
947                    quote!(::swiftui_native::view::group(#body))
948                }
949                // `Section(header:footer:)` picks its constructor the way the
950                // stacks do, since the DSL names one per combination rather
951                // than taking optionals.
952                ("Section", ..) => {
953                    let body = body_view(children);
954                    match (labelled("header"), labelled("footer")) {
955                        (None, None) => quote!(::swiftui_native::view::section(#body)),
956                        (Some(h), None) => {
957                            quote!(::swiftui_native::view::section_titled(#h, #body))
958                        }
959                        (None, Some(f)) => {
960                            quote!(::swiftui_native::view::section_footer(#f, #body))
961                        }
962                        (Some(h), Some(f)) => {
963                            quote!(::swiftui_native::view::section_titled_footer(#h, #f, #body))
964                        }
965                    }
966                }
967                // Containers taking a slice of children, like the stacks.
968                ("LazyVStack", ..) => quote!(::swiftui_native::view::lazy_vstack(#kids)),
969                ("LazyHStack", ..) => quote!(::swiftui_native::view::lazy_hstack(#kids)),
970                ("GridRow", ..) => quote!(::swiftui_native::view::grid_row(#kids)),
971                ("Grid", ..) => quote!(::swiftui_native::view::grid(#kids)),
972                // Containers taking one view.
973                ("NavigationStack", ..) => {
974                    let body = body_view(children);
975                    quote!(::swiftui_native::view::navigation_stack(#body))
976                }
977                ("GroupBox", ..) => {
978                    let body = body_view(children);
979                    quote!(::swiftui_native::view::group_box(#body))
980                }
981                ("ControlGroup", ..) => {
982                    let body = body_view(children);
983                    quote!(::swiftui_native::view::control_group(#body))
984                }
985                ("TabView", ..) => {
986                    let body = body_view(children);
987                    quote!(::swiftui_native::view::tab_view(#body))
988                }
989                ("NavigationLink", ..) => {
990                    // `NavigationLink("go") { destination }` takes its label as
991                    // a string; `NavigationLink { destination } label: { … }`
992                    // takes a view, the same pair `Button` has.
993                    let body = body_view(children);
994                    match labelled("label") {
995                        Some(l) => {
996                            quote!(::swiftui_native::view::navigation_link_labelled(#l, #body))
997                        }
998                        None => {
999                            let label = positional.first();
1000                            quote!(::swiftui_native::view::navigation_link(#label, #body))
1001                        }
1002                    }
1003                }
1004                _ => {
1005                    // Anything else with a body: whatever was written in the
1006                    // parentheses, then the children as one view. Passing only
1007                    // the body meant `Menu("Actions") { … }` dropped its title
1008                    // and failed to compile against a two-argument function.
1009                    let f = Ident::new(&snake(&name), self.name.span());
1010                    let body = body_view(children);
1011                    quote!(::swiftui_native::view::#f(#(#positional,)* #body))
1012                }
1013            };
1014            return if stmts.is_empty() { ctor } else { quote!({ #(#stmts)* #ctor }) };
1015        }
1016
1017        // Controls whose Swift spelling names a binding. `Toggle(isOn:)` and
1018        // `TextField(text:)` always take one in Swift — there is no
1019        // by-value form — so the label is enough to pick the bound
1020        // constructor, and `$flag` has already become the borrow it wants.
1021        let bound = |label: &str, alt: &str| labelled(label).or_else(|| labelled(alt));
1022        if name == "Toggle" {
1023            if let Some(state) = bound("isOn", "is_on") {
1024                let title = positional.first();
1025                return quote!(::swiftui_native::view::toggle_bound(#title, #state));
1026            }
1027        }
1028        if name == "TextField" {
1029            if let Some(state) = bound("text", "value") {
1030                let placeholder = positional.first();
1031                return quote!(::swiftui_native::view::textfield_bound(#placeholder, #state));
1032            }
1033        }
1034
1035        // A leaf: `Text("x")` to `text("x")`.
1036        //
1037        // The name is the Swift one in snake_case, which is what the bindings
1038        // are called — except where they are not, and those are listed rather
1039        // than guessed at.
1040        let rust_name = match name.as_str() {
1041            "TextField" => "textfield".to_string(),
1042            _ => snake(&name),
1043        };
1044        let f = Ident::new(&rust_name, self.name.span());
1045        let args: Vec<Expr> = self.args.iter().map(|a| a.value.clone()).collect();
1046        let args = lower_args(&args);
1047        quote!(::swiftui_native::view::#f(#(#args),*))
1048    }
1049}
1050
1051// ═══════════════════════════════════════════════════════════════════════════
1052// `stateful!`
1053// ═══════════════════════════════════════════════════════════════════════════
1054
1055/// Declare a view with property wrappers, by name.
1056///
1057/// [`ComposedBuilder`] works by handing out a handle per property, which is
1058/// type-safe but leaves the caller threading handles into the body. This
1059/// declares the same thing and reads every property *before* the body runs, so
1060/// the body gets a plain struct with plain fields:
1061///
1062/// Properties are declared either the way Swift declares them, or the way a
1063/// Rust reader expects. Both are accepted, including in the same block, so a
1064/// port can keep the shape of its source and new code can read as Rust:
1065///
1066/// ```ignore
1067/// stateful! {
1068///     pub struct Counter {
1069///         @State var count: i64 = 0
1070///         @State var title: String = String::new()
1071///         @AppStorage("rswift.dark") var dark: bool = false
1072///         @Environment(ColorSchemeKey) var scheme
1073///         @FocusState var editor
1074///     }
1075/// }
1076///
1077/// stateful! {
1078///     pub struct Counter {
1079///         count: state(i64) = 0,
1080///         title: state(String) = String::new(),
1081///         dark: storage(bool) = ("rswift.dark", false),
1082///         scheme: env(ColorSchemeKey),
1083///         editor: focus(),
1084///     }
1085/// }
1086///
1087/// let c = Counter::new(|s| swiftui! { Text("{s.count} {s.title}") });
1088/// c.set_count(1);
1089/// ```
1090///
1091/// The difference is only where the key goes: Swift's wrapper carries it
1092/// — `@AppStorage("k") var dark: bool = false` — and Rust's pairs it with the
1093/// default, `dark: storage(bool) = ("k", false)`.
1094///
1095/// A `focus()` property also gets a `<name>_focus` field holding the three
1096/// words `.focused(_:)` wants, so the body can attach it to a field.
1097///
1098/// [`ComposedBuilder`]: swiftui_native::state::ComposedBuilder
1099#[proc_macro]
1100pub fn stateful(input: TokenStream) -> TokenStream {
1101    let decl = syn::parse_macro_input!(input as StatefulDecl);
1102    decl.expand().into()
1103}
1104
1105/// What a wrapper carries in its parentheses: a key string for `@AppStorage`,
1106/// a key *type* for `@Environment`.
1107enum WrapperArg {
1108    Expr(Expr),
1109    Type(syn::Type),
1110}
1111
1112impl Parse for WrapperArg {
1113    fn parse(input: ParseStream) -> Result<Self> {
1114        // `@AppStorage("k")` is an expression; `@Environment(ColorSchemeKey)`
1115        // is a type. A bare path parses as either, so try the expression first
1116        // and keep it only when it is something a type could not be.
1117        let fork = input.fork();
1118        if let Ok(e) = fork.parse::<Expr>() {
1119            if matches!(e, Expr::Lit(_) | Expr::Call(_) | Expr::MethodCall(_) | Expr::Macro(_)) {
1120                input.advance_to(&fork);
1121                return Ok(Self::Expr(e));
1122            }
1123        }
1124        Ok(Self::Type(input.parse()?))
1125    }
1126}
1127
1128/// Which wrapper, whichever way it was spelled.
1129#[derive(Clone, Copy, PartialEq, Eq)]
1130enum Kind {
1131    State,
1132    Storage,
1133    Env,
1134    Focus,
1135}
1136
1137/// One property, from either spelling.
1138///
1139/// The two are the same declaration:
1140///
1141/// ```ignore
1142/// @AppStorage("k") var dark: bool = false   // Swift's
1143/// dark: storage(bool) = ("k", false)        // Rust's
1144/// ```
1145struct PropDecl {
1146    name: Ident,
1147    kind: Kind,
1148    /// Where to point an error about this property.
1149    span: proc_macro2::Span,
1150    /// `@AppStorage`'s key, when the spelling puts it in the wrapper.
1151    key: Option<Expr>,
1152    /// `@Environment`'s key type.
1153    env_key: Option<syn::Type>,
1154    ty: Option<syn::Type>,
1155    init: Option<Expr>,
1156}
1157
1158struct StatefulDecl {
1159    vis: syn::Visibility,
1160    name: Ident,
1161    props: Vec<PropDecl>,
1162}
1163
1164impl Parse for StatefulDecl {
1165    fn parse(input: ParseStream) -> Result<Self> {
1166        let vis: syn::Visibility = input.parse()?;
1167        input.parse::<Token![struct]>().map_err(|e| {
1168            syn::Error::new(e.span(), "expected `struct <Name> { … }` — `stateful! { pub struct Counter { … } }`")
1169        })?;
1170        let name: Ident = input.parse()?;
1171        let inner;
1172        braced!(inner in input);
1173        let mut props = Vec::new();
1174        while !inner.is_empty() {
1175            // Both spellings are accepted, told apart by the leading `@`.
1176            props.push(if inner.peek(Token![@]) {
1177                parse_swift_prop(&inner)?
1178            } else {
1179                parse_rust_prop(&inner)?
1180            });
1181            if inner.is_empty() {
1182                break;
1183            }
1184            // Swift separates stored properties by line; a comma is accepted
1185            // too, because a Rust reader expects one.
1186            if inner.peek(Token![,]) {
1187                inner.parse::<Token![,]>()?;
1188            }
1189        }
1190        if props.is_empty() {
1191            return Err(syn::Error::new(name.span(), "a stateful view needs at least one property"));
1192        }
1193        Ok(Self { vis, name, props })
1194    }
1195}
1196
1197/// `@State var count: i64 = 0` — Swift's spelling.
1198fn parse_swift_prop(inner: ParseStream) -> Result<PropDecl> {
1199    inner.parse::<Token![@]>()?;
1200    let wrapper: Ident = inner.parse()?;
1201    let span = wrapper.span();
1202    let arg = if inner.peek(syn::token::Paren) {
1203        let args;
1204        syn::parenthesized!(args in inner);
1205        if args.is_empty() { None } else { Some(args.parse::<WrapperArg>()?) }
1206    } else {
1207        None
1208    };
1209    // `var` is Swift's, not Rust's, so it arrives as a plain identifier.
1210    let var: Ident = inner
1211        .parse()
1212        .map_err(|e| syn::Error::new(e.span(), "expected `var` after the wrapper, as in Swift"))?;
1213    if var != "var" {
1214        return Err(syn::Error::new(
1215            var.span(),
1216            format!("expected `var`, found `{var}` — `@State var count: i64 = 0`"),
1217        ));
1218    }
1219    let name: Ident = inner.parse()?;
1220    let ty = if inner.peek(Token![:]) {
1221        inner.parse::<Token![:]>()?;
1222        Some(inner.parse::<syn::Type>()?)
1223    } else {
1224        None
1225    };
1226    let init = if inner.peek(Token![=]) {
1227        inner.parse::<Token![=]>()?;
1228        Some(inner.parse::<Expr>()?)
1229    } else {
1230        None
1231    };
1232
1233    let w = wrapper.to_string();
1234    let kind = match w.as_str() {
1235        "State" => Kind::State,
1236        "AppStorage" => Kind::Storage,
1237        "Environment" => Kind::Env,
1238        "FocusState" => Kind::Focus,
1239        other => {
1240            return Err(syn::Error::new(
1241                span,
1242                format!(
1243                    "unknown property wrapper `@{other}` — one of `@State`, `@AppStorage`, \
1244                     `@Environment`, `@FocusState`"
1245                ),
1246            ));
1247        }
1248    };
1249    let (mut key, mut env_key) = (None, None);
1250    match (kind, arg) {
1251        (Kind::Storage, Some(WrapperArg::Expr(e))) => key = Some(e),
1252        (Kind::Storage, _) => {
1253            return Err(syn::Error::new(
1254                span,
1255                "`@AppStorage` needs its key — `@AppStorage(\"some.key\")`",
1256            ));
1257        }
1258        (Kind::Env, Some(WrapperArg::Type(t))) => env_key = Some(t),
1259        (Kind::Env, _) => {
1260            return Err(syn::Error::new(
1261                span,
1262                format!(
1263                    "`@Environment` needs its key type — `@Environment(ColorSchemeKey) var {name}`"
1264                ),
1265            ));
1266        }
1267        _ => {}
1268    }
1269    check_prop(kind, span, &name, &ty, &init, "Swift")?;
1270    Ok(PropDecl { name, kind, span, key, env_key, ty, init })
1271}
1272
1273/// `count: state(i64) = 0` — the Rust spelling, where the name leads and the
1274/// wrapper reads as a type constructor.
1275fn parse_rust_prop(inner: ParseStream) -> Result<PropDecl> {
1276    let name: Ident = inner.parse()?;
1277    inner.parse::<Token![:]>()?;
1278    let wrapper: Ident = inner.parse()?;
1279    let span = wrapper.span();
1280    let args;
1281    syn::parenthesized!(args in inner);
1282    let arg = if args.is_empty() { None } else { Some(args.parse::<WrapperArg>()?) };
1283    let init = if inner.peek(Token![=]) {
1284        inner.parse::<Token![=]>()?;
1285        Some(inner.parse::<Expr>()?)
1286    } else {
1287        None
1288    };
1289
1290    let w = wrapper.to_string();
1291    let kind = match w.as_str() {
1292        "state" => Kind::State,
1293        "storage" => Kind::Storage,
1294        "env" => Kind::Env,
1295        "focus" => Kind::Focus,
1296        other => {
1297            return Err(syn::Error::new(
1298                span,
1299                format!(
1300                    "unknown property kind `{other}` — one of `state`, `storage`, `env`, \
1301                     `focus`, or Swift's `@State` / `@AppStorage` / `@Environment` / \
1302                     `@FocusState`"
1303                ),
1304            ));
1305        }
1306    };
1307    let (mut ty, mut env_key) = (None, None);
1308    match (kind, arg) {
1309        (Kind::State | Kind::Storage, Some(WrapperArg::Type(t))) => ty = Some(t),
1310        (Kind::State | Kind::Storage, Some(WrapperArg::Expr(e))) => {
1311            // A bare `state(Foo)` parses as a type; anything else here is a
1312            // mistake worth naming.
1313            return Err(syn::Error::new(
1314                span,
1315                format!("`{w}` takes a type — `{name}: {w}(i64) = 0`, not `{}`", quote!(#e)),
1316            ));
1317        }
1318        (Kind::Env, Some(WrapperArg::Type(t))) => env_key = Some(t),
1319        _ => {}
1320    }
1321    check_prop(kind, span, &name, &ty, &init, "Rust")?;
1322    Ok(PropDecl { name, kind, span, key: None, env_key, ty, init })
1323}
1324
1325/// What both spellings have to supply, whichever way they say it.
1326fn check_prop(
1327    kind: Kind,
1328    span: proc_macro2::Span,
1329    name: &Ident,
1330    ty: &Option<syn::Type>,
1331    init: &Option<Expr>,
1332    style: &str,
1333) -> Result<()> {
1334    let swift = style == "Swift";
1335    match kind {
1336        Kind::State if ty.is_none() || init.is_none() => Err(syn::Error::new(
1337            span,
1338            if swift {
1339                format!("`@State` needs a type and a value — `@State var {name}: i64 = 0`")
1340            } else {
1341                format!("`state` needs a type and a value — `{name}: state(i64) = 0`")
1342            },
1343        )),
1344        Kind::Storage if ty.is_none() || init.is_none() => Err(syn::Error::new(
1345            span,
1346            if swift {
1347                format!(
1348                    "`@AppStorage` needs a type and a value — \
1349                     `@AppStorage(\"key\") var {name}: bool = false`"
1350                )
1351            } else {
1352                format!("`storage` needs a type and a key/value pair — `{name}: storage(bool) = (\"key\", false)`")
1353            },
1354        )),
1355        Kind::Env if ty.is_some() || init.is_some() => Err(syn::Error::new(
1356            span,
1357            "an `@Environment` property is read from the environment, so it takes no type or value",
1358        )),
1359        _ => Ok(()),
1360    }
1361}
1362
1363impl StatefulDecl {
1364    fn expand(&self) -> TokenStream2 {
1365        let vis = &self.vis;
1366        let name = &self.name;
1367        let state_ty = Ident::new(&format!("{name}State"), name.span());
1368
1369        let (mut handles, mut builds, mut fields, mut reads, mut setters) =
1370            (vec![], vec![], vec![], vec![], vec![]);
1371        let mut h_names: Vec<Ident> = Vec::new();
1372
1373        for p in &self.props {
1374            let f = &p.name;
1375            let h = Ident::new(&format!("h_{f}"), f.span());
1376            let setter = Ident::new(&format!("set_{f}"), f.span());
1377            h_names.push(h.clone());
1378            match p.kind {
1379                Kind::State => {
1380                    let ty = p.ty.as_ref().expect("checked");
1381                    let init = p.init.as_ref().expect("checked");
1382                    handles.push(quote!(#h: ::swiftui_native::state::StateProp<#ty>));
1383                    builds.push(quote!(let #h = __b.state::<#ty>(#init);));
1384                    fields.push(quote!(pub #f: #ty));
1385                    reads.push(quote!(#f: __p.state(#h)));
1386                    setters.push(quote! {
1387                        /// Write this `@State`, re-running the body. False before
1388                        /// the first body evaluation, when SwiftUI has not
1389                        /// installed the property yet.
1390                        pub fn #setter(&self, value: #ty) -> bool {
1391                            self.view.set_state(self.#h, value)
1392                        }
1393                    });
1394                }
1395                Kind::Storage => {
1396                    let ty = p.ty.as_ref().expect("checked");
1397                    let init = p.init.as_ref().expect("checked");
1398                    handles.push(quote!(#h: ::swiftui_native::state::StoredProp<#ty>));
1399                    // Swift's spelling carries the key in the wrapper; Rust's
1400                    // carries a `(key, value)` pair on the right.
1401                    builds.push(match p.key.as_ref() {
1402                        Some(k) => quote!(let #h = __b.app_storage::<#ty>(#k, #init);),
1403                        None => quote! {
1404                            let (__key, __default) = #init;
1405                            let #h = __b.app_storage::<#ty>(__key, __default);
1406                        },
1407                    });
1408                    fields.push(quote!(pub #f: #ty));
1409                    reads.push(quote!(#f: __p.stored(#h)));
1410                    setters.push(quote! {
1411                        /// Write this `@AppStorage`, which persists and re-runs
1412                        /// the body.
1413                        pub fn #setter(&self, value: #ty) {
1414                            self.view.set_stored(self.#h, value)
1415                        }
1416
1417                        /// Read it from outside the body.
1418                        pub fn #f(&self) -> #ty {
1419                            self.view.stored(self.#h)
1420                        }
1421                    });
1422                }
1423                Kind::Env => {
1424                    let key = p.env_key.as_ref().ok_or_else(|| {
1425                        syn::Error::new(p.span, "an `@Environment` property needs its key type")
1426                    });
1427                    let key = match key {
1428                        Ok(k) => k,
1429                        Err(e) => return e.to_compile_error(),
1430                    };
1431                    handles.push(quote!(#h: ::swiftui_native::state::EnvProp<#key>));
1432                    builds.push(quote!(let #h = __b.environment::<#key>();));
1433                    fields.push(
1434                        quote!(pub #f: <#key as ::swiftui_native::state::EnvKey>::Value),
1435                    );
1436                    reads.push(quote!(#f: __p.env(#h)));
1437                }
1438                Kind::Focus => {
1439                    let proj = Ident::new(&format!("{f}_focus"), f.span());
1440                    handles.push(quote!(#h: ::swiftui_native::state::FocusProp));
1441                    builds.push(quote!(let #h = __b.focus_state();));
1442                    fields.push(quote!(pub #f: bool));
1443                    fields.push(quote! {
1444                        /// The three words `.focused(_:)` wants for this
1445                        /// property; hand it to `views::focused_on`.
1446                        pub #proj: [u64; 3]
1447                    });
1448                    reads.push(quote!(#f: __p.focus(#h)));
1449                    reads.push(quote!(#proj: __p.focus_projection(#h)));
1450                    setters.push(quote! {
1451                        /// Move focus to — or away from — this property. False
1452                        /// before the first body evaluation.
1453                        pub fn #setter(&self, value: bool) -> bool {
1454                            self.view.set_focus(self.#h, value)
1455                        }
1456
1457                        /// Whether it currently has focus.
1458                        pub fn #f(&self) -> bool {
1459                            self.view.focus(self.#h)
1460                        }
1461                    });
1462                }
1463            }
1464        }
1465
1466        let doc = format!("Every property of [`{name}`], read before its body runs.");
1467        quote! {
1468            #[doc = #doc]
1469            #vis struct #state_ty {
1470                #(#fields,)*
1471            }
1472
1473            #vis struct #name {
1474                view: ::swiftui_native::state::ComposedView,
1475                #(#handles,)*
1476            }
1477
1478            impl #name {
1479                /// Build the type and one instance.
1480                pub fn new(
1481                    body: impl Fn(&#state_ty) -> ::swiftui_native::ViewHandle + Send + 'static,
1482                ) -> Self {
1483                    let mut __b = ::swiftui_native::state::ComposedBuilder::new();
1484                    #(#builds)*
1485                    let view = __b.build(move |__p| {
1486                        let __s = #state_ty { #(#reads,)* };
1487                        body(&__s)
1488                    });
1489                    Self { view, #(#h_names: #h_names,)* }
1490                }
1491
1492                /// Wrap the instance so it can be hosted like any other view.
1493                pub fn as_view(&self) -> ::swiftui_native::ViewHandle {
1494                    self.view.as_view()
1495                }
1496
1497                /// How many times SwiftUI has evaluated the body.
1498                pub fn runs(&self) -> usize {
1499                    self.view.runs()
1500                }
1501
1502                #(#setters)*
1503            }
1504        }
1505    }
1506}
1507
1508/// `Text("Item \(i)")` — a localisable `Text`, interpolated the way SwiftUI does.
1509///
1510/// [`text!`](swiftui_native::text) formats in Rust and hands SwiftUI a
1511/// *literal* key: `Text("Item 3")`, `hasFormatting: false`, no arguments. This
1512/// builds the key Swift's own interpolation builds — `"Item %lld"` with one
1513/// argument — which is the difference between a string a translation can
1514/// reorder and one it cannot.
1515///
1516/// ```ignore
1517/// ltext!("Item {}", i)                 // Text("Item \(i)")
1518/// ltext!("{} of {}", done, total)      // Text("\(done) of \(total)")
1519/// ```
1520///
1521/// Only `{}` is understood. A format spec like `{:.2}` is a Rust idea — the
1522/// specifier here is Swift's, chosen by the argument's type — so it is
1523/// rejected rather than silently ignored. Use [`text!`](swiftui_native::text)
1524/// where the formatting matters more than the localisation.
1525#[proc_macro]
1526pub fn ltext(input: TokenStream) -> TokenStream {
1527    let call = syn::parse_macro_input!(input as LocalizedText);
1528    quote!(#call).into()
1529}
1530
1531/// `ltext!("…{}…", args…)`, split into literal and interpolated segments.
1532struct LocalizedText {
1533    parts: Vec<LocalizedPart>,
1534}
1535
1536enum LocalizedPart {
1537    Literal(String),
1538    Value(Expr),
1539}
1540
1541impl Parse for LocalizedText {
1542    fn parse(input: ParseStream) -> Result<Self> {
1543        let format: syn::LitStr = input.parse()?;
1544        let mut args: Vec<Expr> = Vec::new();
1545        while input.parse::<Token![,]>().is_ok() {
1546            if input.is_empty() {
1547                break;
1548            }
1549            args.push(input.parse()?);
1550        }
1551
1552        let text = format.value();
1553        let mut parts = Vec::new();
1554        let mut literal = String::new();
1555        let mut used = 0usize;
1556        let mut rest = text.as_str();
1557        while let Some(at) = rest.find('{') {
1558            // `{{` is an escaped brace, as in `format!`.
1559            if rest[at + 1..].starts_with('{') {
1560                literal.push_str(&rest[..at + 1]);
1561                rest = &rest[at + 2..];
1562                continue;
1563            }
1564            let Some(close) = rest[at..].find('}') else {
1565                return Err(syn::Error::new(format.span(), "unclosed `{` in the format string"));
1566            };
1567            let spec = &rest[at + 1..at + close];
1568            if !spec.is_empty() {
1569                return Err(syn::Error::new(
1570                    format.span(),
1571                    format!(
1572                        "`{{{spec}}}` is a Rust format spec, and the specifier here is \
1573                         Swift's — chosen by the argument's type. Use `text!` if the \
1574                         formatting matters more than the localisation."
1575                    ),
1576                ));
1577            }
1578            literal.push_str(&rest[..at]);
1579            if !literal.is_empty() {
1580                parts.push(LocalizedPart::Literal(core::mem::take(&mut literal)));
1581            }
1582            let Some(arg) = args.get(used) else {
1583                return Err(syn::Error::new(
1584                    format.span(),
1585                    "more `{}` than arguments",
1586                ));
1587            };
1588            parts.push(LocalizedPart::Value(arg.clone()));
1589            used += 1;
1590            rest = &rest[at + close + 1..];
1591        }
1592        literal.push_str(rest.replace("}}", "}").as_str());
1593        if !literal.is_empty() {
1594            parts.push(LocalizedPart::Literal(literal));
1595        }
1596        if used != args.len() {
1597            return Err(syn::Error::new(
1598                format.span(),
1599                "more arguments than `{}`",
1600            ));
1601        }
1602        Ok(Self { parts })
1603    }
1604}
1605
1606impl quote::ToTokens for LocalizedText {
1607    fn to_tokens(&self, out: &mut TokenStream2) {
1608        let parts = self.parts.iter().map(|p| match p {
1609            LocalizedPart::Literal(s) => {
1610                quote!(::swiftui_native::views::TextPart::Literal(#s))
1611            }
1612            // Through the trait, so the argument's *type* picks the Swift
1613            // specifier — `%lld` for an integer, `%lf` for a double, and the
1614            // whole-string overload for text.
1615            LocalizedPart::Value(e) => quote!(
1616                ::swiftui_native::views::Interpolatable::as_part(&(#e))
1617            ),
1618        });
1619        out.extend(quote!(
1620            ::swiftui_native::view::View::new(
1621                ::swiftui_native::views::text_interpolated(&[#(#parts),*])
1622            )
1623        ));
1624    }
1625}