darling_core 0.24.0

Helper crate for proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code.
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
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
use quote::ToTokens;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::btree_map::BTreeMap;
use std::collections::hash_map::HashMap;
use std::collections::HashSet;
use std::hash::BuildHasher;
use std::num;
use std::rc::Rc;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use syn::spanned::Spanned;

use syn::{Expr, Ident, Lit, Meta, Path};

use crate::ast::{MetaNameValueInvalidExpr, NestedMeta};
use crate::util::path_to_string;
use crate::{Error, Result};

/// Create an instance from an item in an attribute declaration.
///
/// # Implementing `FromMeta`
/// * Do not take a dependency on the `ident` of the passed-in meta item. The ident will be set by the field name of the containing struct.
/// * Implement only the `from_*` methods that you intend to support. The default implementations will return useful errors.
///
/// # Provided Implementations
/// ## bool
///
/// * Word with no value specified - becomes `true`.
/// * As a boolean literal, e.g. `foo = true`.
/// * As a string literal, e.g. `foo = "true"`.
///
/// ## char
/// * As a char literal, e.g. `foo = '#'`.
/// * As a string literal consisting of a single character, e.g. `foo = "#"`.
///
/// ## String
/// * As a string literal, e.g. `foo = "hello"`.
/// * As a raw string literal, e.g. `foo = r#"hello "world""#`.
///
/// ## Number
/// * As a string literal, e.g. `foo = "-25"`.
/// * As an unquoted positive value, e.g. `foo = 404`. Negative numbers must be in quotation marks.
///
/// ## ()
/// * Word with no value specified, e.g. `foo`. This is best used with `Option`.
///   See `darling::util::Flag` for a more strongly-typed alternative.
///
/// ## Option
/// * Any format produces `Some`.
///
/// ## `Result<T, darling::Error>`
/// * Allows for fallible parsing; will populate the target field with the result of the
///   parse attempt.
pub trait FromMeta: Sized {
    fn from_nested_meta(item: &NestedMeta) -> Result<Self> {
        (match *item {
            NestedMeta::Lit(ref lit) => Self::from_value(lit),
            NestedMeta::Meta(ref mi) => Self::from_meta(mi),
            NestedMeta::NameValueInvalidExpr(ref meta) => Self::from_invalid_expr(meta),
        })
        .map_err(|e| e.with_span(item))
    }

    /// Create an instance from a `syn::Meta` by dispatching to the format-appropriate
    /// trait function. This generally should not be overridden by implementers.
    ///
    /// # Error Spans
    /// If this method is overridden and can introduce errors that weren't passed up from
    /// other `from_meta` calls, the override must call `with_span` on the error using the
    /// `item` to make sure that the emitted diagnostic points to the correct location in
    /// source code.
    fn from_meta(item: &Meta) -> Result<Self> {
        (match *item {
            Meta::Path(_) => Self::from_word(),
            Meta::List(ref value) => {
                Self::from_list(&NestedMeta::parse_meta_list(value.tokens.clone())?[..])
            }
            Meta::NameValue(ref value) => Self::from_expr(&value.value),
        })
        .map_err(|e| e.with_span(item))
    }

    /// When a field is omitted from a parent meta-item, `from_none` is used to attempt
    /// recovery before a missing field error is generated.
    ///
    /// **Most types should not override this method.** `darling` already allows field-level
    /// missing-field recovery using `#[darling(default)]` and `#[darling(default = "...")]`,
    /// and users who add a `String` field to their `FromMeta`-deriving struct would be surprised
    /// if they get back `""` instead of a missing field error when that field is omitted.
    ///
    /// The primary use-case for this is `Option<T>` fields gracefully handling absence without
    /// needing `#[darling(default)]`.
    fn from_none() -> Option<Self> {
        None
    }

    /// Create an instance from the presence of the word in the attribute with no
    /// additional options specified.
    fn from_word() -> Result<Self> {
        Err(Error::unsupported_format("word"))
    }

    /// Create an instance from a list of nested meta items.
    #[allow(unused_variables)]
    fn from_list(items: &[NestedMeta]) -> Result<Self> {
        Err(Error::unsupported_format("list"))
    }

    /// Create an instance from a literal value of either `foo = "bar"` or `foo("bar")`.
    /// This dispatches to the appropriate method based on the type of literal encountered,
    /// and generally should not be overridden by implementers.
    ///
    /// # Error Spans
    /// If this method is overridden, the override must make sure to add `value`'s span
    /// information to the returned error by calling `with_span(value)` on the `Error` instance.
    fn from_value(value: &Lit) -> Result<Self> {
        (match *value {
            Lit::Bool(ref b) => Self::from_bool(b.value),
            Lit::Str(ref s) => Self::from_string(&s.value()),
            Lit::Char(ref ch) => Self::from_char(ch.value()),
            _ => Err(Error::unexpected_lit_type(value)),
        })
        .map_err(|e| e.with_span(value))
    }

    fn from_expr(expr: &Expr) -> Result<Self> {
        match *expr {
            Expr::Lit(ref lit) => Self::from_value(&lit.lit),
            Expr::Group(ref group) => {
                // syn may generate this invisible group delimiter when the input to the darling
                // proc macro (specifically, the attributes) are generated by a
                // macro_rules! (e.g. propagating a macro_rules!'s expr)
                // Since we want to basically ignore these invisible group delimiters,
                // we just propagate the call to the inner expression.
                Self::from_expr(&group.expr)
            }
            _ => Err(Error::unexpected_expr_type(expr)),
        }
        .map_err(|e| e.with_span(expr))
    }

    /// `name = value` where the `value` failed to parse as a [`syn::Expr`].
    ///
    /// For example:
    ///
    /// ```ignore
    /// #[example(vis = pub(crate))]
    /// #[example(bound = where T: Deserialize<'de>)]
    /// ```
    ///
    /// It is recommended to implement [`syn::parse::Parse`] for your type, then
    /// have an implementation of `from_invalid_expr` as follows:
    ///
    /// ```ignore
    /// fn from_invalid_expr(value: &MetaNameValueInvalidExpr) -> darling::Result<Self> {
    ///     syn::parse2(value.value.clone()).map_err(Into::into)
    /// }
    /// ```
    ///
    /// # Convert from anything
    ///
    /// This function handles parsing for things that are invalid expressions.
    ///
    /// Because of that, if you were to try and re-implement `impl FromMeta for syn::Type`,
    /// you will run into a problem: `(i32, u32)` is both a valid [`Expr`]
    /// and a valid [`Type`](syn::Type). `from_invalid_expr` will never be called for it, because it
    /// **is** a valid expression.
    ///
    /// In order to circumvent that, you need to implement both `from_expr` and `from_invalid_expr`:
    ///
    /// ```ignore
    /// fn from_expr(expr: &Expr) -> darling::Result<Self> {
    ///     match *expr {
    ///         // Invisible delimiter when the input to the macro is passed
    ///         // by a `macro_rules!`, but we can safely ignore the wrapper
    ///         Expr::Group(ref group) => Self::from_expr(&group.expr),
    ///         _ => Ok(syn::parse2(expr.into_token_stream().clone())?)
    ///     }
    ///     .map_err(|e| e.with_span(expr))
    /// }
    ///
    /// fn from_invalid_expr(value: &MetaNameValueInvalidExpr) -> darling::Result<Type> {
    ///     syn::parse2(value.value.clone()).map_err(Into::into)
    /// }
    /// ```
    ///
    /// `from_expr` parses the set of all valid expressions, `from_invalid_expr` parses the set of all invalid expressions:
    /// together, they can parse anything!
    ///
    /// # Truly arbitrary inputs
    ///
    /// Tokens are collected until the first comma is encountered. The comma is excluded
    /// from the collected tokens.
    ///
    /// For this input, it means we first collect everything between `=` and `,` into a `TokenStream`:
    ///
    /// ```ignore
    /// #[example(bound = where T: Deserialize<'de>, D: 'static)]
    ///                   ^^^^^^^^^^^^^^^^^^^^^^^^^
    /// ```
    ///
    /// Then we try to parse the remaining as a [`syn::NestedMeta`], and fail:
    ///
    /// ```ignore
    /// #[example(bound = where T: Deserialize<'de>, D: 'static)]
    ///                                              ^^^^^^^^^^
    /// ```
    ///
    /// In order to support truly arbitrary inputs like the `bound` above, you can hold
    /// the tokens in a string literal:
    ///
    /// ```ignore
    /// #[example(bound = "where T: Deserialize<'de>, D: 'static")]
    /// ```
    ///
    /// Then parse
    fn from_invalid_expr(value: &MetaNameValueInvalidExpr) -> Result<Self> {
        Err(value.error.clone())
    }

    /// Create an instance from a char literal in a value position.
    #[allow(unused_variables)]
    fn from_char(value: char) -> Result<Self> {
        Err(Error::unexpected_type("char"))
    }

    /// Create an instance from a string literal in a value position.
    #[allow(unused_variables)]
    fn from_string(value: &str) -> Result<Self> {
        Err(Error::unexpected_type("string"))
    }

    /// Create an instance from a bool literal in a value position.
    #[allow(unused_variables)]
    fn from_bool(value: bool) -> Result<Self> {
        Err(Error::unexpected_type("bool"))
    }
}

// FromMeta impls for std and syn types.

impl FromMeta for () {
    fn from_word() -> Result<Self> {
        Ok(())
    }

    fn from_list(items: &[NestedMeta]) -> Result<Self> {
        let mut errors = Error::accumulator();
        for item in items {
            errors.push(match item {
                // Use `unknown_field_path` rather than `too_many_items` so that when this is used with
                // `flatten` the resulting error message will include the valid fields rather than a confusing
                // message about having only expected zero items.
                //
                // The accumulator is used to ensure all these errors are returned at once, rather than
                // only producing an error on the first unexpected field in the flattened list.
                NestedMeta::Meta(meta) => Error::unknown_field_path(meta.path()).with_span(meta),
                NestedMeta::NameValueInvalidExpr(meta) => {
                    Error::unknown_field_path(&meta.path).with_span(&meta.path.span())
                }
                NestedMeta::Lit(lit) => {
                    Error::unexpected_expr_type(&syn::Expr::Lit(syn::ExprLit {
                        attrs: vec![],
                        lit: lit.clone(),
                    }))
                    .with_span(lit)
                }
            });
        }

        errors.finish()
    }
}

impl FromMeta for bool {
    fn from_word() -> Result<Self> {
        Ok(true)
    }

    #[allow(clippy::wrong_self_convention)] // false positive
    fn from_bool(value: bool) -> Result<Self> {
        Ok(value)
    }

    fn from_string(value: &str) -> Result<Self> {
        value.parse().map_err(|_| Error::unknown_value(value))
    }
}

impl FromMeta for AtomicBool {
    fn from_meta(mi: &Meta) -> Result<Self> {
        FromMeta::from_meta(mi)
            .map(AtomicBool::new)
            .map_err(|e| e.with_span(mi))
    }
}

impl FromMeta for char {
    #[allow(clippy::wrong_self_convention)] // false positive
    fn from_char(value: char) -> Result<Self> {
        Ok(value)
    }

    fn from_string(s: &str) -> Result<Self> {
        let mut chars = s.chars();
        let char1 = chars.next();
        let char2 = chars.next();

        if let (Some(char), None) = (char1, char2) {
            Ok(char)
        } else {
            Err(Error::unexpected_type("string"))
        }
    }
}

impl FromMeta for String {
    fn from_string(s: &str) -> Result<Self> {
        Ok(s.to_string())
    }
}

impl FromMeta for std::path::PathBuf {
    fn from_string(s: &str) -> Result<Self> {
        Ok(s.into())
    }
}

/// Generate an impl of `FromMeta` that will accept strings which parse to numbers or
/// integer literals.
macro_rules! from_meta_num {
    ($ty:path) => {
        impl FromMeta for $ty {
            fn from_string(s: &str) -> Result<Self> {
                s.parse().map_err(|_| Error::unknown_value(s))
            }

            fn from_value(value: &Lit) -> Result<Self> {
                (match *value {
                    Lit::Str(ref s) => Self::from_string(&s.value()),
                    Lit::Int(ref s) => s.base10_parse::<$ty>().map_err(Error::from),
                    _ => Err(Error::unexpected_lit_type(value)),
                })
                .map_err(|e| e.with_span(value))
            }
        }
    };
}

from_meta_num!(u8);
from_meta_num!(u16);
from_meta_num!(u32);
from_meta_num!(u64);
from_meta_num!(u128);
from_meta_num!(usize);
from_meta_num!(i8);
from_meta_num!(i16);
from_meta_num!(i32);
from_meta_num!(i64);
from_meta_num!(i128);
from_meta_num!(isize);
from_meta_num!(num::NonZeroU8);
from_meta_num!(num::NonZeroU16);
from_meta_num!(num::NonZeroU32);
from_meta_num!(num::NonZeroU64);
from_meta_num!(num::NonZeroU128);
from_meta_num!(num::NonZeroUsize);
from_meta_num!(num::NonZeroI8);
from_meta_num!(num::NonZeroI16);
from_meta_num!(num::NonZeroI32);
from_meta_num!(num::NonZeroI64);
from_meta_num!(num::NonZeroI128);
from_meta_num!(num::NonZeroIsize);

/// Generate an impl of `FromMeta` that will accept strings which parse to floats or
/// float literals.
macro_rules! from_meta_float {
    ($ty:ident) => {
        impl FromMeta for $ty {
            fn from_string(s: &str) -> Result<Self> {
                s.parse().map_err(|_| Error::unknown_value(s))
            }

            fn from_value(value: &Lit) -> Result<Self> {
                (match *value {
                    Lit::Str(ref s) => Self::from_string(&s.value()),
                    Lit::Float(ref s) => s.base10_parse::<$ty>().map_err(Error::from),
                    _ => Err(Error::unexpected_lit_type(value)),
                })
                .map_err(|e| e.with_span(value))
            }
        }
    };
}

from_meta_float!(f32);
from_meta_float!(f64);

/// Parsing support for punctuated. This attempts to preserve span information
/// when available, but also supports parsing strings with the call site as the
/// emitted span.
impl<T: syn::parse::Parse, P: syn::parse::Parse> FromMeta for syn::punctuated::Punctuated<T, P> {
    fn from_value(value: &Lit) -> Result<Self> {
        if let Lit::Str(ref ident) = *value {
            ident
                .parse_with(syn::punctuated::Punctuated::parse_terminated)
                .map_err(|_| Error::unknown_lit_str_value(ident))
        } else {
            Err(Error::unexpected_lit_type(value))
        }
    }
}

/// Support for arbitrary expressions as values in a meta item.
///
/// For backwards-compatibility to versions of `darling` based on `syn` 1,
/// string literals will be "unwrapped" and their contents will be parsed
/// as an expression.
///
/// See [`util::parse_expr`](crate::util::parse_expr) for functions to provide
/// alternate parsing modes for this type.
impl FromMeta for syn::Expr {
    fn from_expr(expr: &Expr) -> Result<Self> {
        match expr {
            Expr::Lit(syn::ExprLit {
                lit: lit @ syn::Lit::Str(_),
                ..
            }) => Self::from_value(lit),
            Expr::Group(group) => Self::from_expr(&group.expr), // see FromMeta::from_expr
            _ => Ok(expr.clone()),
        }
    }

    fn from_string(value: &str) -> Result<Self> {
        syn::parse_str(value).map_err(|_| Error::unknown_value(value))
    }

    fn from_value(value: &::syn::Lit) -> Result<Self> {
        if let ::syn::Lit::Str(ref v) = *value {
            v.parse::<syn::Expr>()
                .map_err(|_| Error::unknown_lit_str_value(v))
        } else {
            Err(Error::unexpected_lit_type(value))
        }
    }
}

/// Parser for paths that supports both quote-wrapped and bare values.
impl FromMeta for syn::Path {
    fn from_string(value: &str) -> Result<Self> {
        syn::parse_str(value).map_err(|_| Error::unknown_value(value))
    }

    fn from_value(value: &::syn::Lit) -> Result<Self> {
        if let ::syn::Lit::Str(ref v) = *value {
            v.parse().map_err(|_| Error::unknown_lit_str_value(v))
        } else {
            Err(Error::unexpected_lit_type(value))
        }
    }

    fn from_expr(expr: &Expr) -> Result<Self> {
        match expr {
            Expr::Lit(lit) => Self::from_value(&lit.lit),
            Expr::Path(path) => Ok(path.path.clone()),
            Expr::Group(group) => Self::from_expr(&group.expr), // see FromMeta::from_expr
            _ => Err(Error::unexpected_expr_type(expr)),
        }
    }
}

impl FromMeta for syn::Ident {
    fn from_string(value: &str) -> Result<Self> {
        syn::parse_str(value).map_err(|_| Error::unknown_value(value))
    }

    fn from_value(value: &syn::Lit) -> Result<Self> {
        if let syn::Lit::Str(ref v) = *value {
            v.parse().map_err(|_| Error::unknown_lit_str_value(v))
        } else {
            Err(Error::unexpected_lit_type(value))
        }
    }

    fn from_expr(expr: &Expr) -> Result<Self> {
        match expr {
            Expr::Lit(lit) => Self::from_value(&lit.lit),
            // All idents are paths, but not all paths are idents -
            // the get_ident() method does additional validation to
            // make sure the path is actually an ident.
            Expr::Path(path) => match path.path.get_ident() {
                Some(ident) => Ok(ident.clone()),
                None => Err(Error::unexpected_expr_type(expr)),
            },
            Expr::Group(group) => Self::from_expr(&group.expr), // see FromMeta::from_expr
            _ => Err(Error::unexpected_expr_type(expr)),
        }
    }
}

/// Adapter for various expression types.
///
/// Prior to syn 2.0, darling supported arbitrary expressions as long as they
/// were wrapped in quotation marks. This was helpful for people writing
/// libraries that needed expressions, but it now creates an ambiguity when
/// parsing a meta item.
///
/// To address this, the macro supports both formats; if it cannot parse the
/// item as an expression of the right type and the passed-in expression is
/// a string literal, it will fall back to parsing the string contents.
macro_rules! from_syn_expr_type {
    ($ty:path, $variant:ident) => {
        impl FromMeta for $ty {
            fn from_expr(expr: &syn::Expr) -> Result<Self> {
                match expr {
                    syn::Expr::$variant(body) => Ok(body.clone()),
                    syn::Expr::Lit(expr_lit) => Self::from_value(&expr_lit.lit),
                    syn::Expr::Group(group) => Self::from_expr(&group.expr), // see FromMeta::from_expr
                    _ => Err(Error::unexpected_expr_type(expr)),
                }
            }

            fn from_value(value: &::syn::Lit) -> Result<Self> {
                if let syn::Lit::Str(body) = &value {
                    body.parse::<$ty>()
                        .map_err(|_| Error::unknown_lit_str_value(body))
                } else {
                    Err(Error::unexpected_lit_type(value))
                }
            }
        }
    };
}

from_syn_expr_type!(syn::ExprArray, Array);
from_syn_expr_type!(syn::ExprPath, Path);
from_syn_expr_type!(syn::ExprRange, Range);

/// Adapter from `syn::parse::Parse` to `FromMeta` for items that cannot
/// be expressed in a [`syn::MetaNameValue`].
///
/// This cannot be a blanket impl, due to the `syn::Lit` family's need to handle non-string values.
/// Therefore, we use a macro and a lot of impls.
macro_rules! from_syn_parse {
    ($ty:path) => {
        impl FromMeta for $ty {
            fn from_string(value: &str) -> Result<Self> {
                syn::parse_str(value).map_err(|_| Error::unknown_value(value))
            }

            fn from_value(value: &::syn::Lit) -> Result<Self> {
                if let ::syn::Lit::Str(ref v) = *value {
                    v.parse::<$ty>()
                        .map_err(|_| Error::unknown_lit_str_value(v))
                } else {
                    Err(Error::unexpected_lit_type(value))
                }
            }

            fn from_expr(expr: &Expr) -> Result<Self> {
                match *expr {
                    Expr::Lit(ref lit) => Self::from_value(&lit.lit),
                    Expr::Group(ref group) => {
                        // syn may generate this invisible group delimiter when the input to the darling
                        // proc macro (specifically, the attributes) are generated by a
                        // macro_rules! (e.g. propagating a macro_rules!'s expr)
                        // Since we want to basically ignore these invisible group delimiters,
                        // we just propagate the call to the inner expression.
                        Self::from_expr(&group.expr)
                    }
                    // Parse valid expressions as this type T implementing Parse instead.
                    // For example, `_` is both an expression and a type. Parse it as a type.
                    _ => Ok(syn::parse2(expr.into_token_stream().clone())?),
                }
                .map_err(|e| e.with_span(expr))
            }

            fn from_invalid_expr(value: &MetaNameValueInvalidExpr) -> Result<Self> {
                syn::parse2(value.value.clone()).map_err(Into::into)
            }
        }
    };
}

from_syn_parse!(syn::Type);
from_syn_parse!(syn::TypeArray);
from_syn_parse!(syn::TypeFnPtr);
from_syn_parse!(syn::TypeGroup);
from_syn_parse!(syn::TypeImplTrait);
from_syn_parse!(syn::TypeInfer);
from_syn_parse!(syn::TypeMacro);
from_syn_parse!(syn::TypeNever);
from_syn_parse!(syn::TypeParam);
from_syn_parse!(syn::TypeParen);
from_syn_parse!(syn::TypePtr);
from_syn_parse!(syn::TypeReference);
from_syn_parse!(syn::TypeSlice);
from_syn_parse!(syn::TypeTraitObject);
from_syn_parse!(syn::TypeTuple);
from_syn_parse!(syn::Visibility);
from_syn_parse!(syn::WhereClause);

impl FromMeta for syn::TypePath {
    /// Supports both quote-wrapped and bare values.
    fn from_expr(expr: &Expr) -> Result<Self> {
        match expr {
            Expr::Path(body) => {
                if body.attrs.is_empty() {
                    Ok(syn::TypePath {
                        attrs: vec![],
                        qself: body.qself.clone(),
                        path: body.path.clone(),
                    })
                } else {
                    Err(Error::custom("attributes are not allowed").with_span(body))
                }
            }
            Expr::Lit(expr_lit) => Self::from_value(&expr_lit.lit),
            Expr::Group(group) => Self::from_expr(&group.expr),
            _ => Err(Error::unexpected_expr_type(expr)),
        }
    }

    fn from_string(value: &str) -> Result<Self> {
        syn::parse_str(value).map_err(|_| Error::unknown_value(value))
    }

    fn from_value(value: &Lit) -> Result<Self> {
        if let Lit::Str(ref v) = *value {
            v.parse().map_err(|_| Error::unknown_lit_str_value(v))
        } else {
            Err(Error::unexpected_lit_type(value))
        }
    }
}

macro_rules! from_numeric_array {
    ($ty:ident) => {
        /// Parsing an unsigned integer array, i.e. `example = "[1, 2, 3, 4]"`.
        impl FromMeta for Vec<$ty> {
            fn from_expr(expr: &syn::Expr) -> Result<Self> {
                match expr {
                    syn::Expr::Array(expr_array) => expr_array
                        .elems
                        .iter()
                        .map(|expr| {
                            let unexpected = || {
                                Error::custom("Expected array of unsigned integers").with_span(expr)
                            };
                            match expr {
                                Expr::Lit(lit) => $ty::from_value(&lit.lit),
                                Expr::Group(group) => match &*group.expr {
                                    Expr::Lit(lit) => $ty::from_value(&lit.lit),
                                    _ => Err(unexpected()),
                                },
                                _ => Err(unexpected()),
                            }
                        })
                        .collect::<Result<Vec<$ty>>>(),
                    syn::Expr::Lit(expr_lit) => Self::from_value(&expr_lit.lit),
                    syn::Expr::Group(group) => Self::from_expr(&group.expr), // see FromMeta::from_expr
                    _ => Err(Error::unexpected_expr_type(expr)),
                }
            }

            fn from_value(value: &Lit) -> Result<Self> {
                let expr_array = syn::ExprArray::from_value(value)?;
                Self::from_expr(&syn::Expr::Array(expr_array))
            }
        }
    };
}

from_numeric_array!(u8);
from_numeric_array!(u16);
from_numeric_array!(u32);
from_numeric_array!(u64);
from_numeric_array!(usize);

impl FromMeta for syn::Lit {
    fn from_value(value: &Lit) -> Result<Self> {
        Ok(value.clone())
    }
}

macro_rules! from_meta_lit {
    ($impl_ty:path, $lit_variant:path) => {
        impl FromMeta for $impl_ty {
            fn from_value(value: &Lit) -> Result<Self> {
                if let $lit_variant(ref value) = *value {
                    Ok(value.clone())
                } else {
                    Err(Error::unexpected_lit_type(value))
                }
            }
        }

        impl FromMeta for Vec<$impl_ty> {
            fn from_list(items: &[NestedMeta]) -> Result<Self> {
                items
                    .iter()
                    .map(<$impl_ty as FromMeta>::from_nested_meta)
                    .collect()
            }

            fn from_value(value: &syn::Lit) -> Result<Self> {
                let expr_array = syn::ExprArray::from_value(value)?;
                Self::from_expr(&syn::Expr::Array(expr_array))
            }

            fn from_expr(expr: &syn::Expr) -> Result<Self> {
                match expr {
                    syn::Expr::Array(expr_array) => expr_array
                        .elems
                        .iter()
                        .map(<$impl_ty as FromMeta>::from_expr)
                        .collect::<Result<Vec<_>>>(),
                    syn::Expr::Lit(expr_lit) => Self::from_value(&expr_lit.lit),
                    syn::Expr::Group(g) => Self::from_expr(&g.expr),
                    _ => Err(Error::unexpected_expr_type(expr)),
                }
            }
        }
    };
}

from_meta_lit!(syn::LitInt, Lit::Int);
from_meta_lit!(syn::LitFloat, Lit::Float);
from_meta_lit!(syn::LitStr, Lit::Str);
from_meta_lit!(syn::LitByte, Lit::Byte);
from_meta_lit!(syn::LitByteStr, Lit::ByteStr);
from_meta_lit!(syn::LitChar, Lit::Char);
from_meta_lit!(syn::LitBool, Lit::Bool);
from_meta_lit!(proc_macro2::Literal, Lit::Verbatim);

impl FromMeta for syn::Meta {
    fn from_meta(value: &syn::Meta) -> Result<Self> {
        Ok(value.clone())
    }
}

impl FromMeta for Vec<syn::WherePredicate> {
    fn from_string(value: &str) -> Result<Self> {
        syn::WhereClause::from_string(&format!("where {}", value))
            .map(|c| c.predicates.into_iter().collect())
    }

    fn from_value(value: &Lit) -> Result<Self> {
        if let syn::Lit::Str(s) = value {
            syn::WhereClause::from_value(&syn::Lit::Str(syn::LitStr::new(
                &format!("where {}", s.value()),
                value.span(),
            )))
            .map(|c| c.predicates.into_iter().collect())
        } else {
            Err(Error::unexpected_lit_type(value))
        }
    }
}

impl FromMeta for ident_case::RenameRule {
    fn from_string(value: &str) -> Result<Self> {
        value.parse().map_err(|_| Error::unknown_value(value))
    }
}

impl<T: FromMeta> FromMeta for Option<T> {
    fn from_none() -> Option<Self> {
        Some(None)
    }

    fn from_meta(item: &Meta) -> Result<Self> {
        FromMeta::from_meta(item).map(Some)
    }
}

impl<T: FromMeta> FromMeta for Result<T> {
    fn from_none() -> Option<Self> {
        T::from_none().map(Ok)
    }

    // `#[darling(flatten)]` forwards directly to this method, so it's
    // necessary to declare it to avoid getting an unsupported format
    // error if it's invoked directly.
    fn from_list(items: &[NestedMeta]) -> Result<Self> {
        Ok(FromMeta::from_list(items))
    }

    fn from_meta(item: &Meta) -> Result<Self> {
        Ok(FromMeta::from_meta(item))
    }
}

/// Create an impl that forwards to an inner type `T` for parsing.
macro_rules! smart_pointer_t {
    ($ty:path, $map_fn:path) => {
        impl<T: FromMeta> FromMeta for $ty {
            fn from_none() -> Option<Self> {
                T::from_none().map($map_fn)
            }

            // `#[darling(flatten)]` forwards directly to this method, so it's
            // necessary to declare it to avoid getting an unsupported format
            // error if it's invoked directly.
            fn from_list(items: &[NestedMeta]) -> Result<Self> {
                FromMeta::from_list(items).map($map_fn)
            }

            fn from_meta(item: &Meta) -> Result<Self> {
                FromMeta::from_meta(item).map($map_fn)
            }
        }
    };
}

smart_pointer_t!(Box<T>, Box::new);
smart_pointer_t!(Rc<T>, Rc::new);
smart_pointer_t!(Arc<T>, Arc::new);
smart_pointer_t!(RefCell<T>, RefCell::new);

/// Parses the meta-item, and in case of error preserves a copy of the input for
/// later analysis.
impl<T: FromMeta> FromMeta for ::std::result::Result<T, Meta> {
    fn from_meta(item: &Meta) -> Result<Self> {
        T::from_meta(item)
            .map(Ok)
            .or_else(|_| Ok(Err(item.clone())))
    }
}

/// Trait to convert from a path into an owned key for a map.
trait KeyFromPath: Sized {
    fn from_path(path: &syn::Path) -> Result<Self>;
    fn to_display(&self) -> Cow<'_, str>;
}

impl KeyFromPath for String {
    fn from_path(path: &syn::Path) -> Result<Self> {
        Ok(path_to_string(path))
    }

    fn to_display(&self) -> Cow<'_, str> {
        Cow::Borrowed(self)
    }
}

impl KeyFromPath for syn::Path {
    fn from_path(path: &syn::Path) -> Result<Self> {
        Ok(path.clone())
    }

    fn to_display(&self) -> Cow<'_, str> {
        Cow::Owned(path_to_string(self))
    }
}

impl KeyFromPath for syn::Ident {
    fn from_path(path: &syn::Path) -> Result<Self> {
        if path.segments.len() == 1
            && path.leading_colon.is_none()
            && path.segments[0].arguments.is_empty()
        {
            Ok(path.segments[0].ident.clone())
        } else {
            Err(Error::custom("Key must be an identifier").with_span(path))
        }
    }

    fn to_display(&self) -> Cow<'_, str> {
        Cow::Owned(self.to_string())
    }
}

macro_rules! map {
    (hash_map, $key:ty, $nested:ident) => {
        impl<V: FromMeta, S: BuildHasher + Default> FromMeta for HashMap<$key, V, S> {
            map!(
                HashMap::with_capacity_and_hasher($nested.len(), Default::default()),
                $key,
                $nested
            );
        }
    };

    (btree_map, $key:ty, $nested:ident) => {
        impl<V: FromMeta> FromMeta for BTreeMap<$key, V> {
            map!(BTreeMap::new(), $key, $nested);
        }
    };

    ($new:expr, $key:ty, $nested:ident) => {
        fn from_list($nested: &[NestedMeta]) -> Result<Self> {
            // Convert the nested meta items into a sequence of (path, value result) result tuples.
            // An outer Err means no (key, value) structured could be found, while an Err in the
            // second position of the tuple means that value was rejected by FromMeta.
            //
            // We defer key conversion into $key so that we don't lose span information in the case
            // of String keys; we'll need it for good duplicate key errors later.
            let pairs = $nested
                .iter()
                .map(|item| -> Result<(&syn::Path, Result<V>)> {
                    match *item {
                        NestedMeta::Meta(ref inner) => {
                            let path = inner.path();
                            Ok((
                                path,
                                FromMeta::from_meta(inner).map_err(|e| e.at_path(&path)),
                            ))
                        }
                        NestedMeta::NameValueInvalidExpr(ref inner) => Ok((
                            &inner.path,
                            FromMeta::from_invalid_expr(inner).map_err(|e| e.at_path(&inner.path)),
                        )),
                        NestedMeta::Lit(_) => Err(Error::unsupported_format("expression")),
                    }
                });

            let mut errors = Error::accumulator();
            // We need to track seen keys separately from the final map, since a seen key with an
            // Err value won't go into the final map but should trigger a duplicate field error.
            //
            // This is a set of $key rather than Path to avoid the possibility that a key type
            // parses two paths of different values to the same key value.
            let mut seen_keys = HashSet::with_capacity($nested.len());

            // The map to return in the Ok case. Its size will always be exactly nested.len(),
            // since otherwise ≥1 field had a problem and the entire map is dropped immediately
            // when the function returns `Err`.
            let mut map = $new;

            for item in pairs {
                if let Some((path, value)) = errors.handle(item) {
                    let key: $key = match KeyFromPath::from_path(path) {
                        Ok(k) => k,
                        Err(e) => {
                            errors.push(e);

                            // Surface value errors even under invalid keys
                            errors.handle(value);

                            continue;
                        }
                    };

                    let already_seen = seen_keys.contains(&key);

                    if already_seen {
                        errors.push(Error::duplicate_field(&key.to_display()).with_span(path));
                    }

                    match value {
                        Ok(_) if already_seen => {}
                        Ok(val) => {
                            map.insert(key.clone(), val);
                        }
                        Err(e) => {
                            errors.push(e);
                        }
                    }

                    seen_keys.insert(key);
                }
            }

            errors.finish_with(map)
        }
    };
}

// This is done as a macro rather than a blanket impl to avoid breaking backwards compatibility
// with 0.12.x, while still sharing the same impl.
map!(hash_map, String, nested);
map!(hash_map, syn::Ident, nested);
map!(hash_map, syn::Path, nested);

map!(btree_map, String, nested);
map!(btree_map, syn::Ident, nested);

#[doc(hidden)]
/// Autoref specialization to allow using `.from_none()` on types `T` implementing
/// `FromMeta` to get `Option<T>`,  and on other types always getting `None`
///
/// This is used inside the `#[derive(FromMeta)]` impl, see
/// issue: <https://github.com/TedDriggs/darling/issues/305>
///
/// # How it works
///
/// When using method call syntax, if Rust can't find the method, then Rust will
/// insert an extra reference `&` and try again.
///
/// This allows a form of "specialization", which can't be used in a generic context
/// BUT it can be used with "concrete" types that are known at compile time.
///
/// This is only useful inside of macros.
///
/// This is known as "autoref specialization", more information can be found here:
/// <https://github.com/dtolnay/case-studies/tree/master/autoref-specialization>
///
/// # Usage
///
/// ```ignore
/// use _darling::autoref_specialization::{
///     SpecFromMeta as _,
///     SpecFromMetaAll as _
/// };
///
/// let x = (&_darling::export::PhantomData::<T>).tag().from_none()
/// ```
///
/// If `T` implements `FromMeta`, `x` will be `T::from_meta()` (an `Option<T>`)
/// because `(&PhantomData::<T>).tag()` selects the `SpecFromMeta` trait impl, and evaluates to `FromMetaTag`,
/// which then calls `FromMetaTag::<T>.from_none()` getting us the value of `T`.
///
/// Otherwise, if `T` does not implement `FromMeta`, `x` will always be `None` because
/// `(&PhantomData::<T>).tag()` selects the `SpecFromMetaAll` trait impl, and evaluates to `FromMetaTagAll`,
/// which then calls `FromMetaTagAll::<T>.from_none()` which always just returns `None`.
///
/// The `PhantomData` must be there because we must use exactly method call syntax, so the function
/// must take `self`, but we don't have an instantiation of `T`, we just have the type. Usually
/// auto-ref specialization works on concrete expressions.
#[allow(clippy::wrong_self_convention)]
pub mod autoref_specialization {
    use super::FromMeta;
    use std::marker::PhantomData;

    pub struct FromMetaTag<T>(PhantomData<T>);
    pub struct FromMetaTagAll<T>(PhantomData<T>);

    impl<T: FromMeta> FromMetaTag<T> {
        pub fn from_none(self) -> Option<T> {
            T::from_none()
        }
    }

    impl<T> FromMetaTagAll<T> {
        pub fn from_none(self) -> Option<T> {
            None
        }
    }

    pub trait SpecFromMeta<T>: Sized {
        fn tag(self) -> FromMetaTag<T> {
            FromMetaTag(PhantomData)
        }
    }

    pub trait SpecFromMetaAll<T>: Sized {
        fn tag(self) -> FromMetaTagAll<T> {
            FromMetaTagAll(PhantomData)
        }
    }

    // Less specific than the next impl, so this will get
    // selected if the next impl isn't because Rust will add a `&`
    // and try again
    impl<T> SpecFromMetaAll<T> for &&PhantomData<T> {}

    impl<T: FromMeta> SpecFromMeta<T> for &PhantomData<T> {}
}

impl FromMeta for Vec<Ident> {
    fn from_list(nested: &[NestedMeta]) -> Result<Self> {
        let items = nested.iter().map(|item| match *item {
            NestedMeta::Meta(ref inner) => Ok(inner.require_path_only()?.require_ident()?),
            NestedMeta::NameValueInvalidExpr(_) | NestedMeta::Lit(_) => {
                Err(Error::unsupported_format("expression"))
            }
        });

        let mut errors = Error::accumulator();

        let list = items
            .filter_map(|item| errors.handle(item))
            .cloned()
            .collect();

        errors.finish_with(list)
    }
}

impl FromMeta for Vec<Path> {
    fn from_list(nested: &[NestedMeta]) -> Result<Self> {
        let items = nested.iter().map(|item| match *item {
            NestedMeta::Meta(ref inner) => Ok(inner.require_path_only()?),
            NestedMeta::NameValueInvalidExpr(_) | NestedMeta::Lit(_) => {
                Err(Error::unsupported_format("expression"))
            }
        });

        let mut errors = Error::accumulator();

        let list = items
            .filter_map(|item| errors.handle(item))
            .cloned()
            .collect();

        errors.finish_with(list)
    }
}

impl FromMeta for HashSet<Ident> {
    fn from_list(nested: &[NestedMeta]) -> Result<Self> {
        let items = nested.iter().map(|item| match *item {
            NestedMeta::Meta(ref inner) => Ok(inner.require_path_only()?.require_ident()?),
            NestedMeta::NameValueInvalidExpr(_) | NestedMeta::Lit(_) => {
                Err(Error::unsupported_format("expression"))
            }
        });

        let mut errors = Error::accumulator();
        let mut list = HashSet::with_capacity(nested.len());

        for item in items {
            let Some(item) = errors.handle(item) else {
                continue;
            };
            if !list.insert(item.clone()) {
                errors.push(Error::duplicate_field(&item.to_string()).with_span(item))
            };
        }

        errors.finish_with(list)
    }
}

impl FromMeta for HashSet<Path> {
    fn from_list(nested: &[NestedMeta]) -> Result<Self> {
        let items = nested.iter().map(|item| match *item {
            NestedMeta::Meta(ref inner) => Ok(inner.require_path_only()?),
            NestedMeta::NameValueInvalidExpr(_) | NestedMeta::Lit(_) => {
                Err(Error::unsupported_format("expression"))
            }
        });

        let mut errors = Error::accumulator();
        let mut list = HashSet::with_capacity(nested.len());

        for item in items {
            let Some(item) = errors.handle(item) else {
                continue;
            };
            if !list.insert(item.clone()) {
                errors.push(Error::duplicate_field(&path_to_string(item)).with_span(item))
            };
        }

        errors.finish_with(list)
    }
}

/// Tests for `FromMeta` implementations. Wherever the word `ignore` appears in test input,
/// it should not be considered by the parsing.
#[cfg(test)]
mod tests {
    use std::{
        collections::HashSet,
        fmt::Debug,
        num::{NonZeroU32, NonZeroU64},
    };

    use proc_macro2::TokenStream;
    use quote::quote;
    use syn::{
        parse_quote, Ident, Path, Type, TypeArray, TypeFnPtr, TypeImplTrait, TypeInfer, TypeNever,
        TypeParen, TypePtr, TypeReference, TypeSlice, TypeTraitObject, TypeTuple, Visibility,
        WhereClause,
    };

    use crate::{Error, FromMeta, Result};

    #[track_caller]
    fn test_type<T: FromMeta + PartialEq + Debug>(tokens: TokenStream, f: fn(T) -> Type) {
        // Should work if the type is in a string literal
        let tokens_str = tokens.to_string();
        let t1 = pnm::<T>(tokens.clone()).expect("1");
        let t2 = pnm::<T>(quote! { #tokens_str }).expect("2");
        let type1 = pnm::<Type>(tokens).expect("3");
        let type2 = pnm::<Type>(quote! { #tokens_str }).expect("4");

        assert_eq!(t1, t2, "5");
        assert_eq!(type1, type2, "6");
        assert_eq!(f(t1), type1, "7");
        assert_eq!(f(t2), type1, "8");
    }

    /// parse a string as a syn::Meta instance.
    fn pm(tokens: TokenStream) -> ::std::result::Result<syn::Meta, String> {
        let attribute: syn::Attribute = parse_quote!(#[#tokens]);
        Ok(attribute.meta)
    }

    /// assert that this value parses into NestedMeta
    #[track_caller]
    fn pnm<T: FromMeta>(ts: TokenStream) -> Result<T> {
        T::from_nested_meta(&parse_quote!(ignore = #ts))
    }

    #[track_caller]
    fn fm<T: FromMeta>(tokens: TokenStream) -> T {
        FromMeta::from_meta(&pm(tokens).expect("Tests should pass well-formed input"))
            .expect("Tests should pass valid input")
    }

    #[test]
    fn unit_succeeds() {
        fm::<()>(quote!(ignore));
        fm::<()>(quote!(ignore()));
    }

    #[test]
    #[should_panic(expected = "UnknownField")]
    fn unit_fails() {
        fm::<()>(quote!(ignore(foo = "bar")));
    }

    #[test]
    #[allow(clippy::bool_assert_comparison)]
    fn bool_succeeds() {
        // word format
        assert_eq!(fm::<bool>(quote!(ignore)), true);

        // bool literal
        assert_eq!(fm::<bool>(quote!(ignore = true)), true);
        assert_eq!(fm::<bool>(quote!(ignore = false)), false);

        // string literals
        assert_eq!(fm::<bool>(quote!(ignore = "true")), true);
        assert_eq!(fm::<bool>(quote!(ignore = "false")), false);
    }

    #[test]
    fn char_succeeds() {
        // char literal
        assert_eq!(fm::<char>(quote!(ignore = '😬')), '😬');

        // string literal
        assert_eq!(fm::<char>(quote!(ignore = "😬")), '😬');
    }

    #[test]
    fn string_succeeds() {
        // cooked form
        assert_eq!(&fm::<String>(quote!(ignore = "world")), "world");

        // raw form
        assert_eq!(&fm::<String>(quote!(ignore = r#"world"#)), "world");
    }

    #[test]
    fn pathbuf_succeeds() {
        assert_eq!(
            fm::<std::path::PathBuf>(quote!(ignore = r#"C:\"#)),
            std::path::PathBuf::from(r#"C:\"#)
        );
    }

    #[test]
    #[allow(clippy::float_cmp)] // we want exact equality
    fn number_succeeds() {
        assert_eq!(fm::<u8>(quote!(ignore = "2")), 2u8);
        assert_eq!(fm::<i16>(quote!(ignore = "-25")), -25i16);
        assert_eq!(fm::<f64>(quote!(ignore = "1.4e10")), 1.4e10);
    }

    #[should_panic(expected = "UnknownValue")]
    #[test]
    fn nonzero_number_fails() {
        fm::<NonZeroU64>(quote!(ignore = "0"));
    }

    #[test]
    fn nonzero_number_succeeds() {
        assert_eq!(
            fm::<NonZeroU32>(quote!(ignore = "2")),
            NonZeroU32::new(2).unwrap()
        );
    }

    #[test]
    fn int_without_quotes() {
        assert_eq!(fm::<u8>(quote!(ignore = 2)), 2u8);
        assert_eq!(fm::<u16>(quote!(ignore = 255)), 255u16);
        assert_eq!(fm::<u32>(quote!(ignore = 5000)), 5000u32);

        // Check that we aren't tripped up by incorrect suffixes
        assert_eq!(fm::<u32>(quote!(ignore = 5000i32)), 5000u32);
    }

    #[test]
    fn negative_int_without_quotes() {
        assert_eq!(fm::<i8>(quote!(ignore = -2)), -2i8);
        assert_eq!(fm::<i32>(quote!(ignore = -255)), -255i32);
    }

    #[test]
    #[allow(clippy::float_cmp)] // we want exact equality
    fn float_without_quotes() {
        assert_eq!(fm::<f32>(quote!(ignore = 2.)), 2.0f32);
        assert_eq!(fm::<f32>(quote!(ignore = 2.0)), 2.0f32);
        assert_eq!(fm::<f64>(quote!(ignore = 1.4e10)), 1.4e10f64);
    }

    #[test]
    fn too_large_int_produces_error() {
        assert!(fm::<Result<u8>>(quote!(ignore = 2000)).is_err());
    }

    #[test]
    fn meta_succeeds() {
        use syn::Meta;

        assert_eq!(
            fm::<Meta>(quote!(hello(world, today))),
            pm(quote!(hello(world, today))).unwrap()
        );
    }

    #[test]
    fn hash_map_succeeds() {
        use std::collections::HashMap;

        let comparison = {
            let mut c = HashMap::new();
            c.insert("hello".to_string(), true);
            c.insert("world".to_string(), false);
            c.insert("there".to_string(), true);
            c
        };

        assert_eq!(
            fm::<HashMap<String, bool>>(quote!(ignore(hello, world = false, there = "true"))),
            comparison
        );
    }

    /// Check that a `HashMap` cannot have duplicate keys, and that the generated error
    /// is assigned a span to correctly target the diagnostic message.
    #[test]
    fn hash_map_duplicate() {
        use std::collections::HashMap;

        let err: Result<HashMap<String, bool>> =
            FromMeta::from_meta(&pm(quote!(ignore(hello, hello = false))).unwrap());

        let err = err.expect_err("Duplicate keys in HashMap should error");

        assert!(err.has_span());
        assert_eq!(err.to_string(), Error::duplicate_field("hello").to_string());
    }

    #[test]
    fn hash_map_multiple_errors() {
        use std::collections::HashMap;

        let err = HashMap::<String, bool>::from_meta(
            &pm(quote!(ignore(hello, hello = 3, hello = false))).unwrap(),
        )
        .expect_err("Duplicates and bad values should error");

        assert_eq!(err.len(), 3);
        let errors = err.into_iter().collect::<Vec<_>>();
        assert!(errors[0].has_span());
        assert!(errors[1].has_span());
        assert!(errors[2].has_span());
    }

    #[test]
    fn hash_map_ident_succeeds() {
        use std::collections::HashMap;
        use syn::parse_quote;

        let comparison = {
            let mut c = HashMap::<syn::Ident, bool>::new();
            c.insert(parse_quote!(first), true);
            c.insert(parse_quote!(second), false);
            c
        };

        assert_eq!(
            fm::<HashMap<syn::Ident, bool>>(quote!(ignore(first, second = false))),
            comparison
        );
    }

    #[test]
    fn hash_map_ident_rejects_non_idents() {
        use std::collections::HashMap;

        let err: Result<HashMap<syn::Ident, bool>> =
            FromMeta::from_meta(&pm(quote!(ignore(first, the::second))).unwrap());

        err.unwrap_err();
    }

    #[test]
    fn hash_map_path_succeeds() {
        use std::collections::HashMap;
        use syn::parse_quote;

        let comparison = {
            let mut c = HashMap::<syn::Path, bool>::new();
            c.insert(parse_quote!(first), true);
            c.insert(parse_quote!(the::second), false);
            c
        };

        assert_eq!(
            fm::<HashMap<syn::Path, bool>>(quote!(ignore(first, the::second = false))),
            comparison
        );
    }

    #[test]
    fn btree_map_succeeds() {
        use std::collections::BTreeMap;

        let comparison = {
            let mut c = BTreeMap::new();
            c.insert("hello".to_string(), true);
            c.insert("world".to_string(), false);
            c.insert("there".to_string(), true);
            c
        };

        assert_eq!(
            fm::<BTreeMap<String, bool>>(quote!(ignore(hello, world = false, there = "true"))),
            comparison
        );
    }

    /// Check that a `HashMap` cannot have duplicate keys, and that the generated error
    /// is assigned a span to correctly target the diagnostic message.
    #[test]
    fn btree_map_duplicate() {
        use std::collections::BTreeMap;

        let err: Result<BTreeMap<String, bool>> =
            FromMeta::from_meta(&pm(quote!(ignore(hello, hello = false))).unwrap());

        let err = err.expect_err("Duplicate keys in BTreeMap should error");

        assert!(err.has_span());
        assert_eq!(err.to_string(), Error::duplicate_field("hello").to_string());
    }

    #[test]
    fn btree_map_multiple_errors() {
        use std::collections::BTreeMap;

        let err = BTreeMap::<String, bool>::from_meta(
            &pm(quote!(ignore(hello, hello = 3, hello = false))).unwrap(),
        )
        .expect_err("Duplicates and bad values should error");

        assert_eq!(err.len(), 3);
        let errors = err.into_iter().collect::<Vec<_>>();
        assert!(errors[0].has_span());
        assert!(errors[1].has_span());
        assert!(errors[2].has_span());
    }

    #[test]
    fn btree_map_ident_succeeds() {
        use std::collections::BTreeMap;
        use syn::parse_quote;

        let comparison = {
            let mut c = BTreeMap::<syn::Ident, bool>::new();
            c.insert(parse_quote!(first), true);
            c.insert(parse_quote!(second), false);
            c
        };

        assert_eq!(
            fm::<BTreeMap<syn::Ident, bool>>(quote!(ignore(first, second = false))),
            comparison
        );
    }

    #[test]
    fn btree_map_ident_rejects_non_idents() {
        use std::collections::BTreeMap;

        let err: Result<BTreeMap<syn::Ident, bool>> =
            FromMeta::from_meta(&pm(quote!(ignore(first, the::second))).unwrap());

        err.unwrap_err();
    }

    #[test]
    fn btree_map_expr_values_succeed() {
        use std::collections::BTreeMap;
        use syn::parse_quote;

        let comparison: BTreeMap<String, syn::Expr> = vec![
            ("hello", parse_quote!(2 + 2)),
            ("world", parse_quote!(x.foo())),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v))
        .collect();

        assert_eq!(
            fm::<BTreeMap<String, syn::Expr>>(quote!(ignore(hello = 2 + 2, world = x.foo()))),
            comparison
        );
    }

    #[test]
    fn vec_ident_succeeds() {
        let input: Vec<Ident> = vec![
            parse_quote!(hello),
            parse_quote!(world),
            parse_quote!(there),
        ];

        assert_eq!(fm::<Vec<Ident>>(quote!(ignore(hello, world, there))), input);
    }

    #[test]
    fn vec_ident_allows_duplicates() {
        let input: Vec<Ident> = vec![parse_quote!(hello), parse_quote!(hello)];

        assert_eq!(fm::<Vec<Ident>>(quote!(ignore(hello, hello))), input);
    }

    #[test]
    fn vec_ident_rejects_paths() {
        let result: Result<Vec<Ident>> =
            FromMeta::from_meta(&pm(quote!(ignore(the::world))).unwrap());

        result.unwrap_err();
    }

    #[test]
    fn vec_path_succeeds() {
        let input = vec![parse_quote!(hello), parse_quote!(the::world)];

        assert_eq!(
            fm::<Vec<syn::Path>>(quote!(ignore(hello, the::world))),
            input
        );
    }

    #[test]
    fn vec_path_allows_duplicates() {
        let input = vec![parse_quote!(hello), parse_quote!(hello)];

        assert_eq!(fm::<Vec<Path>>(quote!(ignore(hello, hello))), input);
    }

    #[test]
    fn hash_set_ident_succeeds() {
        let comparison: HashSet<Ident> = [parse_quote!(hello), parse_quote!(world)].into();

        assert_eq!(
            fm::<HashSet<Ident>>(quote!(ignore(hello, world))),
            comparison
        );
    }

    #[test]
    fn hash_set_ident_duplicate() {
        HashSet::<syn::Ident>::from_meta(&pm(quote!(ignore(hello, hello))).unwrap()).unwrap_err();
    }

    #[test]
    fn hash_set_ident_multiple_errors() {
        let err = HashSet::<syn::Ident>::from_meta(
            &pm(quote!(ignore(hello, hello, the::world))).unwrap(),
        )
        .unwrap_err();

        assert_eq!(err.len(), 2);
    }

    #[test]
    fn hash_set_path_succeeds() {
        let comparison: HashSet<_> = [parse_quote!(hello), parse_quote!(the::world)].into();

        assert_eq!(
            fm::<HashSet<syn::Path>>(quote!(ignore(hello, the::world))),
            comparison
        );
    }

    #[test]
    fn hash_set_path_duplicate() {
        HashSet::<syn::Path>::from_meta(&pm(quote!(ignore(the::world, the::world))).unwrap())
            .unwrap_err();
    }

    /// Tests that fallible parsing will always produce an outer `Ok` (from `fm`),
    /// and will accurately preserve the inner contents.
    #[test]
    fn darling_result_succeeds() {
        fm::<Result<()>>(quote!(ignore)).unwrap();
        fm::<Result<()>>(quote!(ignore(world))).unwrap_err();
    }

    /// Test punctuated
    #[test]
    fn test_punctuated() {
        fm::<syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>>(quote!(
            ignore = "a: u8, b: Type"
        ));
        fm::<syn::punctuated::Punctuated<syn::Expr, syn::token::Comma>>(quote!(ignore = "a, b, c"));
    }

    #[test]
    fn test_expr_array() {
        fm::<syn::ExprArray>(quote!(ignore = "[0x1, 0x2]"));
        fm::<syn::ExprArray>(quote!(ignore = "[\"Hello World\", \"Test Array\"]"));
    }

    #[test]
    fn test_expr() {
        fm::<syn::Expr>(quote!(ignore = "x + y"));
        fm::<syn::Expr>(quote!(ignore = "an_object.method_call()"));
        fm::<syn::Expr>(quote!(ignore = "{ a_statement(); in_a_block }"));
    }

    #[test]
    fn test_expr_without_quotes() {
        fm::<syn::Expr>(quote!(ignore = x + y));
        fm::<syn::Expr>(quote!(ignore = an_object.method_call()));
        fm::<syn::Expr>(quote!(
            ignore = {
                a_statement();
                in_a_block
            }
        ));
    }

    #[test]
    fn test_expr_path() {
        fm::<syn::ExprPath>(quote!(ignore = "std::mem::replace"));
        fm::<syn::ExprPath>(quote!(ignore = "x"));
        fm::<syn::ExprPath>(quote!(ignore = "example::<Test>"));
    }

    #[test]
    fn test_expr_path_without_quotes() {
        fm::<syn::ExprPath>(quote!(ignore = std::mem::replace));
        fm::<syn::ExprPath>(quote!(ignore = x));
        fm::<syn::ExprPath>(quote!(ignore = example::<Test>));
    }

    #[test]
    fn test_path_without_quotes() {
        fm::<syn::Path>(quote!(ignore = std::mem::replace));
        fm::<syn::Path>(quote!(ignore = x));
        fm::<syn::Path>(quote!(ignore = example::<Test>));
    }

    #[test]
    fn test_number_array() {
        assert_eq!(fm::<Vec<u8>>(quote!(ignore = [16, 0xff])), vec![0x10, 0xff]);
        assert_eq!(
            fm::<Vec<u16>>(quote!(ignore = "[32, 0xffff]")),
            vec![0x20, 0xffff]
        );
        assert_eq!(
            fm::<Vec<u32>>(quote!(ignore = "[48, 0xffffffff]")),
            vec![0x30, 0xffffffff]
        );
        assert_eq!(
            fm::<Vec<u64>>(quote!(ignore = "[64, 0xffffffffffffffff]")),
            vec![0x40, 0xffffffffffffffff]
        );
        assert_eq!(
            fm::<Vec<usize>>(quote!(ignore = "[80, 0xffffffff]")),
            vec![0x50, 0xffffffff]
        );
    }

    #[test]
    fn test_lit_array() {
        fm::<Vec<syn::LitStr>>(quote!(ignore = "[\"Hello World\", \"Test Array\"]"));
        fm::<Vec<syn::LitStr>>(quote!(ignore = ["Hello World", "Test Array"]));
        fm::<Vec<syn::LitChar>>(quote!(ignore = "['a', 'b', 'c']"));
        fm::<Vec<syn::LitBool>>(quote!(ignore = "[true]"));
        fm::<Vec<syn::LitStr>>(quote!(ignore = "[]"));
        fm::<Vec<syn::LitStr>>(quote!(ignore = []));
        fm::<Vec<syn::LitBool>>(quote!(ignore = [true, false]));
    }

    #[test]
    fn expr_range_without_quotes() {
        fm::<syn::ExprRange>(quote!(ignore = 0..5));
        fm::<syn::ExprRange>(quote!(ignore = 0..=5));
        fm::<syn::ExprRange>(quote!(ignore = ..5));
        fm::<syn::ExprRange>(quote!(ignore = ..(x + y)));
    }

    #[test]
    fn test_where_clause() {
        pnm::<WhereClause>(quote!(where T: Deserialize<'de>)).unwrap();
        // Must use quotes because this contains a comma. Due to this comma,
        // it thinks that the next value (D: 'static) is a NestedMeta
        pnm::<WhereClause>(quote!("where T: Deserialize<'de>, D: 'static")).unwrap();
    }

    #[test]
    fn test_vis() {
        pnm::<Visibility>(quote!(pub(in crate::module))).unwrap();
        pnm::<Visibility>(quote!(pub)).unwrap();
    }

    #[test]
    fn test_type_array() {
        test_type::<TypeArray>(quote!([u32; 4]), Type::Array);
    }

    #[test]
    fn test_type_infer() {
        test_type::<TypeInfer>(quote!(_), Type::Infer);
    }

    #[test]
    fn test_type_slice() {
        test_type::<TypeSlice>(quote!([u32]), Type::Slice);
    }

    #[test]
    fn test_type_ptr() {
        test_type::<TypePtr>(quote!(*const T), Type::Ptr);
        test_type::<TypePtr>(quote!(*mut T), Type::Ptr);
    }

    #[test]
    fn test_type_trait_object() {
        test_type::<TypeTraitObject>(quote!(dyn Trait), Type::TraitObject);
    }

    #[test]
    fn test_type_never() {
        test_type::<TypeNever>(quote!(!), Type::Never);
    }

    #[test]
    fn test_type_impl_trait() {
        test_type::<TypeImplTrait>(quote!(impl Trait + 'a), Type::ImplTrait);
    }

    #[test]
    fn test_type_tuple() {
        test_type::<TypeTuple>(quote!((u32, i32)), Type::Tuple);
    }

    #[test]
    fn test_type_reference() {
        test_type::<TypeReference>(quote!(&u32), Type::Reference);
        test_type::<TypeReference>(quote!(&'a mut u32), Type::Reference);
    }

    #[test]
    fn test_type_bare_fn() {
        test_type::<TypeFnPtr>(quote!(fn(usize) -> bool), Type::FnPtr);
    }

    #[test]
    fn test_type_paren() {
        test_type::<TypeParen>(quote!((u32)), Type::Paren);
    }
}