1use 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#[proc_macro]
59pub fn swiftui(input: TokenStream) -> TokenStream {
60 let body = syn::parse_macro_input!(input as Node);
61 quote!(#body).into()
62}
63
64enum Node {
66 Call(CallNode),
68 Plain(Expr),
70 If(Box<IfNode>),
72 ForEach(Box<ForEachNode>),
74 Match(Box<MatchNode>),
75 Let(syn::Stmt),
77}
78
79struct CallNode {
80 name: Ident,
81 args: Vec<Arg>,
82 children: Option<Vec<Node>>,
83 action: Option<Vec<syn::Stmt>>,
90 modifiers: TokenStream2,
92}
93
94struct Arg {
96 label: Option<Ident>,
97 value: Expr,
98}
99
100struct IfNode {
101 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
114struct 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
127impl Parse for Node {
130 fn parse(input: ParseStream) -> Result<Self> {
131 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 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 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
210fn takes_an_action(method: &Ident) -> bool {
221 actions::ACTION_MODIFIERS.binary_search(&method.to_string().as_str()).is_ok()
222}
223
224fn closure_params(input: ParseStream) -> Result<Vec<Ident>> {
226 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
247fn 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 out.push(inner.parse().map_err(|e| {
258 let msg = e.to_string();
259 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 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 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 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 if input.peek(syn::token::Brace) {
358 let last = if takes_an_action(&method) {
359 let inner;
360 braced!(inner in input);
361 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 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 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 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
418fn 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
433fn 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()?; 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 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 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
525fn 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 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 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
584fn is_format_string(raw: &str) -> bool {
591 raw.contains('{') || raw.contains('}')
592}
593
594fn 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 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 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 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
661fn 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 args.iter().map(|e| quote!(#e)).collect()
703}
704
705fn 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
722fn 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
738impl 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 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 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 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 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 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 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
851fn 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
871fn 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 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", ..) => {
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 ("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 ("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 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 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 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 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#[proc_macro]
1100pub fn stateful(input: TokenStream) -> TokenStream {
1101 let decl = syn::parse_macro_input!(input as StatefulDecl);
1102 decl.expand().into()
1103}
1104
1105enum WrapperArg {
1108 Expr(Expr),
1109 Type(syn::Type),
1110}
1111
1112impl Parse for WrapperArg {
1113 fn parse(input: ParseStream) -> Result<Self> {
1114 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#[derive(Clone, Copy, PartialEq, Eq)]
1130enum Kind {
1131 State,
1132 Storage,
1133 Env,
1134 Focus,
1135}
1136
1137struct PropDecl {
1146 name: Ident,
1147 kind: Kind,
1148 span: proc_macro2::Span,
1150 key: Option<Expr>,
1152 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 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 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
1197fn 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 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
1273fn 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 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
1325fn 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 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 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 pub fn #setter(&self, value: #ty) {
1414 self.view.set_stored(self.#h, value)
1415 }
1416
1417 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 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 pub fn #setter(&self, value: bool) -> bool {
1454 self.view.set_focus(self.#h, value)
1455 }
1456
1457 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 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 pub fn as_view(&self) -> ::swiftui_native::ViewHandle {
1494 self.view.as_view()
1495 }
1496
1497 pub fn runs(&self) -> usize {
1499 self.view.runs()
1500 }
1501
1502 #(#setters)*
1503 }
1504 }
1505 }
1506}
1507
1508#[proc_macro]
1526pub fn ltext(input: TokenStream) -> TokenStream {
1527 let call = syn::parse_macro_input!(input as LocalizedText);
1528 quote!(#call).into()
1529}
1530
1531struct 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 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 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}