ifengine_macros 0.0.6

Procedural macros for ifengine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
//! See [`ifengine::elements`]
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    Arm, Error, Expr, ExprClosure, ItemFn, LitStr, Result, Token,
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
};
mod nodes;
use nodes::*;

/// Decorate your function with this.
///
/// The function must take your game state as a parameter, and return `()`.
/// This macro will rewrite your function to receive a &mut [`ifengine::Game`] and return a [`ifengine::core::Response`], as well as enabling usage of [`ifengine::elements`] to produce that response (which in most cases will be a [`ifengine::View`]).
///
/// # Examples
///```rust
/// #[ifview]
/// pub fn p1(s: &mut State) {
///     h!("SALTWRACK", 3); // heading level 3
///     p!(link!("BEGIN", p2)); // Link to the next page
/// }
///
/// // ----- mod.rs -----
/// pub type Game = ifengine::Game<State>;
/// pub fn new() -> Game {
///    ifengine::Game!(chap1::p1)
/// }
///```
#[proc_macro_attribute]
pub fn ifview(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);

    let name = &input.sig.ident;
    let original_block = &input.block;

    if input.sig.inputs.len() != 1 {
        return Error::new_spanned(
            &input.sig.inputs,
            "ifview functions must have exactly one input: the context type C",
        )
        .to_compile_error()
        .into();
    }

    let ctx_arg = input.sig.inputs.first().unwrap();
    let ctx_type = if let syn::FnArg::Typed(pat_type) = ctx_arg
        && let syn::Type::Reference(ty_ref) = &*pat_type.ty
        && ty_ref.mutability.is_some()
    {
        &*ty_ref.elem
    } else {
        return Error::new_spanned(ctx_arg, "Expected a &mut C type")
            .to_compile_error()
            .into();
    };

    let expanded = quote! {
        pub fn #name(__ifengine_game: &mut ifengine::Game<#ctx_type>)
        -> ifengine::core::Response
        {
            let __ifengine_simulating = __ifengine_game.simulating();
            #[allow(unused_variables)]
            let #ctx_arg = &mut __ifengine_game.context;
            let __ifengine_game_tags = &mut __ifengine_game.tags;
            let __ifengine_game = &mut __ifengine_game.inner;
            let mut __ifengine_page_state = ifengine::core::PageState::new(

                format!("{}::{}", module_path!(), stringify!(#name)),
                __ifengine_game.fresh(),
                __ifengine_simulating,
                __ifengine_game.state.get_page_mut(format!("{}::{}", module_path!(), stringify!(#name))),
                __ifengine_game_tags,

            );

            #original_block

            #[allow(unreachable_code)]
            __ifengine_page_state.into_response()
        }
    };

    expanded.into()
}

// ----------- CHOICES -------------------------

// Expr instead of Pattern
struct LineArm {
    line: Expr,
    block: Option<Expr>,
}

impl Parse for LineArm {
    fn parse(input: ParseStream) -> Result<Self> {
        let line: Expr = input.parse()?;

        let block = if input.parse::<Token![=>]>().is_ok() {
            Some(input.parse()?)
        } else {
            None
        };

        Ok(LineArm { line, block })
    }
}
struct ChoiceInput {
    maybe_key: MaybeKey,
    arms: Vec<LineArm>,
}

impl Parse for ChoiceInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let maybe_key = input.parse()?;

        let mut arms = Vec::new();
        while !input.is_empty() {
            let mut lhs_exprs = vec![input.parse::<Expr>()?];

            while input.peek(Token![|]) {
                let _ = input.parse::<Token![|]>()?;
                lhs_exprs.push(input.parse()?);
            }

            let block = if input.parse::<Token![=>]>().is_ok() {
                Some(input.parse()?)
            } else {
                None
            };

            for line in lhs_exprs {
                arms.push(LineArm {
                    line,
                    block: block.clone(),
                });
            }

            input.parse::<Token![,]>().ok();
        }

        Ok(ChoiceInput { maybe_key, arms })
    }
}

/// Conditionally display one of several choices based on user selection.
///
/// Returns true if it has resolved, otherwise false.
///
/// # Description
/// The `choice!` macro takes a list of arms in the form `LHS => RHS`, where both
/// sides implement `Into<`[`Line`](ifengine::view::Line)`>`. It works as follows:
///
/// - If no arm is selected, the LHS values are displayed as a list of lines.
/// - Once a choice is selcted, subsequent renders execute the corresponding RHS expression and
///   display its result.
///
/// # Additional
/// A [`MaybeKey`] can be specified as the first argument
///   When a choice is clicked, it sets the value of its key to (the u8 value of) its id in [`PageState`].
///   It is discouraged to specify this: by default, it will be automatically generated.
/// Multiple LHS values can be specified for the same RHS using `|`
///
/// # Example
/// ```rust
/// choice! {
///     "1" => "Chose 1",
///     "2" | "3" => {
///         "Chose 2 or 3"
///     },
/// };
/// ```
#[proc_macro]
pub fn choice(input: TokenStream) -> TokenStream {
    let ChoiceInput { maybe_key, arms } = syn::parse_macro_input!(input as ChoiceInput);

    let key_tokens = maybe_key.into_tokens();

    let mut index_arms = Vec::new();
    let mut lines = Vec::new();

    for (i, LineArm { line, block }) in arms.iter().enumerate() {
        let i = i as u8;

        lines.push(quote! { (#i, ifengine::view::Line::from(#line)) });

        let block_tokens = match block {
            Some(b) => quote! { ifengine::view::Line::from({ #b }) },
            None => quote! { unreachable!() },
        };

        index_arms.push(quote! {
            #i => { #block_tokens }
        });
    }

    let expanded = quote! {
        if let Some(__ifengine_tmp_idx) = __ifengine_page_state.get_mask_last(#key_tokens) {
            #[allow(unreachable_code)]
            __ifengine_page_state.push(
                ifengine::view::Object::Paragraph(
                    match __ifengine_tmp_idx {
                        #(#index_arms),*,
                        _ => unreachable!(),
                    }
                )
            );
            true
        } else {
            __ifengine_page_state.push(
                ifengine::view::Object::Choice(
                    #key_tokens,
                    vec![
                    #(#lines),*
                    ]
                )
            );
            false
        }
    };

    expanded.into()
}

/// Execute a set of conditional expressions based on user-selected choices.
///
/// Each arm has the form `Choice => Expr`. If a choice was selected, its
/// corresponding expression (the RHS) is executed (executions occur in order), regardless of whether
/// the choice's key (the LHS) is currently visible.
///
/// Each LHS key is a [`ifengine::elements::ChoiceVariant`], dictating its visibility.
/// Any type that implements `Into<`[`Line`](ifengine::view::Line)`>` will coerce to `Choice::Once`.
/// Any `Option<Into<Line>>` will coerce to `Choice::None` or `Choice::Always`.
///
/// The return type is a [bool; n] representing which of the options were hidden (NOT displayed).
///
/// The following example permits you to pass once you have chosen 2 party members and checked the special event.
/// ```rust
///  if mchoice! {
///     s.c1.name.is_empty().then_some(link!("member_1_choice_1", _oracle_1)),
///     s.c1.name.is_empty().then_some(link!("member_1_choice_2", _oracle_2)),
///     s.c2.name.is_empty().then_some(link!("member_2_choice_1", _walker_1)),
///     s.c2.name.is_empty().then_some(link!("member_2_choice_2", _walker_2)),
///     (!s.part1.seen.contains("special_event")).then_some(link!("special_event", _interpreter_2))
///  }.all() {
///     GOTO!(p6)
///  }
/// ```

#[proc_macro]
pub fn mchoice(input: TokenStream) -> TokenStream {
    let ChoiceInput { maybe_key, arms } = syn::parse_macro_input!(input as ChoiceInput);

    let key = maybe_key.into_tokens();

    let arm_blocks: Vec<_> = arms
        .iter()
        .enumerate()
        .map(|(i, LineArm { line, block })| {
            let i = i as u8;

            let block_tokens = match block {
                Some(b) => quote! { #b },
                None => quote! {},
            };

            quote! {
                if (__ifengine_tmp_mask & (1u64 << #i)) != 0 {
                    #block_tokens
                }
                if let Some(l) = ifengine::elements::ChoiceVariant::from(#line)
                .as_line((__ifengine_tmp_mask & (1u64 << #i)) != 0)
                {
                    __ifengine_tmp_lines.push((#i, l));
                    __ifengine_visible_mask[#i as usize] = false;
                }
            }
        })
        .collect::<Vec<_>>();

    let n = arms.len();

    let expanded = quote! {
        {
            let __ifengine_tmp_mask = __ifengine_page_state.get(#key).unwrap_or(0u64);
            let mut __ifengine_tmp_lines = Vec::new();
            let mut __ifengine_visible_mask = [true; #n];

            #(#arm_blocks)*

            if ! __ifengine_tmp_lines.is_empty() {
                __ifengine_page_state.push(
                    ifengine::view::Object::Choice(#key, __ifengine_tmp_lines)
                );
            }

            __ifengine_visible_mask
        }
    };

    expanded.into()
}

/// Executes code for a set of selectable choices. Prefer to use [`dchoice`] for brevity.
///
/// # Overview
/// This macro displays list of choices, and registers a corresponding handler
/// for each selection. The handler is specified as a `match` expression, where
/// each arm corresponds to a choice and contains the code to execute when
/// that choice is selected. Unlike the other choice elements ([`choice`], [`mchoice`]),
/// the conditional expression is evaluated only the first time it's choice is selected.
/// The intent is that the arms are used to set values for the user's custom [`ifengine::core::GameContext`].
///
/// # Arguments
/// - [`MaybeKey`] (Optional)
/// - **Choices list**: A `Vec<(Id, Line)>` representing the selectable options. The Id can either be a [#repr(u8)] Unit Enum or a pure u8.
/// - **Handler**: A `match` statement handling each choice.
///
/// # Match statement
/// The match token of the match statement should be given with your custom enum type, or not given if you identify your choices with pure u8's.
///
/// # Additional
/// A [`MaybeKey`] can be specified in the first argument:
///   When a choice is clicked, it sets the value of its key to its id (cast as a u8) in [`PageState`].
///   When the page is next rendered, this value is removed, and the corresponding match arm is run.
///   It is discouraged to specify this: by default, it will be automatically generated.
///
/// # Example
/// ```rust
/// let choices = vec![
///     (0, line!("A")),
///     (1, line!("B")),
///     (2, line!("C")),
/// ];
///
/// if let Some(x) = dynamic_choice!(choices) {
///     match x {
///         0 => "A clicked",
///         1 => "B clicked",
///         2 => "C clicked",
///     }
/// }
/// ```
///
/// It is also possible to use unit enums:
/// ```rust
/// #[derive(Clone, Copy)]
/// #[repr(u8)]
/// enum DChoices { A, B, C }
///
/// let choices = vec![
///     (DChoices::A, line!("A")),
///     (DChoices::B, line!("B")),
///     (DChoices::C, line!("C")),
/// ];
///
/// if let Some(x) = dynamic_choice!(choices) {
///     match x {
///         DChoices::A => "A clicked",
///         DChoices::B => "B clicked",
///         DChoices::C => "C clicked",
///     }
/// }
/// ```

#[proc_macro]
pub fn dynamic_choice(input: TokenStream) -> TokenStream {
    let KeyExpr { maybe_key, expr } = syn::parse_macro_input!(input as KeyExpr);
    let key_tokens = maybe_key.into_tokens();

    let expanded = quote! {
        {
            // Push the DynamicChoice object
            __ifengine_page_state.push(ifengine::view::Object::Choice(
                #key_tokens,
                #expr
                .into_iter()
                .map(|(t, l)| (t as u8, ifengine::view::Line::from(l)))
                .collect()
            ));

            __ifengine_page_state.remove_mask_last(#key_tokens).map(|x|
                unsafe { std::mem::transmute::<u8, _>(x) }
            )
        }
    };

    expanded.into()
}

struct DChoicesInput {
    pub maybe_key: MaybeKey,
    pub expr: Expr,
    pub arms: Vec<Arm>,
}

impl Parse for DChoicesInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let KeyExpr { maybe_key, expr } = input.parse()?;

        if !input.is_empty() {
            input.parse::<Token![,]>()?;
        }

        let mut arms = Vec::new();
        while !input.is_empty() {
            arms.push(input.parse::<Arm>()?);
        }

        Ok(DChoicesInput {
            maybe_key,
            expr,
            arms,
        })
    }
}

/// A version of [`dynamic_choice`] with slightly abbreviated syntax.
/// It can be a bit trickier to use this if your list is fully dynamic,
/// but the flexibility of match statements should be sufficient for any purpose.
/// For example, if you have pairs of (handler, choice), you can simply them and use
/// `c => handlers[c]` as your arm.
///
/// # Example
/// ```rust
/// let choices = vec![
///     line!("A"),
///     line!("B"),
///     line!("C"),
/// ];
/// dchoice! { choices,
///     0 => "A clicked",
///     1 => "B clicked",
///     2 => "C clicked",
/// }
/// ```
#[proc_macro]
pub fn dchoice(input: TokenStream) -> TokenStream {
    let DChoicesInput {
        maybe_key,
        expr,
        arms,
    } = parse_macro_input!(input as DChoicesInput);

    let key_tokens = maybe_key.into_tokens();

    let has_wildcard = arms.iter().any(|arm| matches!(arm.pat, syn::Pat::Wild(_)));
    let catch_all = if has_wildcard {
        quote! {}
    } else {
        quote! { _ => {} }
    };
    let match_block = if arms.is_empty() {
        quote! {}
    } else {
        quote! {
            if let Some(__ifengine_id) = __ifengine_page_state.remove_mask_last(#key_tokens) {
                match __ifengine_id as usize {
                    #(#arms)*
                    #catch_all
                }
            }
        }
    };

    let expanded = quote! {
        {
            __ifengine_page_state.push(ifengine::view::Object::Choice(
                #key_tokens,
                #expr
                .iter()
                .enumerate()
                .map(|(i, l)| (i as u8, ifengine::view::Line::from(l.clone())))
                .collect()
            ));

            if let Some(__ifengine_id) = __ifengine_page_state.remove_mask_last(#key_tokens) {
                #match_block
            }
        }
    };

    expanded.into()
}
/// Create a paragraph with interactive elements from a string.
///
/// Interactive text sections are automatically added from text delimited by [[ and ]] (Also see: [`mparagraph`]).
/// The return type is the value of whichever text token that was clicked.
///
/// # Syntax
/// ```text
/// dparagraph!(maybe_key, expr1, expr2, ..., exprN)
///
/// # Additional
/// Text is trimmed
/// Multiple inputs are accepted, and produce multiple paragraphs
/// The interactive elements must not change between renders.
#[proc_macro]
pub fn dparagraph(input: TokenStream) -> TokenStream {
    let KeyExprs { maybe_key, exprs } = syn::parse_macro_input!(input as KeyExprs);

    let key = maybe_key.into_tokens();

    let expanded = quote! {{
        let mut ret = None;

        #(
            let mut __ifengine_tmp_strings =
            ifengine::utils::split_braced(&ifengine::utils::trim_lines(&#exprs));

            if let Some(__ifengine_tmp_val) = __ifengine_page_state
            .remove(#key)
            .and_then(|k| {
                ifengine::utils::find_hash_match(__ifengine_tmp_strings.iter().step_by(2), k).cloned()
            }) {
                ret = Some(__ifengine_tmp_val);
            }

            __ifengine_page_state.push(
                ifengine::view::Object::Paragraph(
                    ifengine::view::Line::from_interleaved_actions::<false>(
                        (__ifengine_page_state.id(), #key),
                        __ifengine_tmp_strings
                    )
                )
            );
        )*

        ret
    }};

    expanded.into()
}

/// Create a paragraph with interactive elements from a string.
///
/// Interactive text sections are automatically added from text delimited by [[ and ]] (Also see: [`dparagraph`]).
/// This macro tracks and returns which of the interactive elements had been clicked since page load as a `Vec<bool>`.
///
/// # Note
/// The interactive elements must not change between renders.

#[proc_macro]
pub fn mparagraph(input: TokenStream) -> TokenStream {
    let KeyExpr { maybe_key, expr } = syn::parse_macro_input!(input as KeyExpr);

    let key = maybe_key.into_tokens();

    let expanded = quote! {{
        let strings =
        ifengine::utils::split_braced(&ifengine::utils::trim_lines(&#expr));
        let count = strings.len() / 2;

        __ifengine_page_state.push(
            ifengine::view::Object::Paragraph(
                ifengine::view::Line::from_interleaved_actions::<true>(
                    (__ifengine_page_state.id(), #key),
                    strings
                )
            )
        );

        __ifengine_page_state.get_mask::<64>(#key)[..count].to_vec()
    }};

    expanded.into()
}

// ----------------- ELEMENTS -------------------

/// Push a (Object)[ifengine::view::Object] to the current (View)[ifengine::View]
#[proc_macro]
pub fn push(input: TokenStream) -> TokenStream {
    let expr = parse_macro_input!(input as Expr);

    let expanded = quote! {
        __ifengine_page_state.push(
            #expr
        );
    };

    expanded.into()
}

struct LineArgs {
    exprs: Vec<Expr>,
    trailer: Option<LitStr>,
}

impl syn::parse::Parse for LineArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut exprs = Vec::new();
        let mut trailer = None;

        while !input.is_empty() {
            if input.peek(Token![::]) {
                let _coloncolon: Token![::] = input.parse()?;
                let lit: LitStr = input.parse()?;
                trailer = Some(lit);
                break;
            }

            exprs.push(input.parse()?);

            if input.peek(Token![,]) {
                let _ = input.parse::<Token![,]>()?;
            } else {
                break;
            }
        }

        Ok(LineArgs { exprs, trailer })
    }
}

/// Pure text element, constructed from a sequence of spans.
///
/// # Additional
/// A trailing [`ifengine::view::RenderData`] can be specified following `::`.
///
/// # Example
/// ```rust
/// text!("Hello, world!");
/// text!("Hello, ", "world!" :: "my_render_data");
/// ```
#[proc_macro]
pub fn text(input: TokenStream) -> TokenStream {
    let LineArgs { exprs, trailer } = syn::parse_macro_input!(input as LineArgs);

    let string_expr = match trailer {
        Some(s) => quote!(#s),
        None => quote!(""),
    };

    let expanded = quote! {
        __ifengine_page_state.push(
            ifengine::view::Object::Text(
                ifengine::view::Line::from_spans(
                    vec![#(#exprs.into()),*]
                ),
                #string_expr
            )
        );
    };

    TokenStream::from(expanded)
}

/// A sequence of text elements. See [`text`].
///
/// # Additional
/// A trailing [`ifengine::view::RenderData`] can be specified following `::`.
///
/// Note that text and choice styling may differ depending on the renderer, particularly with respect to vertical item spacing.
/// When you want to display choices without handling their effects seperately from actions attached to their spans, prefer [`dchoice`].
///
/// # Example
/// ```rust
/// texts!("Line 1", "Line 2");
/// ```
#[proc_macro]
pub fn texts(input: TokenStream) -> TokenStream {
    let LineArgs { exprs, trailer } = syn::parse_macro_input!(input as LineArgs);

    let string_expr = match trailer {
        Some(s) => quote!(#s),
        None => quote!(""),
    };

    let expanded = quote! {
        #(
            __ifengine_page_state.push(
                ifengine::view::Object::Text(
                    ifengine::view::Line::from(#exprs),
                    #string_expr
                )
            );
        )*
    };

    TokenStream::from(expanded)
}

/// Create a paragraph from a sequence of spans.
///
/// # Example
/// ```rust
/// paragraph!(span1, span2, span3);
/// ```
#[proc_macro]
pub fn paragraph(input: TokenStream) -> TokenStream {
    let exprs_parsed = parse_macro_input!(input with Punctuated<Expr, Token![,]>::parse_terminated);
    let exprs: Vec<Expr> = exprs_parsed.into_iter().collect();

    let expanded = quote! {
        __ifengine_page_state.push(
            ifengine::view::Object::Paragraph(
                ifengine::view::Line::from_spans(vec![#(ifengine::view::Span::from_lingual(#exprs)),*])
            )
        );
    };

    TokenStream::from(expanded)
}

/// Shorthand for creating multiple paragraphs from a sequence of [`crate::view::Line`]'s.
///
/// # Example
/// ```rust
/// paragraphs!(line1, line2, line3);
/// ```
///
/// # Additional
/// Any type implementing `Into<Line>` is accepted.
#[proc_macro]
pub fn paragraphs(input: TokenStream) -> TokenStream {
    use quote::quote;
    use syn::punctuated::Punctuated;
    use syn::{Expr, Token, parse_macro_input};

    let exprs_parsed = parse_macro_input!(input with Punctuated<Expr, Token![,]>::parse_terminated);
    let exprs: Vec<Expr> = exprs_parsed.into_iter().collect();

    let expanded = quote! {
        #(
            __ifengine_page_state.push(
                ifengine::view::Object::Paragraph(
                    ifengine::view::Line::from_lingual(#exprs)
                )
            );
        )*
    };

    TokenStream::from(expanded)
}

/// Push an image from a string literal.
///
/// # Example
/// ```rust
/// img!("assets/logo.png");
/// img!("https://example.com/logo.png", (100, 50));
/// ```
#[proc_macro]
pub fn img(input: TokenStream) -> TokenStream {
    use quote::quote;
    use syn::punctuated::Punctuated;
    use syn::{Expr, Lit, Token, parse_macro_input};

    let exprs_parsed = parse_macro_input!(input with Punctuated<Expr, Token![,]>::parse_terminated);
    let exprs: Vec<&Expr> = exprs_parsed.iter().collect();

    let (path_expr, size_expr) = match exprs.len() {
        1 => (exprs[0], None),
        2 => (exprs[0], Some(exprs[1])),
        _ => {
            return syn::Error::new_spanned(exprs_parsed, "image! macro expects 1 or 2 arguments")
                .to_compile_error()
                .into();
        }
    };

    let image_tokens = if let Expr::Lit(lit) = path_expr
        && let Lit::Str(s) = &lit.lit
    {
        let path = s.value();
        if path.starts_with("http://") || path.starts_with("https://") {
            if let Some(size) = size_expr {
                quote! { ifengine::view::Image::new_url(#path).with_size(#size) }
            } else {
                quote! { ifengine::view::Image::new_url(#path) }
            }
        } else {
            if let Some(size) = size_expr {
                quote! { ifengine::view::Image::new_local(#path, include_bytes!(#path)).with_size(#size) }
            } else {
                quote! { ifengine::view::Image::new_local(#path, include_bytes!(#path)) }
            }
        }
    } else {
        return syn::Error::new_spanned(path_expr, "expected string literal")
            .to_compile_error()
            .into();
    };

    let expanded = quote! {
        __ifengine_page_state.push(ifengine::view::Object::Image(#image_tokens));
    };

    TokenStream::from(expanded)
}

/// Markdown heading.
///
/// # Example
/// ```rust
/// h!("Title", 2)
/// ```
#[proc_macro]
pub fn h(input: TokenStream) -> TokenStream {
    let exprs_parsed = parse_macro_input!(input with Punctuated<Expr, Token![,]>::parse_terminated);
    let exprs: Vec<&Expr> = exprs_parsed.iter().collect();

    if exprs.len() != 2 {
        return syn::Error::new_spanned(
            exprs_parsed,
            "macro expects exactly 2 arguments: text and level",
        )
        .to_compile_error()
        .into();
    }

    let text = exprs[0];
    let level = exprs[1];

    let expanded = quote! {
        __ifengine_page_state.push(
            ifengine::view::Object::Heading(ifengine::view::Span::from_lingual(#text), #level)
        );
    };

    TokenStream::from(expanded)
}

/// Horizontal rule (`<hr/>`).
///
/// # Example
/// ```rust
/// hr!()
/// ```
#[proc_macro]
pub fn hr(_input: TokenStream) -> TokenStream {
    let expanded = quote! {
        __ifengine_page_state.push(ifengine::view::Object::Break);
    };

    TokenStream::from(expanded)
}

// --------------- ALTS -------------------------

#[derive(Clone)]
enum AltVariant {
    Stop,
    Shuffle,
    Cycle,
}

impl Default for AltVariant {
    fn default() -> Self {
        AltVariant::Stop
    }
}

impl Parse for AltVariant {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let ident: syn::Ident = input.parse()?;
        match ident.to_string().as_str() {
            "Stop" => Ok(AltVariant::Stop),
            "Shuffle" => Ok(AltVariant::Shuffle),
            "Cycle" => Ok(AltVariant::Cycle),
            _ => Err(syn::Error::new(
                ident.span(),
                "expected AltVariant: Stop | Shuffle | Cycle",
            )),
        }
    }
}

struct AltsInput {
    maybe_key: MaybeKey,
    list: Vec<Expr>,
    variant: Option<AltVariant>,
}

impl Parse for AltsInput {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let content;
        syn::bracketed!(content in input);

        let maybe_key = input.parse()?;

        let mut list = Vec::new();
        while !content.is_empty() {
            list.push(content.parse()?);
            if content.peek(Token![,]) {
                let _: Token![,] = content.parse()?;
            }
        }

        // optional variant
        let variant = if !input.is_empty() {
            input.parse::<Token![,]>()?;
            Some(input.parse()?)
        } else {
            None
        };

        Ok(Self {
            maybe_key,
            list,
            variant,
        })
    }
}

/// Cycle between multiple alternative spans on click.
///
/// ## Behavior
///
/// - The first span is shown when no prior state exists.
/// - The active index is stored in page state under the provided key.
///
/// ## Variants
///
/// ### `stop` (default)
/// Advances until the last span, then stops:
///
/// ```text
/// A → B → C (stops)
/// ```
///
/// ### `cycle`
/// Advances to the next span on activation, wrapping around:
///
/// ```text
/// A → B → C → A → …
/// ```
///
/// ### `shuffle`
/// Chooses a random span each time, avoiding immediate repetition.
/// The internal state uses the low bit as a regeneration flag.
///
/// ## Syntax
///
/// ```ignore
/// alts!(key?, variant?, [expr, expr, ...])
/// ```
///
/// - `key` (optional): Explicit state key
/// - `variant` (optional): `cycle`, `stop`, or `shuffle`
/// - `expr`: Any value convertible into a `Span`
///
/// ## Examples
///
/// Basic cycling:
///
/// ```ignore
/// alts!([
///     "Look around",
///     "Open the door",
///     "Wait",
/// ])
/// ```
///
/// With an explicit key and variant:
///
/// ```ignore
/// alts!(
///     (5),
///     shuffle,
///     [
///         "Attack",
///         "Defend",
///         "Flee",
///     ]
/// )
/// ```
///
/// ## Notes
///
/// - State is updated via [`ifengine::Action::Inc`] or [`ifengine::Action::Set`].
/// - Random selection uses the page state's RNG.
/// - The macro expands to an expression producing a `Span`.
/// - Shuffle and Cycle are hidden during simulation.
#[proc_macro]
pub fn alts(input: TokenStream) -> TokenStream {
    let AltsInput {
        maybe_key,
        list,
        variant,
    } = parse_macro_input!(input as AltsInput);

    let key = maybe_key.into_tokens();

    let variant = variant.unwrap_or_default();
    let list_init = quote! { &[ #(#list),* ] };

    let expanded = match variant {
        AltVariant::Stop => {
            quote! {{
                let alts = #list_init;

                if let Some(idx) = __ifengine_page_state.get(#key) {
                    ifengine::view::Span::from(
                        alts[(idx as usize + 1).min(alts.len() - 1)]
                    )
                    .with_action(ifengine::Action::Inc((__ifengine_page_state.id(), #key)))
                } else {
                    ifengine::view::Span::from(
                        alts[0]
                    )
                    .with_action(ifengine::Action::Inc((__ifengine_page_state.id(), #key)))
                }
            }}
        }

        AltVariant::Shuffle => {
            quote! {{
                let alts = #list_init;

                // Determine tmp index
                let idx = if let Some(prev) = __ifengine_page_state.get(#key) {
                    if prev & 1 == 0 {
                        (prev as usize) >> 1
                    } else {
                        // regenerate, excluding previous index
                        let new_idx = __ifengine_page_state.rand(alts.len(), &[(prev as usize) >> 1]);
                        __ifengine_page_state.insert(#key, (new_idx as u64) << 1);
                        new_idx
                    }
                } else {
                    let new_idx = __ifengine_page_state.rand(alts.len(), &[]);
                    __ifengine_page_state.insert(#key, (new_idx as u64) << 1);
                    new_idx
                } ;

                // Use it and store back with last bit set
                ifengine::view::Span::from(alts[idx])
                .with_action(ifengine::Action::Set(
                    (__ifengine_page_state.id(), #key),
                    ((idx as u64) << 1) + 1
                ))
                .no_sim()
            }}
        }

        AltVariant::Cycle => {
            quote! {{
                let alts = #list_init;

                if let Some(idx) = __ifengine_page_state.get(#key) {
                    ifengine::view::Span::from(
                        alts[(idx as usize) % alts.len()]
                    )
                    .with_action(ifengine::Action::Inc((__ifengine_page_state.id(), #key)))
                    .no_sim()
                } else {
                    ifengine::view::Span::from(
                        alts[0]
                    )
                    .with_action(ifengine::Action::Inc((__ifengine_page_state.id(), #key)))
                    .no_sim()
                }
            }}
        }
    };

    expanded.into()
}
//

// ------------- SPANS/CLOSURES ----------------------

struct CountInput {
    maybe_key: MaybeKey,
    closure: ExprClosure,
}

impl Parse for CountInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let maybe_key = input.parse()?;
        let closure = input.parse()?;

        Ok(CountInput { maybe_key, closure })
    }
}

/// Use a closure to compute a span based on how many times the span has been clicked.
///
/// # Syntax
/// ```rust
/// let span_count = read_key!(6); // Can be called before
/// let span = count!((6), |val| "span");
/// ```
///
/// # Arguments
/// - [`MaybeKey`]
/// - `closure`: A closure taking the current value and returning a `Span`.
#[proc_macro]
pub fn count(input: TokenStream) -> TokenStream {
    let CountInput { maybe_key, closure } = syn::parse_macro_input!(input as CountInput);
    let key = maybe_key.into_tokens();

    let expanded = quote! {{
        ifengine::view::Span::from(
            (#closure)(__ifengine_page_state.get(#key).unwrap_or_default())
        )
        .with_action(ifengine::Action::Inc((__ifengine_page_state.id(), #key)))
        .no_sim()
    }};

    expanded.into()
}

struct ClickInput {
    maybe_key: MaybeKey,
    expr: Expr,
    block: Expr,
}

impl Parse for ClickInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let maybe_key = input.parse()?;

        let expr: Expr = input.parse()?;

        let block = if input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
            input.parse::<Expr>()?
        } else {
            syn::parse_quote!({})
        };

        Ok(ClickInput {
            maybe_key,
            expr,
            block,
        })
    }
}

/// Run code on click.
///
/// # Syntax
/// ```rust
/// p!(click!(span, expr ))
/// ```
///
/// # Arguments
/// - [`MaybeKey`]
/// - `span`: The element to display. The link style is automatically applied.
/// - `block`: Executed exactly once whenever the key is clicked.
///
/// # Note
/// The handler is evaluated before the span is.
#[proc_macro]
pub fn click(input: TokenStream) -> TokenStream {
    let ClickInput {
        maybe_key,
        expr,
        block,
    } = syn::parse_macro_input!(input as ClickInput);
    let key = maybe_key.into_tokens();

    let expanded = quote! {{
        if __ifengine_page_state.was_zero(#key) {
            let _ = #block;
        };

        let span = ifengine::view::Span::from(
            #expr
        )
        .with_action(ifengine::Action::Inc((__ifengine_page_state.id(), #key)))
        .as_link();

        // sim the handler once
        if __ifengine_page_state.get(#key).is_some() {
            span.no_sim()
        } else {
            span
        }
    }};

    expanded.into()
}

/// Run a function only once when the page is first loaded.
///
/// # Syntax
/// ```rust
/// fresh!(|| { /* code */ })
/// ```
#[proc_macro]
pub fn fresh(input: TokenStream) -> TokenStream {
    let closure = parse_macro_input!(input as ExprClosure);

    let expanded = quote! {{
        if __ifengine_page_state.fresh() {
            (#closure)();
        }
    }};

    expanded.into()
}

// -------------- SPANS -------------------------

/// Create a link [`Span`] that navigates backward.
///
/// - `$e`: Display text.
/// - `$n`: Optional number of steps to go back (defaults to 1).
///
/// # Additional
/// This option will be hidden during simulation if no number is specified
#[proc_macro]
pub fn back(input: TokenStream) -> TokenStream {
    let ExprAndOptional { expr, n } = parse_macro_input!(input as ExprAndOptional);

    let expanded = if let Some(n_expr) = n {
        quote! {
            ifengine::view::Span::from(#expr)
            .as_link()
            .with_action(ifengine::Action::Back(#n_expr))
        }
    } else {
        quote! {
            ifengine::view::Span::from(#expr)
            .as_link()
            .with_action(ifengine::Action::Back(1))
            .no_sim()
        }
    };

    TokenStream::from(expanded)
}

/// Immediately yield a [`Response::View`] with the current [`View`].
///
/// This returns `!`, exiting the current function.
#[proc_macro]
#[allow(non_snake_case)]
pub fn r#YIELD(_input: TokenStream) -> TokenStream {
    let expanded = quote! {
        return __ifengine_page_state.into_response()
    };
    expanded.into()
}

// ------------ KEY OPERATIONS -------------------
/// Read the value of a key of the internal [`PageState`]
///
/// Elements push to the view in the order they are called.
/// This can be used to query their state out of order.
///
/// Beware that the implementation details of the internal page state that these keys index is internal and should not be relied on!
///
/// # Example
/// ```rust
/// let value = read_key!(my_key);
/// ```
#[proc_macro]
pub fn read_key(input: TokenStream) -> TokenStream {
    let expr = syn::parse_macro_input!(input as syn::Expr);

    let expanded = quote! {
        __ifengine_page_state.get(#expr)
    };

    expanded.into()
}

/// Read a key as a bitmask. See [`read_key`].
///
/// # Example
/// ```rust
/// let mask = read_key_mask!(my_key); // [bool; 64]
/// let mask = read_key_mask!(my_key, 5); // [bool; 5]
/// ```
#[proc_macro]
pub fn read_key_mask(input: TokenStream) -> TokenStream {
    let ExprAndOptional { expr: key, n } = syn::parse_macro_input!(input as ExprAndOptional);

    let n = n.unwrap_or_else(|| syn::parse_quote!(64));

    quote! {
        __ifengine_page_state.get_mask::<#n>(#key)
    }
    .into()
}

/// Set a key to a value. See [`read_key`].
///
/// # Example
/// ```rust
/// set_key!(my_key, 42);
/// ```
#[proc_macro]
pub fn set_key(input: TokenStream) -> TokenStream {
    let expr = syn::parse_macro_input!(input as syn::Expr);

    let expanded = quote! {
        __ifengine_page_state.insert(#expr.0, #expr.1)
    };

    expanded.into()
}

/// Set individual bits of a key to true. See [`read_key_mask`].
///
/// # Example
/// ```rust
/// set_key_mask!(my_key, 0, 2, 4);
/// ```
#[proc_macro]
pub fn set_key_mask(input: TokenStream) -> TokenStream {
    use syn::{Expr, Token, parse::Parser, punctuated::Punctuated};

    let parts = match Punctuated::<Expr, Token![,]>::parse_terminated.parse(input) {
        Ok(parts) => parts,
        Err(e) => return e.to_compile_error().into(),
    };

    let mut iter = parts.iter();
    let key = if let Some(key) = iter.next() {
        key
    } else {
        return syn::Error::new_spanned(parts, "expected key")
            .to_compile_error()
            .into();
    };
    let bits: Vec<&Expr> = iter.collect();

    let mut mask = 0u64;
    for expr in &bits {
        if let Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Int(i),
            ..
        }) = expr
        {
            match i.base10_parse::<usize>() {
                Ok(bit) => mask |= 1u64 << bit,
                Err(_) => {
                    return syn::Error::new_spanned(i, "failed to parse bit position")
                        .to_compile_error()
                        .into();
                }
            }
        } else {
            return syn::Error::new_spanned(expr, "bit positions must be integer literals")
                .to_compile_error()
                .into();
        }
    }

    let expanded = quote! {
        {
            let old = __ifengine_page_state.get(#key).unwrap_or(0u64);
            __ifengine_page_state.insert(#key, old | #mask);
        }
    };

    expanded.into()
}

/// Clear individual bits of a key. See [`read_key_mask`].
///
/// # Example
/// ```rust
/// unset_key_mask!(my_key, 1, 3);
/// ```
#[proc_macro]
pub fn unset_key_mask(input: TokenStream) -> TokenStream {
    use syn::{Expr, Token, parse::Parser, punctuated::Punctuated};

    let parts = match Punctuated::<Expr, Token![,]>::parse_terminated.parse(input) {
        Ok(parts) => parts,
        Err(e) => return e.to_compile_error().into(),
    };

    let mut iter = parts.iter();
    let key = if let Some(key) = iter.next() {
        key
    } else {
        return syn::Error::new_spanned(parts, "expected key")
            .to_compile_error()
            .into();
    };
    let bits: Vec<&Expr> = iter.collect();

    let mut mask = 0u64;
    for expr in &bits {
        if let Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Int(i),
            ..
        }) = expr
        {
            match i.base10_parse::<usize>() {
                Ok(bit) => mask |= 1u64 << bit,
                Err(_) => {
                    return syn::Error::new_spanned(i, "failed to parse bit position")
                        .to_compile_error()
                        .into();
                }
            }
        } else {
            return syn::Error::new_spanned(expr, "bit positions must be integer literals")
                .to_compile_error()
                .into();
        }
    }

    let expanded = quote! {
        {
            let old = __ifengine_page_state.get(#key).unwrap_or(0u64);
            __ifengine_page_state.insert(#key, old & !#mask);
        }
    };

    expanded.into()
}

/// Increment the value of a key. See [`read_key`].
///
/// # Example
/// ```rust
/// inc_key!(my_key);
/// ```
#[proc_macro]
pub fn inc_key(input: TokenStream) -> TokenStream {
    let expr = syn::parse_macro_input!(input as syn::Expr);

    let expanded = quote! {
        {
            let k = #expr;
            let v = __ifengine_page_state.get(k).unwrap_or(0);
            __ifengine_page_state.insert(k, v.wrapping_add(1));
        }
    };

    expanded.into()
}

/// Reset (remove) a key from state. See [`read_key`].
///
/// # Example
/// ```rust
/// reset_key!(my_key);
/// ```
#[proc_macro]
pub fn reset_key(input: TokenStream) -> TokenStream {
    let expr = syn::parse_macro_input!(input as syn::Expr);

    let expanded = quote! {
        __ifengine_page_state.remove(#expr)
    };

    expanded.into()
}

// ------------ TAGS ------------------

// note: this doesn't work
/// [Tags](crate::core::GameTags) the current page.
///
/// Pass `Sticky` to persist the tag between pages.
///
/// # Examples
///
/// ```rust
/// tag!(my_value);          // non-sticky tag
/// tag!(my_value, Sticky);  // sticky tag
/// tag!(my_value, Once);    // apply only once
/// ```
#[proc_macro]
pub fn tag(input: TokenStream) -> TokenStream {
    use quote::quote;
    use syn::parse::{Parse, ParseStream, Result};
    use syn::{Expr, Ident, Token, parse_macro_input};

    struct TagInput {
        expr: Expr,
        mode: Option<Ident>,
    }

    impl Parse for TagInput {
        fn parse(input: ParseStream) -> Result<Self> {
            let expr: Expr = input.parse()?;
            let mode: Option<Ident> = if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
                Some(input.parse()?)
            } else if !input.is_empty() {
                Some(input.parse()?)
            } else {
                None
            };
            Ok(TagInput { expr, mode })
        }
    }

    let TagInput { expr, mode } = parse_macro_input!(input as TagInput);

    let sticky = match mode {
        Some(id) => match id.to_string().as_str() {
            "Sticky" => true,
            "Once" => false,
            _ => {
                return syn::Error::new_spanned(&id, "Expected `Sticky` or `Once`")
                    .to_compile_error()
                    .into();
            }
        },
        None => false,
    };

    let expanded = quote! {
        __ifengine_page_state.tag(#expr, #sticky)
    };

    expanded.into()
}

/// Removes a [tag](`crate::core::GameTags`)
#[proc_macro]
pub fn untag(input: TokenStream) -> TokenStream {
    let expr = syn::parse_macro_input!(input as syn::Expr);

    let expanded = quote! {
        __ifengine_page_state.untag(#expr)
    };

    expanded.into()
}

/// Returns whether the current function is running in a [`crate::run::Simulation`].
#[proc_macro]
pub fn in_sim(_: TokenStream) -> TokenStream {
    let expanded = quote! {
        __ifengine_page_state.simulating
    };

    expanded.into()
}

// ------------ UTILS ------------------

/// Debug display the current [`PageState`]
#[proc_macro]
pub fn page_dbg(_input: TokenStream) -> TokenStream {
    let expanded = quote! {
        // #[cfg(debug_assertions)]
        dbg!(&__ifengine_page_state)
    };
    expanded.into()
}

/// Debug display the current view
#[proc_macro]
pub fn view_dbg(_input: TokenStream) -> TokenStream {
    let expanded = quote! {
        dbg!(&__ifengine_page_state.view)
    };
    expanded.into()
}