1use proc_macro::TokenStream;
28use proc_macro2::TokenStream as TokenStream2;
29use quote::quote;
30use syn::{
31 braced, parenthesized,
32 parse::{Parse, ParseStream},
33 parse_macro_input, Expr, Ident, Result, Token,
34};
35
36#[proc_macro]
50pub fn cha(input: TokenStream) -> TokenStream {
51 let input = parse_macro_input!(input as ChaInput);
52 let expanded = input.to_tokens();
53 TokenStream::from(expanded)
54}
55
56struct ChaInput {
62 ctx: Ident,
63 body: LayoutBody,
64}
65
66struct LayoutBody {
68 children: Vec<LayoutNode>,
69}
70
71enum LayoutNode {
73 Col(LayoutContainer),
74 Row(LayoutContainer),
75 Group(LayoutContainer),
76 Scroll(ScrollContainer),
77 Card(CardContainer),
78 Icon(IconNode),
79 If(IfNode),
81 IfElse(IfElseNode),
82 For(ForNode),
83 Enabled(ConditionContainer),
84 Visible(ConditionContainer),
85 Expr(Expr),
86}
87
88struct ScrollContainer {
90 direction: ScrollDirection,
91 props: Vec<LayoutProp>,
92 children: Vec<LayoutNode>,
93}
94
95#[derive(Clone, Copy)]
97enum ScrollDirection {
98 Vertical,
99 Horizontal,
100 Both,
101}
102
103struct CardContainer {
105 title: Option<Expr>,
106 props: Vec<LayoutProp>,
107 children: Vec<LayoutNode>,
108}
109
110struct LayoutContainer {
112 props: Vec<LayoutProp>,
113 children: Vec<LayoutNode>,
114}
115
116struct LayoutProp {
118 key: Ident,
119 value: Expr,
120}
121
122struct IconNode {
124 name: Ident,
125 size: Option<Expr>,
126}
127
128struct IfNode {
130 condition: Expr,
131 children: Vec<LayoutNode>,
132}
133
134struct IfElseNode {
136 condition: Expr,
137 if_children: Vec<LayoutNode>,
138 else_children: Vec<LayoutNode>,
139}
140
141struct ForNode {
143 pattern: syn::Pat,
144 iter: Expr,
145 children: Vec<LayoutNode>,
146}
147
148struct ConditionContainer {
150 condition: Expr,
151 children: Vec<LayoutNode>,
152}
153
154impl Parse for ChaInput {
159 fn parse(input: ParseStream) -> Result<Self> {
160 let ctx: Ident = input.parse().map_err(|e| {
162 syn::Error::new(
163 e.span(),
164 "cha! expects a ViewCtx identifier first: `cha!(ctx, { ... })`",
165 )
166 })?;
167 input.parse::<Token![,]>().map_err(|e| {
168 syn::Error::new(
169 e.span(),
170 "expected `,` between the ViewCtx identifier and the layout body: `cha!(ctx, { ... })`",
171 )
172 })?;
173
174 if !input.peek(syn::token::Brace) {
175 return Err(input.error("expected a braced layout body: `cha!(ctx, { ... })`"));
176 }
177 let content;
178 braced!(content in input);
179 let body = LayoutBody::parse(&content)?;
180
181 Ok(ChaInput { ctx, body })
182 }
183}
184
185impl LayoutBody {
186 fn parse(input: ParseStream) -> Result<Self> {
187 let mut children = Vec::new();
188
189 while !input.is_empty() {
190 let node = LayoutNode::parse(input)?;
191 children.push(node);
192 }
193
194 Ok(LayoutBody { children })
195 }
196}
197
198impl LayoutNode {
199 fn parse(input: ParseStream) -> Result<Self> {
200 if input.peek(Token![@]) {
202 input.parse::<Token![@]>()?;
203 let name: Ident = input.parse().map_err(|e| {
204 syn::Error::new(
205 e.span(),
206 "expected an icon name after `@`, e.g. `@house` or `@gear(20.0)`",
207 )
208 })?;
209
210 let size = if input.peek(syn::token::Paren) {
212 let content;
213 parenthesized!(content in input);
214 Some(content.parse::<Expr>()?)
215 } else {
216 None
217 };
218
219 return Ok(LayoutNode::Icon(IconNode { name, size }));
220 }
221
222 if input.peek(Ident) {
224 let fork = input.fork();
225 let ident: Ident = fork.parse()?;
226 let name = ident.to_string();
227
228 match name.as_str() {
229 "Col" | "Row" | "Group" => {
230 let _: Ident = input.parse()?;
232 let container = parse_container(input)?;
233 validate_props(&container.props, &["spacing", "padding"], &name)?;
234
235 return Ok(match name.as_str() {
236 "Col" => LayoutNode::Col(container),
237 "Row" => LayoutNode::Row(container),
238 "Group" => LayoutNode::Group(container),
239 _ => unreachable!(),
240 });
241 }
242 "Scroll" | "ScrollH" | "ScrollBoth" => {
243 let _: Ident = input.parse()?;
244 let direction = match name.as_str() {
245 "Scroll" => ScrollDirection::Vertical,
246 "ScrollH" => ScrollDirection::Horizontal,
247 "ScrollBoth" => ScrollDirection::Both,
248 _ => unreachable!(),
249 };
250 let container = parse_container(input)?;
251 validate_props(
252 &container.props,
253 &["max_height", "max_width", "min_height", "min_width", "id"],
254 &name,
255 )?;
256 return Ok(LayoutNode::Scroll(ScrollContainer {
257 direction,
258 props: container.props,
259 children: container.children,
260 }));
261 }
262 "Card" => {
263 let _: Ident = input.parse()?;
264 let (title, props, children) = parse_card(input)?;
265 validate_props(&props, &["padding"], &name)?;
266 return Ok(LayoutNode::Card(CardContainer {
267 title,
268 props,
269 children,
270 }));
271 }
272 "If" => {
274 let _: Ident = input.parse()?;
275 let (condition, children) = parse_condition_block(input, "If")?;
276 return Ok(LayoutNode::If(IfNode {
277 condition,
278 children,
279 }));
280 }
281 "IfElse" => {
283 let _: Ident = input.parse()?;
284 let (condition, if_children, else_children) = parse_if_else(input)?;
285 return Ok(LayoutNode::IfElse(IfElseNode {
286 condition,
287 if_children,
288 else_children,
289 }));
290 }
291 "For" => {
293 let _: Ident = input.parse()?;
294 let (pattern, iter, children) = parse_for(input)?;
295 return Ok(LayoutNode::For(ForNode {
296 pattern,
297 iter,
298 children,
299 }));
300 }
301 "Enabled" => {
303 let _: Ident = input.parse()?;
304 let (condition, children) = parse_condition_block(input, "Enabled")?;
305 return Ok(LayoutNode::Enabled(ConditionContainer {
306 condition,
307 children,
308 }));
309 }
310 "Visible" => {
312 let _: Ident = input.parse()?;
313 let (condition, children) = parse_condition_block(input, "Visible")?;
314 return Ok(LayoutNode::Visible(ConditionContainer {
315 condition,
316 children,
317 }));
318 }
319 _ => {}
320 }
321 }
322
323 let expr: Expr = input.parse()?;
325 Ok(LayoutNode::Expr(expr))
326 }
327}
328
329fn parse_container(input: ParseStream) -> Result<LayoutContainer> {
330 let mut props = Vec::new();
331 let mut children = Vec::new();
332
333 if input.peek(syn::token::Paren) {
335 let content;
336 parenthesized!(content in input);
337 props = parse_props(&content)?;
338 }
339
340 if input.peek(syn::token::Brace) {
342 let content;
343 braced!(content in input);
344 while !content.is_empty() {
345 children.push(LayoutNode::parse(&content)?);
346 }
347 }
348
349 Ok(LayoutContainer { props, children })
350}
351
352fn parse_props(input: ParseStream) -> Result<Vec<LayoutProp>> {
353 let mut props = Vec::new();
354
355 while !input.is_empty() {
356 let key: Ident = input.parse().map_err(|e| {
357 syn::Error::new(e.span(), "expected a property name, e.g. `(spacing: 8.0)`")
358 })?;
359 input.parse::<Token![:]>().map_err(|e| {
360 syn::Error::new(
361 e.span(),
362 format!("expected `:` after property `{key}`, e.g. `({key}: value)`"),
363 )
364 })?;
365 let value: Expr = input.parse().map_err(|e| {
366 syn::Error::new(
367 e.span(),
368 format!("expected a value expression for property `{key}`"),
369 )
370 })?;
371 props.push(LayoutProp { key, value });
372
373 if input.peek(Token![,]) {
374 input.parse::<Token![,]>()?;
375 }
376 }
377
378 Ok(props)
379}
380
381fn validate_props(props: &[LayoutProp], allowed: &[&str], node: &str) -> Result<()> {
386 for prop in props {
387 let key = prop.key.to_string();
388 if !allowed.contains(&key.as_str()) {
389 let supported = allowed
390 .iter()
391 .map(|a| format!("`{a}`"))
392 .collect::<Vec<_>>()
393 .join(", ");
394 return Err(syn::Error::new_spanned(
395 &prop.key,
396 format!("unknown property `{key}` for `{node}`; supported: {supported}"),
397 ));
398 }
399 }
400 Ok(())
401}
402
403fn parse_card(input: ParseStream) -> Result<(Option<Expr>, Vec<LayoutProp>, Vec<LayoutNode>)> {
405 let mut title = None;
406 let mut props = Vec::new();
407 let mut children = Vec::new();
408
409 if input.peek(syn::token::Paren) {
411 let content;
412 parenthesized!(content in input);
413
414 if !content.is_empty() {
416 let fork = content.fork();
417 if fork.peek(Ident) {
419 let _: Ident = fork.parse()?;
420 if fork.peek(Token![:]) {
421 props = parse_props(&content)?;
423 } else {
424 title = Some(content.parse::<Expr>()?);
426 if content.peek(Token![,]) {
427 content.parse::<Token![,]>()?;
428 props = parse_props(&content)?;
429 }
430 }
431 } else {
432 title = Some(content.parse::<Expr>()?);
434 if content.peek(Token![,]) {
435 content.parse::<Token![,]>()?;
436 props = parse_props(&content)?;
437 }
438 }
439 }
440 }
441
442 if input.peek(syn::token::Brace) {
444 let content;
445 braced!(content in input);
446 while !content.is_empty() {
447 children.push(LayoutNode::parse(&content)?);
448 }
449 }
450
451 Ok((title, props, children))
452}
453
454fn parse_condition_block(input: ParseStream, keyword: &str) -> Result<(Expr, Vec<LayoutNode>)> {
456 if !input.peek(syn::token::Paren) {
458 return Err(input.error(format!(
459 "`{keyword}` expects a parenthesized condition: `{keyword}(condition) {{ ... }}`"
460 )));
461 }
462 let content;
463 parenthesized!(content in input);
464 let condition: Expr = content.parse().map_err(|e| {
465 syn::Error::new(
466 e.span(),
467 format!("`{keyword}` expects a boolean condition expression"),
468 )
469 })?;
470
471 let mut children = Vec::new();
473 if input.peek(syn::token::Brace) {
474 let content;
475 braced!(content in input);
476 while !content.is_empty() {
477 children.push(LayoutNode::parse(&content)?);
478 }
479 }
480
481 Ok((condition, children))
482}
483
484fn parse_if_else(input: ParseStream) -> Result<(Expr, Vec<LayoutNode>, Vec<LayoutNode>)> {
486 if !input.peek(syn::token::Paren) {
488 return Err(input.error(
489 "`IfElse` expects a parenthesized condition: `IfElse(condition) { ... } Else { ... }`",
490 ));
491 }
492 let content;
493 parenthesized!(content in input);
494 let condition: Expr = content.parse().map_err(|e| {
495 syn::Error::new(e.span(), "`IfElse` expects a boolean condition expression")
496 })?;
497
498 let mut if_children = Vec::new();
500 if input.peek(syn::token::Brace) {
501 let content;
502 braced!(content in input);
503 while !content.is_empty() {
504 if_children.push(LayoutNode::parse(&content)?);
505 }
506 }
507
508 let mut else_children = Vec::new();
510 if input.peek(Ident) {
511 let fork = input.fork();
512 let ident: Ident = fork.parse()?;
513 if ident == "Else" {
514 let _: Ident = input.parse()?; if input.peek(syn::token::Brace) {
516 let content;
517 braced!(content in input);
518 while !content.is_empty() {
519 else_children.push(LayoutNode::parse(&content)?);
520 }
521 }
522 }
523 }
524
525 Ok((condition, if_children, else_children))
526}
527
528fn parse_for(input: ParseStream) -> Result<(syn::Pat, Expr, Vec<LayoutNode>)> {
530 if !input.peek(syn::token::Paren) {
532 return Err(input.error("`For` expects `For(pattern in iterator) { ... }`"));
533 }
534 let content;
535 parenthesized!(content in input);
536
537 let pattern = syn::Pat::parse_single(&content).map_err(|e| {
539 syn::Error::new(
540 e.span(),
541 "`For` expects a binding pattern before `in`, e.g. `For(item in &model.items)`",
542 )
543 })?;
544
545 content.parse::<Token![in]>().map_err(|e| {
547 syn::Error::new(
548 e.span(),
549 "`For` expects the `in` keyword: `For(pattern in iterator)`",
550 )
551 })?;
552
553 let iter: Expr = content.parse().map_err(|e| {
555 syn::Error::new(e.span(), "`For` expects an iterator expression after `in`")
556 })?;
557
558 let mut children = Vec::new();
560 if input.peek(syn::token::Brace) {
561 let content;
562 braced!(content in input);
563 while !content.is_empty() {
564 children.push(LayoutNode::parse(&content)?);
565 }
566 }
567
568 Ok((pattern, iter, children))
569}
570
571impl ChaInput {
576 fn to_tokens(&self) -> TokenStream2 {
577 let ctx = &self.ctx;
578 let children = self.body.children.iter().map(|c| c.to_tokens(ctx));
579
580 quote! {
581 #(#children)*
582 }
583 }
584}
585
586impl LayoutNode {
587 fn to_tokens(&self, ctx: &Ident) -> TokenStream2 {
588 match self {
589 LayoutNode::Col(container) => {
590 let setup = props_to_setup(&container.props, "y");
591 let children = container.children.iter().map(|c| c.to_tokens(ctx));
592
593 quote! {
594 #ctx.vertical(|#ctx| {
595 #setup
596 #(#children)*
597 });
598 }
599 }
600 LayoutNode::Row(container) => {
601 let setup = props_to_setup(&container.props, "x");
602 let children = container.children.iter().map(|c| c.to_tokens(ctx));
603
604 quote! {
605 #ctx.horizontal(|#ctx| {
606 #setup
607 #(#children)*
608 });
609 }
610 }
611 LayoutNode::Group(container) => {
612 let setup = props_to_setup(&container.props, "y");
613 let children = container.children.iter().map(|c| c.to_tokens(ctx));
614
615 quote! {
616 #ctx.group(|#ctx| {
617 #setup
618 #(#children)*
619 });
620 }
621 }
622 LayoutNode::Scroll(scroll) => {
623 let scroll_props = scroll_props_to_builder(&scroll.props);
624 let children = scroll.children.iter().map(|c| c.to_tokens(ctx));
625 let constructor = match scroll.direction {
626 ScrollDirection::Vertical => quote! { ::egui_cha::ScrollArea::vertical() },
627 ScrollDirection::Horizontal => quote! { ::egui_cha::ScrollArea::horizontal() },
628 ScrollDirection::Both => quote! { ::egui_cha::ScrollArea::both() },
629 };
630
631 quote! {
632 #constructor #scroll_props .show_ctx(#ctx, |#ctx| {
633 #(#children)*
634 });
635 }
636 }
637 LayoutNode::Card(card) => {
638 let card_props = card_props_to_builder(&card.props);
639 let children = card.children.iter().map(|c| c.to_tokens(ctx));
640 let constructor = if let Some(title) = &card.title {
641 quote! { ::egui_cha_ds::Card::titled(#title) }
642 } else {
643 quote! { ::egui_cha_ds::Card::new() }
644 };
645
646 quote! {
647 #constructor #card_props .show_ctx(#ctx, |#ctx| {
648 #(#children)*
649 });
650 }
651 }
652 LayoutNode::Icon(icon) => {
653 let name = &icon.name;
654 if let Some(size) = &icon.size {
655 quote! {
656 ::egui_cha_ds::Icon::#name().size(#size).show_ctx(#ctx);
657 }
658 } else {
659 quote! {
660 ::egui_cha_ds::Icon::#name().show_ctx(#ctx);
661 }
662 }
663 }
664 LayoutNode::If(if_node) => {
666 let condition = &if_node.condition;
667 let children = if_node.children.iter().map(|c| c.to_tokens(ctx));
668
669 quote! {
670 #ctx.show_if(#condition, |#ctx| {
671 #(#children)*
672 });
673 }
674 }
675 LayoutNode::IfElse(if_else) => {
677 let condition = &if_else.condition;
678 let if_children = if_else.if_children.iter().map(|c| c.to_tokens(ctx));
679 let else_children = if_else.else_children.iter().map(|c| c.to_tokens(ctx));
680
681 quote! {
682 #ctx.show_if_else(
683 #condition,
684 |#ctx| { #(#if_children)* },
685 |#ctx| { #(#else_children)* }
686 );
687 }
688 }
689 LayoutNode::For(for_node) => {
691 let pattern = &for_node.pattern;
692 let iter = &for_node.iter;
693 let children = for_node.children.iter().map(|c| c.to_tokens(ctx));
694
695 quote! {
696 for #pattern in #iter {
697 #(#children)*
698 }
699 }
700 }
701 LayoutNode::Enabled(container) => {
703 let condition = &container.condition;
704 let children = container.children.iter().map(|c| c.to_tokens(ctx));
705
706 quote! {
707 #ctx.enabled_if(#condition, |#ctx| {
708 #(#children)*
709 });
710 }
711 }
712 LayoutNode::Visible(container) => {
714 let condition = &container.condition;
715 let children = container.children.iter().map(|c| c.to_tokens(ctx));
716
717 quote! {
718 #ctx.visible_if(#condition, |#ctx| {
719 #(#children)*
720 });
721 }
722 }
723 LayoutNode::Expr(expr) => {
724 quote! { #expr; }
725 }
726 }
727 }
728}
729
730fn props_to_setup(props: &[LayoutProp], axis: &str) -> TokenStream2 {
731 let setups: Vec<TokenStream2> = props
732 .iter()
733 .filter_map(|prop| {
734 let key = prop.key.to_string();
735 let value = &prop.value;
736
737 match key.as_str() {
738 "spacing" => {
739 if axis == "y" {
740 Some(quote! { ctx.ui.spacing_mut().item_spacing.y = #value; })
741 } else {
742 Some(quote! { ctx.ui.spacing_mut().item_spacing.x = #value; })
743 }
744 }
745 "padding" => Some(quote! {
746 ctx.ui.spacing_mut().window_margin = egui::Margin::same(#value);
747 }),
748 _ => None,
749 }
750 })
751 .collect();
752
753 quote! { #(#setups)* }
754}
755
756fn scroll_props_to_builder(props: &[LayoutProp]) -> TokenStream2 {
758 let methods: Vec<TokenStream2> = props
759 .iter()
760 .filter_map(|prop| {
761 let key = prop.key.to_string();
762 let value = &prop.value;
763
764 match key.as_str() {
765 "max_height" => Some(quote! { .max_height(#value) }),
766 "max_width" => Some(quote! { .max_width(#value) }),
767 "min_height" => Some(quote! { .min_scrolled_height(#value) }),
768 "min_width" => Some(quote! { .min_scrolled_width(#value) }),
769 "id" => Some(quote! { .id_salt(#value) }),
770 _ => None,
771 }
772 })
773 .collect();
774
775 quote! { #(#methods)* }
776}
777
778fn card_props_to_builder(props: &[LayoutProp]) -> TokenStream2 {
780 let methods: Vec<TokenStream2> = props
781 .iter()
782 .filter_map(|prop| {
783 let key = prop.key.to_string();
784 let value = &prop.value;
785
786 match key.as_str() {
787 "padding" => Some(quote! { .padding(#value) }),
788 _ => None,
789 }
790 })
791 .collect();
792
793 quote! { #(#methods)* }
794}
795
796#[cfg(test)]
801mod tests {
802 use super::*;
803
804 #[test]
805 fn test_parse_simple() {
806 let input: TokenStream2 = quote! {
807 ctx, {
808 ctx.ui.label("Hello")
809 }
810 };
811 let parsed: ChaInput = syn::parse2(input).unwrap();
812 let _ = parsed.to_tokens();
813 }
814
815 #[test]
816 fn test_parse_col() {
817 let input: TokenStream2 = quote! {
818 ctx, {
819 Col {
820 ctx.ui.label("Hello")
821 }
822 }
823 };
824 let parsed: ChaInput = syn::parse2(input).unwrap();
825 let _ = parsed.to_tokens();
826 }
827
828 #[test]
829 fn test_parse_col_with_props() {
830 let input: TokenStream2 = quote! {
831 ctx, {
832 Col(spacing: 8.0) {
833 ctx.ui.label("Hello")
834 }
835 }
836 };
837 let parsed: ChaInput = syn::parse2(input).unwrap();
838 let _ = parsed.to_tokens();
839 }
840
841 #[test]
842 fn test_parse_nested() {
843 let input: TokenStream2 = quote! {
844 ctx, {
845 Col(spacing: 8.0) {
846 Row {
847 ctx.ui.label("A")
848 ctx.ui.label("B")
849 }
850 }
851 }
852 };
853 let parsed: ChaInput = syn::parse2(input).unwrap();
854 let _ = parsed.to_tokens();
855 }
856
857 #[test]
858 fn test_parse_icon_shorthand() {
859 let input: TokenStream2 = quote! {
860 ctx, {
861 Row {
862 @house
863 @gear(20.0)
864 }
865 }
866 };
867 let parsed: ChaInput = syn::parse2(input).unwrap();
868 let tokens = parsed.to_tokens();
869 let code = tokens.to_string();
870 assert!(code.contains("Icon"));
871 assert!(code.contains("house"));
872 assert!(code.contains("gear"));
873 assert!(code.contains("size"));
874 }
875
876 #[test]
877 fn test_parse_scroll() {
878 let input: TokenStream2 = quote! {
879 ctx, {
880 Scroll(max_height: 300.0) {
881 ctx.ui.label("Scrollable")
882 }
883 }
884 };
885 let parsed: ChaInput = syn::parse2(input).unwrap();
886 let tokens = parsed.to_tokens();
887 let code = tokens.to_string();
888 assert!(code.contains("ScrollArea"));
889 assert!(code.contains("vertical"));
890 assert!(code.contains("max_height"));
891 }
892
893 #[test]
894 fn test_parse_scroll_horizontal() {
895 let input: TokenStream2 = quote! {
896 ctx, {
897 ScrollH {
898 ctx.ui.label("Horizontal")
899 }
900 }
901 };
902 let parsed: ChaInput = syn::parse2(input).unwrap();
903 let tokens = parsed.to_tokens();
904 let code = tokens.to_string();
905 assert!(code.contains("ScrollArea"));
906 assert!(code.contains("horizontal"));
907 }
908
909 #[test]
910 fn test_parse_scroll_both() {
911 let input: TokenStream2 = quote! {
912 ctx, {
913 ScrollBoth(max_height: 400.0, max_width: 600.0) {
914 ctx.ui.label("Both directions")
915 }
916 }
917 };
918 let parsed: ChaInput = syn::parse2(input).unwrap();
919 let tokens = parsed.to_tokens();
920 let code = tokens.to_string();
921 assert!(code.contains("ScrollArea"));
922 assert!(code.contains("both"));
923 assert!(code.contains("max_height"));
924 assert!(code.contains("max_width"));
925 }
926
927 #[test]
928 fn test_parse_card_with_title() {
929 let input: TokenStream2 = quote! {
930 ctx, {
931 Card("My Card") {
932 ctx.ui.label("Content")
933 }
934 }
935 };
936 let parsed: ChaInput = syn::parse2(input).unwrap();
937 let tokens = parsed.to_tokens();
938 let code = tokens.to_string();
939 assert!(code.contains("Card"));
940 assert!(code.contains("titled"));
941 }
942
943 #[test]
944 fn test_parse_card_without_title() {
945 let input: TokenStream2 = quote! {
946 ctx, {
947 Card {
948 ctx.ui.label("Content")
949 }
950 }
951 };
952 let parsed: ChaInput = syn::parse2(input).unwrap();
953 let tokens = parsed.to_tokens();
954 let code = tokens.to_string();
955 assert!(code.contains("Card"));
956 assert!(code.contains("new"));
957 }
958
959 #[test]
960 fn test_parse_card_with_props() {
961 let input: TokenStream2 = quote! {
962 ctx, {
963 Card("Title", padding: 8.0) {
964 ctx.ui.label("Content")
965 }
966 }
967 };
968 let parsed: ChaInput = syn::parse2(input).unwrap();
969 let tokens = parsed.to_tokens();
970 let code = tokens.to_string();
971 assert!(code.contains("Card"));
972 assert!(code.contains("titled"));
973 assert!(code.contains("padding"));
974 }
975
976 #[test]
977 fn test_parse_if() {
978 let input: TokenStream2 = quote! {
979 ctx, {
980 If(model.is_admin) {
981 ctx.ui.label("Admin")
982 }
983 }
984 };
985 let parsed: ChaInput = syn::parse2(input).unwrap();
986 let tokens = parsed.to_tokens();
987 let code = tokens.to_string();
988 assert!(code.contains("show_if"));
989 assert!(code.contains("is_admin"));
990 }
991
992 #[test]
993 fn test_parse_if_else() {
994 let input: TokenStream2 = quote! {
995 ctx, {
996 IfElse(model.loading) {
997 ctx.ui.spinner()
998 } Else {
999 ctx.ui.label("Loaded")
1000 }
1001 }
1002 };
1003 let parsed: ChaInput = syn::parse2(input).unwrap();
1004 let tokens = parsed.to_tokens();
1005 let code = tokens.to_string();
1006 assert!(code.contains("show_if_else"));
1007 assert!(code.contains("loading"));
1008 }
1009
1010 #[test]
1011 fn test_parse_for() {
1012 let input: TokenStream2 = quote! {
1013 ctx, {
1014 For(item in &model.items) {
1015 ctx.ui.label(&item.name)
1016 }
1017 }
1018 };
1019 let parsed: ChaInput = syn::parse2(input).unwrap();
1020 let tokens = parsed.to_tokens();
1021 let code = tokens.to_string();
1022 assert!(code.contains("for"));
1023 assert!(code.contains("item"));
1024 assert!(code.contains("items"));
1025 }
1026
1027 #[test]
1028 fn test_parse_enabled() {
1029 let input: TokenStream2 = quote! {
1030 ctx, {
1031 Enabled(model.can_submit) {
1032 ctx.ui.button("Submit")
1033 }
1034 }
1035 };
1036 let parsed: ChaInput = syn::parse2(input).unwrap();
1037 let tokens = parsed.to_tokens();
1038 let code = tokens.to_string();
1039 assert!(code.contains("enabled_if"));
1040 assert!(code.contains("can_submit"));
1041 }
1042
1043 #[test]
1044 fn test_parse_visible() {
1045 let input: TokenStream2 = quote! {
1046 ctx, {
1047 Visible(model.show_details) {
1048 ctx.ui.label("Details")
1049 }
1050 }
1051 };
1052 let parsed: ChaInput = syn::parse2(input).unwrap();
1053 let tokens = parsed.to_tokens();
1054 let code = tokens.to_string();
1055 assert!(code.contains("visible_if"));
1056 assert!(code.contains("show_details"));
1057 }
1058
1059 #[test]
1060 fn test_parse_nested_control_flow() {
1061 let input: TokenStream2 = quote! {
1062 ctx, {
1063 Col {
1064 If(model.show_list) {
1065 For(item in &model.items) {
1066 Card(&item.title) {
1067 ctx.ui.label(&item.content)
1068 }
1069 }
1070 }
1071 }
1072 }
1073 };
1074 let parsed: ChaInput = syn::parse2(input).unwrap();
1075 let tokens = parsed.to_tokens();
1076 let code = tokens.to_string();
1077 assert!(code.contains("vertical"));
1078 assert!(code.contains("show_if"));
1079 assert!(code.contains("for"));
1080 assert!(code.contains("Card"));
1081 }
1082
1083 fn parse_err(input: TokenStream2) -> String {
1088 match syn::parse2::<ChaInput>(input) {
1089 Ok(_) => panic!("expected a parse error"),
1090 Err(e) => e.to_string(),
1091 }
1092 }
1093
1094 #[test]
1095 fn missing_comma_after_ctx_reports_expected_syntax() {
1096 let err = parse_err(quote! {
1097 ctx {
1098 ctx.ui.label("Hello")
1099 }
1100 });
1101 assert!(err.contains("expected `,`"), "unexpected message: {err}");
1102 }
1103
1104 #[test]
1105 fn unknown_container_prop_is_rejected_with_supported_list() {
1106 let err = parse_err(quote! {
1107 ctx, {
1108 Col(spacig: 8.0) {
1109 ctx.ui.label("Hello")
1110 }
1111 }
1112 });
1113 assert!(
1114 err.contains("unknown property `spacig` for `Col`"),
1115 "unexpected message: {err}"
1116 );
1117 assert!(err.contains("`spacing`"), "unexpected message: {err}");
1118 }
1119
1120 #[test]
1121 fn unknown_scroll_prop_is_rejected_with_supported_list() {
1122 let err = parse_err(quote! {
1123 ctx, {
1124 Scroll(height: 300.0) {
1125 ctx.ui.label("Scrollable")
1126 }
1127 }
1128 });
1129 assert!(
1130 err.contains("unknown property `height` for `Scroll`"),
1131 "unexpected message: {err}"
1132 );
1133 assert!(err.contains("`max_height`"), "unexpected message: {err}");
1134 }
1135
1136 #[test]
1137 fn unknown_card_prop_is_rejected_with_supported_list() {
1138 let err = parse_err(quote! {
1139 ctx, {
1140 Card("Title", margin: 8.0) {
1141 ctx.ui.label("Content")
1142 }
1143 }
1144 });
1145 assert!(
1146 err.contains("unknown property `margin` for `Card`"),
1147 "unexpected message: {err}"
1148 );
1149 assert!(err.contains("`padding`"), "unexpected message: {err}");
1150 }
1151
1152 #[test]
1153 fn if_without_condition_reports_expected_syntax() {
1154 let err = parse_err(quote! {
1155 ctx, {
1156 If {
1157 ctx.ui.label("Admin")
1158 }
1159 }
1160 });
1161 assert!(
1162 err.contains("`If` expects a parenthesized condition"),
1163 "unexpected message: {err}"
1164 );
1165 }
1166
1167 #[test]
1168 fn for_without_in_keyword_reports_expected_syntax() {
1169 let err = parse_err(quote! {
1170 ctx, {
1171 For(item, &model.items) {
1172 ctx.ui.label(&item.name)
1173 }
1174 }
1175 });
1176 assert!(err.contains("`in` keyword"), "unexpected message: {err}");
1177 }
1178
1179 #[test]
1180 fn icon_without_name_reports_expected_icon() {
1181 let err = parse_err(quote! {
1182 ctx, {
1183 @
1184 }
1185 });
1186 assert!(
1187 err.contains("icon name after `@`"),
1188 "unexpected message: {err}"
1189 );
1190 }
1191}