ixa 2.0.0-beta2.3

A framework for building agent-based models
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
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
/*!

Macros for implementing properties.

# [`define_property!`][macro@crate::define_property]

For the most common cases, use the [`define_property!`][macro@crate::define_property] macro. This macro defines a struct or enum
with the standard derives required by the [`Property`][crate::entity::property::Property] trait and implements [`Property`][crate::entity::property::Property] (via
[`impl_property!`][macro@crate::impl_property]) for you.

```rust,ignore
define_property!(struct Age(u8), Person);
define_property!(struct Location(City, State), Person);
define_property!(
    enum InfectionStatus {
        Susceptible,
        Infectious,
        Recovered,
    },
    Person,
    default_const = InfectionStatus::Susceptible
);
```

Notice the convenient `default_const = <default_value>` keyword argument that allows you to
define a compile-time constant default value for the property. This is an optional argument.
If it is omitted, a value for the property must be supplied upon entity creation.

The primary advantage of using this macro is that it automatically derives the list of traits every
[`Property`][crate::entity::property::Property] needs to derive for you. You don't have to remember them. You also get a cute syntax for
specifying the default value, but it's not much harder to specify default values using other macros.

If you need the macro to generate `Eq` and/or `Hash` manually instead of deriving them, use the
optional `impl_eq_hash = ...` argument with one of the following values: `Eq`, `Hash`, `both`, or
`neither`.

Notice you need to use the `struct` or `enum` keywords, but you don't need to
specify the visibility. A `pub` visibility is added automatically to the struct
and to inner fields of tuple structs in the expansion.

# [`impl_property!`][macro@crate::impl_property]

You can implement [`Property`][crate::entity::property::Property] for existing types using the
[`impl_property!`][macro@crate::impl_property] macro. This macro defines the
[`Property`][crate::entity::property::Property] trait implementation for you but doesn't take care
of the `#[derive(..)]` boilerplate, so you have to remember to derive or implement the traits
required by [`AnyProperty`][crate::entity::property::AnyProperty] for your type: `Copy`, `Clone`,
`Debug`, `PartialEq`, `Eq`, and `Hash`.

Some examples:

```rust,ignore
define_entity!(Person);

// The `define_property!` automatically adds `pub` visibility to the struct and its tuple fields. If
// we want to restrict the visibility of our `Property` type, we can use the `impl_property!` macro
// instead. The only catch is, we have to remember to derive or implement the traits required by
// `AnyProperty`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
struct Age(pub u8);
impl_property!(Age, Person);

// Here we derive `Default`, which also requires an attribute on one
// of the variants. (`Property` has its own independent mechanism for
// assigning default values for entities unrelated to the `Default` trait.)
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
enum InfectionStatus {
    #[default]
    Susceptible,
    Infected,
    Recovered,
}
// We also specify the default value explicitly for entities.
impl_property!(InfectionStatus, Person, default_const = InfectionStatus::Susceptible);

// Exactly equivalent to
//    `define_property!(struct Vaccinated(pub bool), Person, default_const = Vaccinated(false));`
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Vaccinated(pub bool);
impl_property!(Vaccinated, Person, default_const = Vaccinated(false));
```

# [`impl_property!`][macro@crate::impl_property] with options

The [`impl_property!`][macro@crate::impl_property] macro gives you much more control over the implementation of your
property type. It takes optional keyword arguments for things like the default value,
initialization strategy, and how the property is converted to a string for display.

Non-derived properties either have a default constant value for new entities
(`default_const = ...`), or a value is required to be provided for new entities
(no `default_const`).

```rust,ignore
impl_property!(
    InfectionStatus,
    Person,
    default_const = InfectionStatus::Susceptible,
    display_impl = |v| format!("status: {v:?}")
);
```

## Use case: `Property::CanonicalValue` different from `Self`

The `Property::CanonicalValue` type is used to store the property value in
the index. If the property type is different from the value type, you can
specify a custom canonical type using the `canonical_value` parameter, but
you also must provide a conversion function to and from the canonical type.
Because the canonical value participates directly in index hashing and equality,
it must satisfy [`AnyProperty`][crate::entity::property::AnyProperty].

```rust,ignore
define_entity!(WeatherStation);

#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct DegreesFahrenheit(pub f64);

#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct DegreesCelsius(pub f64);

// Custom canonical type
impl_property!(
    DegreesFahrenheit,
    WeatherStation,
    canonical_value = DegreesCelsius,
    make_canonical = |s: &DegreesFahrenheit| DegreesCelsius((s.0 - 32.0) * 5.0 / 9.0),
    make_uncanonical = |v: DegreesCelsius| DegreesFahrenheit(v.0 * 9.0 / 5.0 + 32.0),
    display_impl = |v| format!("{:.1} °C", v.0)
);
```

*/

/// Defines a `struct` or `enum` with a standard set of derives and automatically invokes
/// [`impl_property!`][macro@crate::impl_property] for it. This macro provides a concise shorthand for defining
/// simple property types that follow the same derive and implementation pattern.
///
/// The macro supports the following forms:
///
/// ### 1. Tuple Structs
/// ```rust
/// # use ixa::{define_entity, define_property};
/// # define_entity!(Person);
/// define_property!(struct Age(u8), Person);
/// ```
/// Expands to:
/// ```rust
/// # use ixa::{impl_property, define_entity};
/// # define_entity!(Person);
/// #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize)]
/// pub struct Age(u8);
/// impl_property!(Age, Person);
/// ```
///
/// You can define multiple tuple fields:
/// ```rust,ignore
/// define_property!(struct Location(City, State), Person);
/// ```
///
/// ### 2. Named-field Structs
/// ```rust
/// # use ixa::{define_property, define_entity};
/// # define_entity!(Person);
/// define_property!(struct Coordinates { x: i32, y: i32 }, Person);
/// ```
/// Expands to:
/// ```rust
/// # use ixa::{impl_property, define_entity};
/// # define_entity!(Person);
/// #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize)]
/// pub struct Coordinates { x: i32, y: i32 }
/// impl_property!(Coordinates, Person);
/// ```
///
/// ### 3. Enums
/// ```rust
/// # use ixa::{define_property, define_entity};
/// # define_entity!(Person);
/// define_property!(
///     enum InfectionStatus {
///         Susceptible,
///         Infectious,
///         Recovered,
///     },
///     Person
/// );
/// ```
/// Expands to:
/// ```rust
/// # use ixa::{impl_property, define_entity};
/// # define_entity!(Person);
/// #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize)]
/// pub enum InfectionStatus {
///     Susceptible,
///     Infectious,
///     Recovered,
/// }
/// impl_property!(InfectionStatus, Person);
/// ```
///
/// ### Notes
///
/// - By default, the generated type derives `Debug`, `PartialEq`, `Eq`, `Hash`, `Clone`, and `Copy`.
/// - Use the optional `default_const = <default_value>` argument to define a compile-time constant
///   default for the property.
/// - Use `impl_eq_hash = Eq`, `Hash`, `both`, or `neither` as the first optional argument to suppress the default
///   `Eq`/`Hash` derives and switch to generated or user-supplied implementations.
/// - Remaining optional arguments follow the same ordering as [`impl_property!`][macro@crate::impl_property].
/// - If you need a more complex type definition (e.g., generics, attributes, or non-`Copy`
///   fields), define the type manually and then call [`impl_property!`][macro@crate::impl_property] directly.
#[macro_export]
macro_rules! define_property {
    // Implementation Notes
    //
    // To implement the optional `impl_eq_hash` keyword argument, we have the following choices:
    //
    // 1. Have a single public match branch per type form with `$(, impl_eq_hash =
    //    $impl_eq_hash:ident)?`, but explicitly list all the keyword options. This option disallows
    //    the `$(, $($extra:tt)+)*` pattern for the tail.
    // 2. Have two branches per type form, one with the `impl_eq_hash = ...` keyword present and one
    //    with it absent, and use the `$(, $($extra:tt)+)*` pattern for the tail. This duplicates the
    //    number of public match arms, but it allows us to keep the keyword arguments defined in
    //    `impl_property!` instead of repeated throughout the code.
    // 3. Use a proc macro or "TT munching", both of which are more heavy weight.
    //
    // We choose the second option. Unfortunately, this doesn't completely eliminate repetition of
    // the list of keyword arguments. We still have them in the
    // `impl_derived_property!(@with_option_display_default ...)` and
    // `impl_property!(@with_option_display_default ...)` subcommands.

    (
        struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ),
        $entity:ident,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration $impl_eq_hash,
            pub struct $name(pub Option<$inner_ty>);,
            $name
        );
        $crate::impl_property!(@with_option_display_default $name, $entity $(, $($extra)*)?);
    };
    (
        struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ),
        $entity:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration ,
            pub struct $name(pub Option<$inner_ty>);,
            $name
        );
        $crate::impl_property!(@with_option_display_default $name, $entity $(, $($extra)*)?);
    };

    (
        struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ),
        $entity:ident,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration $impl_eq_hash,
            pub struct $name($(pub $field_ty),*);,
            $name
        );
        $crate::impl_property!($name, $entity $(, $($extra)*)?);
    };
    (
        struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ),
        $entity:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration ,
            pub struct $name($(pub $field_ty),*);,
            $name
        );
        $crate::impl_property!($name, $entity $(, $($extra)*)?);
    };

    (
        struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? },
        $entity:ident,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration $impl_eq_hash,
            pub struct $name { $(pub $field_name : $field_ty),* },
            $name
        );
        $crate::impl_property!($name, $entity $(, $($extra)*)?);
    };
    (
        struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? },
        $entity:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration ,
            pub struct $name { $(pub $field_name : $field_ty),* },
            $name
        );
        $crate::impl_property!($name, $entity $(, $($extra)*)?);
    };

    (
        enum $name:ident {
            $($variant:ident),* $(,)?
        },
        $entity:ident,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration $impl_eq_hash,
            pub enum $name { $($variant),* },
            $name
        );
        $crate::impl_property!($name, $entity $(, $($extra)*)?);
    };
    (
        enum $name:ident {
            $($variant:ident),* $(,)?
        },
        $entity:ident
        $(, $($extra:tt)*)?
    ) => {
        $crate::define_property!(
            @apply_property_decoration ,
            pub enum $name { $($variant),* },
            $name
        );
        $crate::impl_property!($name, $entity $(, $($extra)*)?);
    };

    // Both `define_property!` and `define_derived_property!` need to attach derives to a
    // concrete item, so the mode table lives here as a shared internal subcommand.
    (@apply_property_decoration , $item:item, $name:ident) => {
        #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize)]
        $item
    };
    (@apply_property_decoration Eq, $item:item, $name:ident) => {
        #[derive(Debug, Clone, Copy, serde::Serialize, $crate::rkyv::Archive, $crate::rkyv::Serialize)]
        #[rkyv(crate = $crate::rkyv)]
        $item
        $crate::define_property!(@apply_property_decoration_eq_impl $name);
    };
    (@apply_property_decoration Hash, $item:item, $name:ident) => {
        #[derive(Debug, Clone, Copy, serde::Serialize, $crate::rkyv::Archive, $crate::rkyv::Serialize)]
        #[rkyv(crate = $crate::rkyv)]
        $item
        $crate::define_property!(@apply_property_decoration_hash_impl $name);
    };
    (@apply_property_decoration both, $item:item, $name:ident) => {
        #[derive(Debug, Clone, Copy, serde::Serialize, $crate::rkyv::Archive, $crate::rkyv::Serialize)]
        #[rkyv(crate = $crate::rkyv)]
        $item
        $crate::define_property!(@apply_property_decoration_eq_impl $name);
        $crate::define_property!(@apply_property_decoration_hash_impl $name);
    };
    (@apply_property_decoration neither, $item:item, $name:ident) => {
        #[derive(Debug, Clone, Copy, serde::Serialize)]
        $item
    };
    (@apply_property_decoration $mode:ident, $item:item, $name:ident) => {
        compile_error!("`impl_eq_hash` must be one of `Eq`, `Hash`, `both`, or `neither`");
    };

    (@apply_property_decoration_eq_impl $name:ident) => {
        impl core::cmp::PartialEq for $name {
            fn eq(&self, other: &Self) -> bool {
                const N: usize = core::mem::size_of::<<$name as $crate::rkyv::Archive>::Archived>();

                let left = $crate::rkyv::api::high::to_bytes_in::<_, $crate::rkyv::rancor::Error>(
                    self,
                    $crate::hashing::EqualityBufferWriter::<N>::new(),
                )
                .expect("serializing left value for equality comparison failed");

                let right = $crate::rkyv::api::high::to_bytes_in::<_, $crate::rkyv::rancor::Error>(
                    other,
                    $crate::hashing::EqualityBufferWriter::<N>::new(),
                )
                .expect("serializing right value for equality comparison failed");

                left.as_written() == right.as_written()
            }
        }

        impl core::cmp::Eq for $name {}
    };
    (@apply_property_decoration_hash_impl $name:ident) => {
        impl core::hash::Hash for $name {
            fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
                $crate::rkyv::api::high::to_bytes_in::<_, $crate::rkyv::rancor::Error>(
                    self,
                    $crate::hashing::HasherWriter::new(state),
                )
                .expect("serialization failed while hashing");
            }
        }
    };

}

/// Implements the [`Property`][crate::entity::property::Property] trait for the given property type and entity.
///
/// Use this macro when you want to implement the `Property<E: Entity>` trait for a type you have declared yourself.
/// You might want to declare your own property type yourself instead of using the [`define_property!`][macro@crate::define_property] macro if
/// - you want a visibility other than `pub`
/// - you want to derive additional traits
/// - your type definition requires attribute proc-macros or other special syntax (for example, deriving
///   `Default` on an enum requires an attribute on one of the variants)
///
/// Example:
///
/// In this example, in addition to the set of derives required for all property types, we also derive the `Default`
/// trait for an enum type, which requires the proc-macro attribute `#[default]` on one of the variants.
///
/// ```rust
/// # use ixa::{impl_property, define_entity};
/// # define_entity!(Person);
/// #[derive(Default, Debug, PartialEq, Eq, Hash, Clone, Copy)]
/// pub enum InfectionStatus {
///     #[default]
///     Susceptible,
///     Infectious,
///     Recovered,
/// }
/// // We also specify that this property is assigned a default value for new entities if a value isn't provided.
/// // Here we have it coincide with `Default::default()`, but this isn't required.
/// impl_property!(InfectionStatus, Person, default_const = InfectionStatus::Susceptible);
/// ```
///
/// # Parameters
///
/// Parameters must be given in the correct order.
///
/// * `$property`: The identifier for the type implementing [`Property`][crate::entity::property::Property].
/// * `$entity`: The entity type this property is associated with.
/// * Optional parameters (each may be omitted; defaults will be used):
///   * `compute_derived_fn = <expr>` — Function used to compute derived properties. Use `define_derived_property!` or
///     `impl_derived_property!` instead of using this option directly.
///   * `default_const = <expr>` — Constant default value if the property has one; implies a non-derived property.
///   * `display_impl = <expr>` — Function converting the property value to a string; defaults to `|v| format!("{v:?}")`.
///   * `canonical_value = <type>` — If the type stored in the index differs from the property's value type; defaults to
///     `Self`. If this option is supplied, you will also want to supply `make_canonical` and `make_uncanonical`.
///   * `make_canonical = <expr>` — Function converting from `Self` to `CanonicalValue`; defaults to `std::convert::identity`.
///   * `make_uncanonical = <expr>` — Function converting from `CanonicalValue` to `Self`; defaults to `std::convert::identity`.
/// * Optional parameters that should generally be left alone, used internally to implement derived properties and
///   multi-properties:
///   * `index_id_fn = <expr>` — Function used to initialize the property index id; defaults to
///     `<Self as $crate::entity::property::Property<$entity>>::id()`.
///   * `collect_deps_fn = <expr>` — Function used to collect property dependencies; defaults to an empty implementation.
///   * `ctor_registration = <expr>` — Code run in the `ctor` for property registration.
///
/// # Semantics
/// - If `compute_derived_fn` is provided, the property is derived. In this case, `default_const` must be absent, and
///   calling `Property::default_const()` results in a panic. Use `define_derived_property!` or `impl_derived_property!`
///   instead of using this option directly.
/// - If `default_const` is provided, the property is a non-derived constant property. In this case,
///   `compute_derived_fn` must be absent, and calling `Property::compute_derived()` results in a panic.
/// - If neither is provided, the property is non-derived and required/explicit; both `Property::default_const()` and
///   `Property::compute_derived()` panic.
/// - If both are provided, a compile-time error is emitted.
#[macro_export]
macro_rules! impl_property {
    (
        $property:ident,
        $entity:ident
        $(, compute_derived_fn = $compute_derived_fn:expr)?
        $(, default_const = $default_const:expr)?
        $(, canonical_value = $canonical_value:ty)?
        $(, make_canonical = $make_canonical:expr)?
        $(, make_uncanonical = $make_uncanonical:expr)?
        $(, index_id_fn = $index_id_fn:expr)?
        $(, collect_deps_fn = $collect_deps_fn:expr)?
        $(, display_impl = $display_impl:expr)?
        $(, ctor_registration = $ctor_registration:expr)?
    ) => {
        // Enforce mutual exclusivity at compile time.
        $crate::impl_property!(@assert_not_both $($compute_derived_fn)? ; $($default_const)?);

        $crate::impl_property!(
            @__impl_property_common
            $property,
            $entity,

            // canonical value
            $crate::impl_property!(@unwrap_or_ty $($canonical_value)?, $property),

            // initialization_kind (implicit)
            $crate::impl_property!(@select_initialization_kind $($compute_derived_fn)? ; $($default_const)?),

            // compute_derived_fn (panic unless explicitly provided)
            $crate::impl_property!(
                @unwrap_or
                $($compute_derived_fn)?,
                |_, _| panic!("property {} is not derived", stringify!($property))
            ),

            // default_const (panic unless explicitly provided)
            $crate::impl_property!(
                @unwrap_or
                $($default_const)?,
                panic!("property {} has no default value", stringify!($property))
            ),

            // make_canonical
            $crate::impl_property!(@unwrap_or $($make_canonical)?, std::convert::identity),

            // make_uncanonical
            $crate::impl_property!(@unwrap_or $($make_uncanonical)?, std::convert::identity),

            // query_parts_type
            [&'a dyn std::any::Any; 1],

            // canonical_from_sorted_query_parts_fn
            {
                |parts: &[&dyn std::any::Any]| -> Option<<$property as $crate::entity::property::Property<$entity>>::CanonicalValue> {
                    let [part] = parts else {
                        return None;
                    };
                    part.downcast_ref::<$property>()
                        .copied()
                        .map(<$property as $crate::entity::property::Property<$entity>>::make_canonical)
                }
            },

            // query_parts_for_value_fn
            {
                fn default_query_parts_for_value<'a>(value: &'a $property) -> [&'a dyn std::any::Any; 1] {
                    [value as &'a dyn std::any::Any]
                }

                default_query_parts_for_value
            },

            // display_impl
            $crate::impl_property!(@unwrap_or $($display_impl)?, |v| format!("{v:?}")),

            // index_id_fn
            $crate::impl_property!(@unwrap_or $($index_id_fn)?, {
                <Self as $crate::entity::property::Property<$entity>>::id()
            }),

            // collect_deps_fn
            $crate::impl_property!(
                @unwrap_or
                $($collect_deps_fn)?,
                |_| {/* Do nothing */}
            ),

            // ctor_registration
            $crate::impl_property!(@unwrap_or $($ctor_registration)?, {
                $crate::entity::property_store::add_to_property_registry::<$entity, $property>();
            }),
        );
    };

    (
        @with_option_display_default
        $property:ident,
        $entity:ident
        $(, compute_derived_fn = $compute_derived_fn:expr)?
        $(, default_const = $default_const:expr)?
        $(, canonical_value = $canonical_value:ty)?
        $(, make_canonical = $make_canonical:expr)?
        $(, make_uncanonical = $make_uncanonical:expr)?
        $(, index_id_fn = $index_id_fn:expr)?
        $(, collect_deps_fn = $collect_deps_fn:expr)?
        $(, display_impl = $display_impl:expr)?
        $(, ctor_registration = $ctor_registration:expr)?
    ) => {
        $crate::impl_property!(
            $property,
            $entity
            $(, compute_derived_fn = $compute_derived_fn)?
            $(, default_const = $default_const)?
            $(, canonical_value = $canonical_value)?
            $(, make_canonical = $make_canonical)?
            $(, make_uncanonical = $make_uncanonical)?
            $(, index_id_fn = $index_id_fn)?
            $(, collect_deps_fn = $collect_deps_fn)?
            , display_impl = $crate::impl_property!(@unwrap_or $($display_impl)?, |value: &Self| {
                match value.0 {
                    Some(v) => format!("{:?}", v),
                    None => "None".to_string(),
                }
            })
            $(, ctor_registration = $ctor_registration)?
        );
    };

    (
        @multi_property
        $property:ident,
        $entity:ident,
        ( $($dependency:ident),+ )
        $(, compute_derived_fn = $compute_derived_fn:expr)?
        $(, default_const = $default_const:expr)?
        $(, canonical_value = $canonical_value:ty)?
        $(, make_canonical = $make_canonical:expr)?
        $(, make_uncanonical = $make_uncanonical:expr)?
        $(, index_id_fn = $index_id_fn:expr)?
        $(, collect_deps_fn = $collect_deps_fn:expr)?
        $(, display_impl = $display_impl:expr)?
        $(, ctor_registration = $ctor_registration:expr)?
    ) => {
        $crate::impl_property!(@assert_not_both $($compute_derived_fn)? ; $($default_const)?);

        $crate::impl_property!(
            @__impl_property_common
            $property,
            $entity,
            $crate::impl_property!(@unwrap_or_ty $($canonical_value)?, $property),
            $crate::impl_property!(@select_initialization_kind $($compute_derived_fn)? ; $($default_const)?),
            $crate::impl_property!(
                @unwrap_or
                $($compute_derived_fn)?,
                |_, _| panic!("property {} is not derived", stringify!($property))
            ),
            $crate::impl_property!(
                @unwrap_or
                $($default_const)?,
                panic!("property {} has no default value", stringify!($property))
            ),
            $crate::impl_property!(@unwrap_or $($make_canonical)?, std::convert::identity),
            $crate::impl_property!(@unwrap_or $($make_uncanonical)?, std::convert::identity),
            [&'a dyn std::any::Any; $crate::impl_property!(@count_tts $($dependency),+)],
            $crate::canonical_from_sorted_query_parts_closure!(( $($dependency),+ )),
            {
                $crate::paste::paste! {
                    fn multi_property_query_parts_for_value<'a>(
                        value: &'a $property,
                    ) -> [&'a dyn std::any::Any; $crate::impl_property!(@count_tts $($dependency),+)] {
                        let keys = [
                            $(
                                <$dependency as $crate::entity::property::Property<$entity>>::name(),
                            )+
                        ];
                        let ( $( [<_ $dependency:lower>] ),+ ) = value;
                        let mut parts = [
                            $(
                                [<_ $dependency:lower>] as &'a dyn std::any::Any,
                            )+
                        ];
                        $crate::entity::multi_property::static_reorder_by_keys(&keys, &mut parts);
                        parts
                    }

                    multi_property_query_parts_for_value
                }
            },
            $crate::impl_property!(@unwrap_or $($display_impl)?, |v| format!("{v:?}")),
            $crate::impl_property!(@unwrap_or $($index_id_fn)?, {
                <Self as $crate::entity::property::Property<$entity>>::id()
            }),
            $crate::impl_property!(@unwrap_or $($collect_deps_fn)?, |_| {/* Do nothing */}),
            $crate::impl_property!(@unwrap_or $($ctor_registration)?, {
                $crate::entity::property_store::add_to_property_registry::<$entity, $property>();
            }),
        );
    };

    // Compile-time mutual exclusivity check.
    (@assert_not_both $compute_derived_fn:expr ; $default_const:expr) => {
        compile_error!(
            "impl_property!: `compute_derived_fn = ...` (derived property) and `default_const = ...` \
             (non-derived property default constant) are mutually exclusive. Remove one of them."
        );
    };
    (@assert_not_both $compute_derived_fn:expr ; ) => {};
    (@assert_not_both ; $default_const:expr) => {};
    (@assert_not_both ; ) => {};

    // Select initialization kind (implicit).
    (@select_initialization_kind $compute_derived_fn:expr ; $default_const:expr) => {
        // This arm should be unreachable because @assert_not_both triggers first, but keep it
        // as a backstop if the macro is used incorrectly.
        compile_error!(
            "impl_property!: cannot select initialization kind because both `compute_derived_fn` \
             and `default_const` are present"
        )
    };
    (@select_initialization_kind $compute_derived_fn:expr ; ) => {
        $crate::entity::property::PropertyInitializationKind::Derived
    };
    (@select_initialization_kind ; $default_const:expr) => {
        $crate::entity::property::PropertyInitializationKind::Constant
    };
    (@select_initialization_kind ; ) => {
        $crate::entity::property::PropertyInitializationKind::Explicit
    };

    // Helpers for defaults, a pair per macro parameter type (`expr`, `ty`).
    (@unwrap_or $value:expr, $_default:expr) => { $value };
    (@unwrap_or, $default:expr) => { $default };

    (@unwrap_or_ty $ty:ty, $_default:ty) => { $ty };
    (@unwrap_or_ty, $default:ty) => { $default };

    (@replace_with_unit $_tt:tt) => { () };
    (@count_tts $($tt:tt),* $(,)?) => {
        <[()]>::len(&[$($crate::impl_property!(@replace_with_unit $tt)),*])
    };

    // This is the purely syntactic implementation.
    (
        @__impl_property_common
        $property:ident,           // The name of the type we are implementing `Property` for
        $entity:ident,             // The entity type this property is associated with
        $canonical_value:ty,       // If the type stored in the index is different from Self, the name of that type
        $initialization_kind:expr, // The kind of initialization this property has (implicit selection)
        $compute_derived_fn:expr,  // If the property is derived, the function that computes the value
        $default_const:expr,       // If the property has a constant default initial value, the default value
        $make_canonical:expr,      // A function that takes a value and returns a canonical value
        $make_uncanonical:expr,    // A function that takes a canonical value and returns a value
        $query_parts_type:ty,
        $canonical_from_sorted_query_parts_fn:expr,
        $query_parts_for_value_fn:expr,
        $display_impl:expr,        // A function that takes a canonical value and returns a string representation of this property
        $index_id_fn:expr,         // Code that returns the unique index for this property
        $collect_deps_fn:expr,     // If the property is derived, the function that computes the value
        $ctor_registration:expr,   // Code that runs in a ctor for property registration
    ) => {
        impl $crate::entity::property::Property<$entity> for $property {
            type CanonicalValue = $canonical_value;
            type QueryParts<'a> = $query_parts_type where Self: 'a;

            const NAME: &'static str = stringify!($property);

            fn initialization_kind() -> $crate::entity::property::PropertyInitializationKind {
                $initialization_kind
            }

            fn compute_derived(
                _context: &$crate::Context,
                _entity_id: $crate::entity::EntityId<$entity>,
            ) -> Self {
                ($compute_derived_fn)(_context, _entity_id)
            }

            fn default_const() -> Self {
                $default_const
            }

            fn make_canonical(self) -> Self::CanonicalValue {
                ($make_canonical)(self)
            }

            fn make_uncanonical(value: Self::CanonicalValue) -> Self {
                ($make_uncanonical)(value)
            }

            fn canonical_from_sorted_query_parts(
                parts: &[&dyn std::any::Any],
            ) -> Option<Self::CanonicalValue> {
                ($canonical_from_sorted_query_parts_fn)(parts)
            }

            fn query_parts_for_value(value: &Self) -> Self::QueryParts<'_> {
                ($query_parts_for_value_fn)(value)
            }

            fn get_display(&self) -> String {
                ($display_impl)(self)
            }

            fn id() -> usize {
                // This static must be initialized with a compile-time constant expression.
                // We use `usize::MAX` as a sentinel to mean "uninitialized". This
                // static variable is shared among all instances of this concrete item type.
                static INDEX: std::sync::atomic::AtomicUsize =
                    std::sync::atomic::AtomicUsize::new(usize::MAX);

                // Fast path: already initialized.
                let index = INDEX.load(std::sync::atomic::Ordering::Relaxed);
                if index != usize::MAX {
                    return index;
                }

                // Slow path: initialize it.
                $crate::entity::property_store::initialize_property_id::<$entity>(&INDEX)
            }

            fn index_id() -> usize {
                $index_id_fn
            }

            fn collect_non_derived_dependencies(result: &mut $crate::HashSet<usize>) {
                ($collect_deps_fn)(result)
            }
        }

        $crate::paste::paste! {
            $crate::ctor::declarative::ctor!{
                #[ctor]
                fn [<_register_property_ $entity:snake _ $property:snake>]() {
                    $ctor_registration
                }
            }
        }
    };
}

/// The "derived" variant of [`define_property!`][macro@crate::define_property] for defining simple derived property types.
/// Defines a `struct` or `enum` with a standard set of derives and automatically invokes
/// [`impl_derived_property!`][macro@crate::impl_derived_property] for it.
///
/// Defines a derived property with the following parameters:
/// * Property type declaration: A struct or enum declaration.
/// * `$entity`: The name of the entity of which the new type is a property.
/// * `[$($dependency),+]`: A list of person properties the derived property depends on.
/// * `[$(global_dependency),*]`: A list of global properties the derived property depends on. Can optionally be omitted if empty.
/// * `$calculate`: A closure that takes the values of each dependency and returns the derived value.
/// * Optional parameters: The same optional parameters accepted by [`impl_property!`][macro@crate::impl_property],
///   plus `impl_eq_hash = Eq | Hash | both | neither` to control whether `Eq`/`Hash` are derived or generated
///   for the declared type, mirroring [`define_property!`][macro@crate::define_property].
#[macro_export]
macro_rules! define_derived_property {
    // Implementation Notes
    //
    // We reuse `define_property!`'s shared decoration helper, then delegate the derived-property
    // behavior to `impl_derived_property!`.
    //
    // See `derive_property!` implementation notes for why each type form is duplicated.

    // Struct (tuple) with single Option<T> field
    (
        struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ),
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            $impl_eq_hash,
            pub struct $name(pub Option<$inner_ty>);,
            $name
        );

        $crate::impl_derived_property!(
            @with_option_display_default
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };
    (
        struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ),
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            ,
            pub struct $name(pub Option<$inner_ty>);,
            $name
        );

        $crate::impl_derived_property!(
            @with_option_display_default
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };

    // Struct (tuple)
    (
        struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ),
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            $impl_eq_hash,
            pub struct $name( $(pub $field_ty),* );,
            $name
        );

        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };
    (
        struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ),
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            ,
            pub struct $name( $(pub $field_ty),* );,
            $name
        );

        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };

    // Struct (named fields)
    (
        struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? },
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            $impl_eq_hash,
            pub struct $name { $($visibility $field_name : $field_ty),* },
            $name
        );

        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };
    (
        struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? },
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            ,
            pub struct $name { $($visibility $field_name : $field_ty),* },
            $name
        );

        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };

    // Enum
    (
        enum $name:ident {
            $($variant:ident),* $(,)?
        },
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr,
        impl_eq_hash = $impl_eq_hash:ident
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            $impl_eq_hash,
            pub enum $name {
                $($variant),*
            },
            $name
        );

        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };
    (
        enum $name:ident {
            $($variant:ident),* $(,)?
        },
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr
        $(, $($extra:tt)+)*
    ) => {
        $crate::define_property!(
            @apply_property_decoration
            ,
            pub enum $name {
                $($variant),*
            },
            $name
        );

        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($($global_dependency),*)?],
            |$($param),+| $derive_fn
            $(, $($extra)+)*
        );
    };
}

/// Implements the [`Property`][crate::entity::property::Property] trait for an existing type as a derived property.
///
/// Accepts the same parameters as [`define_derived_property!`][macro@crate::define_derived_property], except the first parameter is the name of a
/// type assumed to already be declared rather than a type declaration. This is the derived property equivalent
/// of [`impl_property!`][macro@crate::impl_property]. It calls [`impl_property!`][macro@crate::impl_property] with the appropriate derived property parameters.
#[macro_export]
macro_rules! impl_derived_property {
    (
        $name:ident,
        $entity:ident,
        [$($dependency:ident),*]
        $(, [$($global_dependency:ident),*])?,
        |$($param:ident),+| $derive_fn:expr
        $(, $($extra:tt)+)*
    ) => {
        $crate::impl_property!(
            $name,
            $entity,
            compute_derived_fn = $crate::impl_derived_property!(
                @construct_compute_fn
                $entity,
                [$($dependency),*],
                [$($($global_dependency),*)?],
                |$($param),+| $derive_fn
            ),
            collect_deps_fn = | deps: &mut $crate::HashSet<usize> | {
                $(
                    if <$dependency as $crate::entity::property::Property<$entity>>::is_derived() {
                        <$dependency as $crate::entity::property::Property<$entity>>::collect_non_derived_dependencies(deps);
                    } else {
                        deps.insert(<$dependency as $crate::entity::property::Property<$entity>>::id());
                    }
                )*
            }
            $(, $($extra)+)*
        );
    };

    // Internal branch to construct the compute function.
    (
        @construct_compute_fn
        $entity:ident,
        [$($dependency:ident),*],
        [$($global_dependency:ident),*],
        |$($param:ident),+| $derive_fn:expr
    ) => {
        |context: &$crate::Context, entity_id| {
            #[allow(unused_imports)]
            use $crate::global_properties::ContextGlobalPropertiesExt;
            #[allow(unused_parens)]
            let ($($param,)*) = (
                $(context.get_property::<$entity, $dependency>(entity_id)),*,
                $(
                    context.get_global_property_value($global_dependency)
                        .expect(&format!("Global property {} not initialized", stringify!($global_dependency)))
                ),*
            );
            $derive_fn
        }
    };

    (@unwrap_or $value:expr, $_default:expr) => { $value };
    (@unwrap_or, $default:expr) => { $default };

    (
        @with_option_display_default
        $name:ident,
        $entity:ident,
        [$($dependency:ident),*],
        [$($global_dependency:ident),*],
        |$($param:ident),+| $derive_fn:expr
        $(, default_const = $default_const:expr)?
        $(, display_impl = $display_impl:expr)?
        $(, canonical_value = $canonical_value:ty)?
        $(, make_canonical = $make_canonical:expr)?
        $(, make_uncanonical = $make_uncanonical:expr)?
        $(, index_id_fn = $index_id_fn:expr)?
        $(, collect_deps_fn = $collect_deps_fn:expr)?
        $(, ctor_registration = $ctor_registration:expr)?
    ) => {
        $crate::impl_derived_property!(
            $name,
            $entity,
            [$($dependency),*],
            [$($global_dependency),*],
            |$($param),+| $derive_fn
            $(, default_const = $default_const)?
            , display_impl = $crate::impl_derived_property!(@unwrap_or $($display_impl)?, |value: &$name| {
                match value.0 {
                    Some(v) => format!("{:?}", v),
                    None => "None".to_string(),
                }
            })
            $(, canonical_value = $canonical_value)?
            $(, make_canonical = $make_canonical)?
            $(, make_uncanonical = $make_uncanonical)?
            $(, index_id_fn = $index_id_fn)?
            $(, collect_deps_fn = $collect_deps_fn)?
            $(, ctor_registration = $ctor_registration)?
        );
    };

}

/// Defines a derived property consisting of a (named) tuple of other properties. The primary use case
/// is for indexing and querying properties jointly.
///
/// The index subsystem is smart enough to reuse indexes for multi-properties that are equivalent up to
/// reordering of the component properties. The querying subsystem is able to detect when its multiple
/// component properties are equivalent to an indexed multi-property and use that index to perform the
/// query.
///
/// Components must be the underlying property type, not a type alias (see issue #843):
///
/// ```compile_fail
/// use ixa::{define_entity, define_property, define_multi_property};
/// define_entity!(Person);
/// define_property!(struct Age(u8), Person, default_const = Age(0));
/// define_property!(struct Height(u8), Person, default_const = Height(0));
/// type Years = Age;
/// define_multi_property!((Years, Height), Person);
/// ```
#[macro_export]
macro_rules! define_multi_property {
        (
            ( $($dependency:ident),+ ),
            $entity:ident
        ) => {
            $crate::paste::paste! {
                type [<$($dependency)*>] = ( $($dependency),+ );

                // Reject type aliases; see issue #843.
                $(
                    const _: () = assert!(
                        $crate::entity::property::const_str_eq(
                            stringify!($dependency),
                            <$dependency as $crate::entity::property::Property<$entity>>::NAME,
                        ),
                        concat!(
                            "define_multi_property!: `",
                            stringify!($dependency),
                            "` is a type alias; use the underlying property type (see issue #843)."
                        ),
                    );
                )+

                $crate::impl_property!(
                    @multi_property
                    [<$($dependency)*>],
                    $entity,
                    ( $($dependency),+ ),
                    compute_derived_fn = |context: &$crate::Context, entity_id: $crate::entity::EntityId<$entity>| {
                        (
                            $(context.get_property::<$entity, $dependency>(entity_id)),+
                        )
                    },
                    canonical_value = $crate::sorted_tag!(( $($dependency),+ )),
                    make_canonical = $crate::reorder_closure!(( $($dependency),+ )),
                    make_uncanonical = $crate::unreorder_closure!(( $($dependency),+ )),

                    index_id_fn = {
                        // This static must be initialized with a compile-time constant expression.
                        // We use `usize::MAX` as a sentinel to mean "uninitialized". This
                        // static variable is shared among all instances of this concrete item type.
                        static INDEX_ID: std::sync::atomic::AtomicUsize =
                            std::sync::atomic::AtomicUsize::new(usize::MAX);

                        // Fast path: already initialized.
                        let index_id = INDEX_ID.load(std::sync::atomic::Ordering::Relaxed);
                        if index_id != usize::MAX {
                            return index_id;
                        }

                        // Slow path: initialize it.
                        // Multi-properties report a single index ID for all equivalent multi-properties,
                        // because they share a single `Index<E, P>` instance.
                        let mut type_ids = [$( <$dependency as $crate::entity::property::Property<$entity>>::type_id() ),+];
                        type_ids.sort_unstable();
                        // Check if an index has already been assigned to this property set.
                        match $crate::entity::multi_property::type_ids_to_multi_property_index(&type_ids) {
                            Some(index) => {
                                // An index exists. Reuse it for our own index.
                                INDEX_ID.store(index, std::sync::atomic::Ordering::Relaxed);
                                index
                            },
                            None => {
                                // An index ID is not yet assigned. We will use our own index for this property.
                                let index = <Self as $crate::entity::property::Property<$entity>>::id();
                                INDEX_ID.store(index, std::sync::atomic::Ordering::Relaxed);
                                // And register the new index with this property set.
                                $crate::entity::multi_property::register_type_ids_to_multi_property_index(
                                    &type_ids,
                                    index
                                );
                                index
                            }
                        }
                    },

                    collect_deps_fn = | deps: &mut $crate::HashSet<usize> | {
                        $(
                            if <$dependency as $crate::entity::property::Property<$entity>>::is_derived() {
                                <$dependency as $crate::entity::property::Property<$entity>>::collect_non_derived_dependencies(deps);
                            } else {
                                deps.insert(<$dependency as $crate::entity::property::Property<$entity>>::id());
                            }
                        )*
                    },

                    display_impl = |val: &( $($dependency),+ )| {
                        let ( $( [<_ $dependency:lower>] ),+ ) = val;
                        let mut displayed = String::from("(");
                        $(
                            displayed.push_str(
                                &<$dependency as $crate::entity::property::Property<$entity>>::get_display([<_ $dependency:lower>])
                            );
                            displayed.push_str(", ");
                        )+
                        displayed.truncate(displayed.len() - 2);
                        displayed.push_str(")");
                        displayed
                    },

                    ctor_registration = {
                        // Ensure the property's `index_id()` is initialized at startup.
                        let _ = < [<$($dependency)*>] as $crate::entity::property::Property::<$entity> >::index_id();
                        $crate::entity::property_store::add_to_property_registry::<$entity, [<$($dependency)*>]>();
                    }
                );

            }
        };
    }

#[cfg(test)]
mod tests {
    // We define unused properties to test macro implementation.
    #![allow(dead_code)]

    use crate::entity::{PropertyIndexType, QueryInternal};
    use crate::prelude::*;
    use crate::with;

    define_entity!(Person);
    define_entity!(Group);

    define_property!(struct Pu32(u32), Person, default_const = Pu32(0));
    define_property!(struct POu32(Option<u32>), Person, default_const = POu32(None));
    define_property!(
        struct POFloat(Option<f64>),
        Person,
        impl_eq_hash = both,
        default_const = POFloat(None)
    );
    define_property!(
        struct POu32Custom(Option<u32>),
        Person,
        default_const = POu32Custom(None),
        display_impl = |value: &POu32Custom| match value.0 {
            Some(v) => format!("custom:{v}"),
            None => "custom:none".to_string(),
        }
    );
    define_property!(struct Name(&'static str), Person, default_const = Name(""));
    define_property!(struct Age(u8), Person, default_const = Age(0));
    define_property!(struct Weight(f64), Person, impl_eq_hash = both, default_const = Weight(0.0));

    // A struct with named fields
    define_property!(
        struct Innocculation {
            time: f64,
            dose: u8,
        },
        Person,
        impl_eq_hash = both,
        default_const = Innocculation { time: 0.0, dose: 0 }
    );

    // An enum non-derived property
    define_property!(
        enum InfectionStatus {
            Susceptible,
            Infected,
            Recovered,
        },
        Person,
        default_const = InfectionStatus::Susceptible
    );

    // An enum derived property
    define_derived_property!(
        enum AgeGroup {
            Child,
            Adult,
            Senior,
        },
        Person,
        [Age], // Depends only on age
        |age| {
            let age: Age = age;
            if age.0 < 18 {
                AgeGroup::Child
            } else if age.0 < 65 {
                AgeGroup::Adult
            } else {
                AgeGroup::Senior
            }
        }
    );

    // Derived property - computed from other properties
    define_derived_property!(struct DerivedProp(bool), Person, [Age],
        |age| {
            DerivedProp(age.0 % 2 == 0)
        }
    );

    define_derived_property!(
        struct DerivedMaybeAge(Option<u8>),
        Person,
        [Age],
        |age| DerivedMaybeAge((age.0 != 0).then_some(age.0))
    );

    define_derived_property!(
        struct DerivedMaybeWeight(Option<f64>),
        Person,
        [Age],
        |age| DerivedMaybeWeight((age.0 != 0).then_some(age.0 as f64)),
        impl_eq_hash = both
    );

    define_derived_property!(
        struct DerivedMaybeAgeCustom(Option<u8>),
        Person,
        [Age],
        |age| DerivedMaybeAgeCustom((age.0 != 0).then_some(age.0)),
        display_impl = |value: &DerivedMaybeAgeCustom| match value.0 {
            Some(v) => format!("derived:{v}"),
            None => "derived:none".to_string(),
        }
    );

    define_derived_property!(
        struct DerivedWeight(f64),
        Person,
        [Age],
        |age| DerivedWeight(age.0 as f64),
        impl_eq_hash = both
    );

    // A property type for two distinct entities.
    #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
    pub enum InfectionKind {
        Respiratory,
        Genetic,
        Superficial,
    }
    impl_property!(
        InfectionKind,
        Person,
        default_const = InfectionKind::Respiratory
    );
    impl_property!(InfectionKind, Group, default_const = InfectionKind::Genetic);

    define_multi_property!((Name, Age, Weight), Person);
    define_multi_property!((Age, Weight, Name), Person);
    define_multi_property!((Weight, Age, Name), Person);

    // For convenience
    type ProfileNAW = (Name, Age, Weight);
    type ProfileAWN = (Age, Weight, Name);
    type ProfileWAN = (Weight, Age, Name);

    #[test]
    fn test_multi_property_ordering() {
        let a = (Name("Jane"), Age(22), Weight(180.5));
        let b = (Age(22), Weight(180.5), Name("Jane"));
        let c = (Weight(180.5), Age(22), Name("Jane"));

        // Multi-properties share the same index
        assert_eq!(ProfileNAW::index_id(), ProfileAWN::index_id());
        assert_eq!(ProfileNAW::index_id(), ProfileWAN::index_id());

        let a_canonical: <ProfileNAW as Property<_>>::CanonicalValue =
            ProfileNAW::make_canonical(a);
        let b_canonical: <ProfileAWN as Property<_>>::CanonicalValue =
            ProfileAWN::make_canonical(b);
        let c_canonical: <ProfileWAN as Property<_>>::CanonicalValue =
            ProfileWAN::make_canonical(c);

        assert_eq!(a_canonical, b_canonical);
        assert_eq!(a_canonical, c_canonical);

        // Equivalent multi-properties must hash canonical values identically.
        assert_eq!(
            crate::hashing::one_shot_128(&a_canonical),
            crate::hashing::one_shot_128(&b_canonical)
        );
        assert_eq!(
            crate::hashing::one_shot_128(&a_canonical),
            crate::hashing::one_shot_128(&c_canonical)
        );

        // Since the canonical values are the same, we could have used any single one, but this
        // demonstrates that we can convert from one order to another.
        assert_eq!(ProfileNAW::make_uncanonical(b_canonical), a);
        assert_eq!(ProfileAWN::make_uncanonical(c_canonical), b);
        assert_eq!(ProfileWAN::make_uncanonical(a_canonical), c);
    }

    #[test]
    fn test_multi_property_vs_property_query() {
        let mut context = Context::new();

        context
            .add_entity(with!(Person, Name("John"), Age(42), Weight(220.5)))
            .unwrap();
        context
            .add_entity(with!(Person, Name("Jane"), Age(22), Weight(180.5)))
            .unwrap();
        context
            .add_entity(with!(Person, Name("Bob"), Age(32), Weight(190.5)))
            .unwrap();
        context
            .add_entity(with!(Person, Name("Alice"), Age(22), Weight(170.5)))
            .unwrap();

        context.index_property::<_, ProfileNAW>();

        // Check that all equivalent multi-properties are indexed...
        assert!(context.is_property_indexed::<Person, ProfileNAW>());
        assert!(context.is_property_indexed::<Person, ProfileAWN>());
        assert!(context.is_property_indexed::<Person, ProfileWAN>());
        // ...but only one `Index<E, P>` instance was created.
        let mut indexed_count = 0;
        if context
            .get_property_value_store::<Person, ProfileNAW>()
            .index_type()
            != PropertyIndexType::Unindexed
        {
            indexed_count += 1;
        }
        if context
            .get_property_value_store::<Person, ProfileAWN>()
            .index_type()
            != PropertyIndexType::Unindexed
        {
            indexed_count += 1;
        }
        if context
            .get_property_value_store::<Person, ProfileWAN>()
            .index_type()
            != PropertyIndexType::Unindexed
        {
            indexed_count += 1;
        }
        assert_eq!(indexed_count, 1);

        {
            let example_query = (Name("Alice"), Age(22), Weight(170.5));
            let query_multi_property_id =
                <(Name, Age, Weight) as QueryInternal<Person>>::multi_property_id(&example_query);
            assert!(query_multi_property_id.is_some());
            assert_eq!(ProfileNAW::index_id(), query_multi_property_id.unwrap());
            let query_parts = QueryInternal::query_parts(&example_query);
            assert_eq!(
                ProfileNAW::canonical_from_sorted_query_parts(query_parts.as_ref()),
                Some((Name("Alice"), Age(22), Weight(170.5)).make_canonical())
            );
        }

        context.with_query_results(
            with!(Person, (Name("John"), Age(42), Weight(220.5))),
            &mut |results| {
                assert_eq!(results.into_iter().count(), 1);
            },
        );
    }

    #[test]
    fn test_derived_property() {
        let mut context = Context::new();

        let senior = context
            .add_entity::<Person, _>(with!(Person, Age(92)))
            .unwrap();
        let child = context
            .add_entity::<Person, _>(with!(Person, Age(12)))
            .unwrap();
        let adult = context
            .add_entity::<Person, _>(with!(Person, Age(44)))
            .unwrap();

        let senior_group: AgeGroup = context.get_property(senior);
        let child_group: AgeGroup = context.get_property(child);
        let adult_group: AgeGroup = context.get_property(adult);

        assert_eq!(senior_group, AgeGroup::Senior);
        assert_eq!(child_group, AgeGroup::Child);
        assert_eq!(adult_group, AgeGroup::Adult);

        // Age has no dependencies (only dependents)
        assert!(Age::non_derived_dependencies().is_empty());
        // AgeGroup depends only on Age
        assert_eq!(AgeGroup::non_derived_dependencies(), [Age::id()]);

        // Age has several dependents. This assert may break if you add or remove the properties in this test module.
        let mut expected_dependents = [
            AgeGroup::id(),
            DerivedProp::id(),
            DerivedMaybeAge::id(),
            DerivedMaybeWeight::id(),
            DerivedMaybeAgeCustom::id(),
            DerivedWeight::id(),
            ProfileNAW::id(),
            ProfileAWN::id(),
            ProfileWAN::id(),
        ];
        expected_dependents.sort_unstable();
        assert_eq!(Age::dependents(), expected_dependents);
    }

    #[test]
    fn test_get_display() {
        let mut context = Context::new();
        let person = context
            .add_entity(with!(Person, POu32(Some(42)), Pu32(22)))
            .unwrap();
        assert_eq!(
            format!(
                "{:}",
                POu32::get_display(&context.get_property::<_, POu32>(person))
            ),
            "42"
        );
        assert_eq!(
            format!(
                "{:}",
                Pu32::get_display(&context.get_property::<_, Pu32>(person))
            ),
            "Pu32(22)"
        );
        let person2 = context
            .add_entity(with!(Person, POu32(None), Pu32(11)))
            .unwrap();
        assert_eq!(
            format!(
                "{:}",
                POu32::get_display(&context.get_property::<_, POu32>(person2))
            ),
            "None"
        );
    }

    #[test]
    fn test_option_property_display_patterns() {
        let mut context = Context::new();

        let some_person = context
            .add_entity(with!(
                Person,
                POu32(Some(42)),
                POFloat(Some(3.5)),
                POu32Custom(Some(7)),
                Pu32(1),
            ))
            .unwrap();
        let none_person = context
            .add_entity(with!(
                Person,
                POu32(None),
                POFloat(None),
                POu32Custom(None),
                Pu32(2)
            ))
            .unwrap();

        assert_eq!(
            POu32::get_display(&context.get_property::<_, POu32>(some_person)),
            "42"
        );
        assert_eq!(
            POu32::get_display(&context.get_property::<_, POu32>(none_person)),
            "None"
        );

        assert_eq!(
            POFloat::get_display(&context.get_property::<_, POFloat>(some_person)),
            "3.5"
        );
        assert_eq!(
            POFloat::get_display(&context.get_property::<_, POFloat>(none_person)),
            "None"
        );

        assert_eq!(
            POu32Custom::get_display(&context.get_property::<_, POu32Custom>(some_person)),
            "custom:7"
        );
        assert_eq!(
            POu32Custom::get_display(&context.get_property::<_, POu32Custom>(none_person)),
            "custom:none"
        );
    }

    #[test]
    fn test_option_derived_property_display_patterns() {
        let mut context = Context::new();

        let some_person = context
            .add_entity::<Person, _>(with!(Person, Age(42)))
            .unwrap();
        let none_person = context
            .add_entity::<Person, _>(with!(Person, Age(0)))
            .unwrap();

        assert_eq!(
            DerivedMaybeAge::get_display(&context.get_property::<_, DerivedMaybeAge>(some_person)),
            "42"
        );
        assert_eq!(
            DerivedMaybeAge::get_display(&context.get_property::<_, DerivedMaybeAge>(none_person)),
            "None"
        );

        assert_eq!(
            DerivedMaybeWeight::get_display(
                &context.get_property::<_, DerivedMaybeWeight>(some_person)
            ),
            "42.0"
        );
        assert_eq!(
            DerivedMaybeWeight::get_display(
                &context.get_property::<_, DerivedMaybeWeight>(none_person)
            ),
            "None"
        );

        assert_eq!(
            DerivedMaybeAgeCustom::get_display(
                &context.get_property::<_, DerivedMaybeAgeCustom>(some_person)
            ),
            "derived:42"
        );
        assert_eq!(
            DerivedMaybeAgeCustom::get_display(
                &context.get_property::<_, DerivedMaybeAgeCustom>(none_person)
            ),
            "derived:none"
        );
    }

    #[test]
    fn test_debug_trait() {
        let property = Pu32(11);
        let debug_str = format!("{:?}", property);
        assert_eq!(debug_str, "Pu32(11)");

        let property = POu32(Some(22));
        let debug_str = format!("{:?}", property);
        assert_eq!(debug_str, "POu32(Some(22))");
    }

    #[test]
    fn test_define_derived_property_impl_eq_hash() {
        let mut values = crate::HashSet::default();
        values.insert(DerivedWeight(3.0));
        assert!(values.contains(&DerivedWeight(3.0)));
    }
}