struct-path 0.2.9

A helper macros to build a string that represents struct fields path at compile time (such as <field-name>.<field-name>)
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
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
//! A helper macros implementation to build a string that represents struct fields path at compile time.
//!
//! Library provides a tiny macro implementation to reference Rust struct fields at compile time to represent its string format.
//! This is needed to work with JSON paths, and some others protocols when we still want to rely on the compiler to avoid inconsistent changes.
//!
//! Features:
//! - Fast and no macro parsing without huge deps;
//! - Macro produces the code to verify if the specified path really exists;
//! - Multiple fields/arrays support
//! - Optional camelCase and PascalCase conversion support;
//! - Optional delimiter parameter;
//! - `#[derive(StructPath)]` to return all of a struct's declared fields via `Type::*`, without listing them by hand;
//! - `Type::*` nested under a field path, `Parent::child.(Child::*)`, to prefix every one of `Child`'s fields with `child`;
//!
//! Example:
//!
//! ```rust,no_run
//! use struct_path::*;
//!
//! fn example() {
//!
//! pub struct TestStructParent {
//!     pub value_str: String,
//!     pub value_num: u64,
//!     pub value_child: TestStructChild,
//!     pub opt_value_child: Option<TestStructChild>,
//! }
//!
//! pub struct TestStructChild {
//!     pub child_value_str: String,
//!     pub child_value_num: u64,
//! }
//!
//!// returns "value_str"
//!let s1: &str = path!(TestStructParent::value_str);
//!
//!// returns "value_child.child_value_str"
//!let s2: &str = path!(TestStructParent::value_child.child_value_str) ;
//!
//!// returns also "value_child.child_value_str"
//!let s3: &str = path!(TestStructParent::value_child,TestStructChild::child_value_str);
//!
//!// options, returns "valueChild/childValueStr"
//!let s4: &str = path!(TestStructParent::value_child.child_value_str; delim="/", case="camel") ;
//!
//!// `~` steps through a collection field (Vec, Option, ...) while still
//!// verifying the path; returns "optValueChild/childValueStr"
//!let s5: &str = path!(TestStructParent::opt_value_child~child_value_str; delim="/", case="camel") ;
//!
//!// returns ["value_str", "value_num"]
//!let arr: [&str; 2] = paths!(TestStructParent::{ value_str, value_num });
//!
//! }
//!
//! ```
//!
//! All fields with `Type::*`, needing `#[derive(StructPath)]`; none of the calls above need it.
//!
//! ```rust,no_run
//! use struct_path::*;
//!
//! fn example_all_fields() {
//!
//! #[derive(StructPath)]
//! pub struct TestStructWithPrivate {
//!     pub value_str: String,
//!     value_internal: String,
//! }
//!
//!// `Type::*` needs `#[derive(StructPath)]` on `Type`; returns ["value_str"],
//!// only the field declared with plain `pub`
//!let pub_only: [&str; 1] = paths!(TestStructWithPrivate::*);
//!
//!// `visibility="all"` returns every declared field instead
//!let all_fields: [&str; 2] = paths!(TestStructWithPrivate::*; visibility="all");
//!
//! #[derive(StructPath)]
//! pub struct TestStructChild {
//!     pub child_value_str: String,
//!     pub child_value_num: u64,
//! }
//!
//! pub struct TestStructParent {
//!     pub value_child: TestStructChild,
//!     pub opt_value_child: Option<TestStructChild>,
//! }
//!
//!// nested `Type::*`: `TestStructChild` also needs `#[derive(StructPath)]`,
//!// and is named again inside the parens; returns
//!// ["value_child.child_value_str", "value_child.child_value_num"]
//!let nested: [&str; 2] = paths!(TestStructParent::value_child.(TestStructChild::*));
//!
//!// `~` before the parens steps through the `Option` the same way it does
//!// for a single field; returns ["opt_value_child.child_value_str", ...]
//!let nested_opt: [&str; 2] = paths!(TestStructParent::opt_value_child~(TestStructChild::*));
//!
//! }
//!
//! ```
//!

use convert_case::{Case, Casing};
use proc_macro::{Delimiter, Group, Ident, Spacing, Span, TokenStream, TokenTree};
use std::collections::HashMap;

/// Converts a parse-time error into the token stream for a `compile_error!`
/// invocation, so malformed macro input surfaces as a normal compiler error
/// carrying the same message instead of a proc-macro panic.
fn compile_error_for(message: String) -> TokenStream {
    format!("compile_error!({:?})", message)
        .parse()
        .expect("a compile_error! invocation with an escaped string literal always parses")
}

/// Like `compile_error_for`, but for the derive parser, which walks its own
/// item tokens rather than building a `Result<_, String>` message: the error
/// is spanned on the offending token so it is reported there and not at the
/// derive's call site.
fn compile_error_at(message: &str, span: Span) -> TokenStream {
    let mut literal = proc_macro::Literal::string(message);
    literal.set_span(span);
    let message_tokens = TokenStream::from(TokenTree::Literal(literal));
    fill(
        "compile_error!(MESSAGE);",
        span,
        &[("MESSAGE", &message_tokens)],
    )
}

/// The type path and field paths found for one `Type::field[, field...]`
/// group, kept as the user's own tokens so the generated check reports a
/// type error on the exact token that is wrong. A field path holds its
/// idents, `.` and `~` puncts as written; it is the only record kept of the
/// path, so the check and the returned string can never disagree.
type FoundStructs = Vec<(Vec<TokenTree>, Vec<Vec<TokenTree>>)>;

#[proc_macro]
pub fn paths(struct_path_stream: TokenStream) -> TokenStream {
    match paths_impl(struct_path_stream) {
        Ok(stream) => stream,
        Err(message) => compile_error_for(message),
    }
}

fn paths_impl(struct_path_stream: TokenStream) -> Result<TokenStream, String> {
    let top_level_tokens: Vec<TokenTree> = struct_path_stream.clone().into_iter().collect();
    if let Some(result) = try_parse_nested_star(&top_level_tokens) {
        return result;
    }
    if let Some(result) = try_parse_all_fields(&struct_path_stream) {
        return result;
    }

    let mut current_struct_name_tokens: Vec<TokenTree> = Vec::new();
    let mut current_struct_fields: Vec<Vec<TokenTree>> = Vec::with_capacity(16);

    let mut opened_struct = false;
    let mut colons_counter = 0;
    let mut options_opened = false;

    let mut current_field_tokens: Vec<TokenTree> = Vec::new();

    let mut current_option_name: Option<String> = None;
    let mut expect_option_value: bool = false;

    let mut options: HashMap<String, String> = HashMap::new();
    let mut found_structs: FoundStructs = Vec::new();

    for token_tree in struct_path_stream.into_iter() {
        match token_tree {
            TokenTree::Ident(id) if current_struct_name_tokens.is_empty() => {
                current_struct_name_tokens.push(TokenTree::Ident(id));
            }
            TokenTree::Punct(punct)
                if !current_struct_name_tokens.is_empty()
                    && !opened_struct
                    && punct == ':'
                    && colons_counter < 2 =>
            {
                colons_counter += 1;
                if colons_counter > 1 {
                    opened_struct = true;
                }
            }
            TokenTree::Ident(id) if opened_struct => {
                colons_counter = 0;
                current_field_tokens.push(TokenTree::Ident(id));
            }
            TokenTree::Punct(punct)
                if !current_struct_name_tokens.is_empty()
                    && opened_struct
                    && punct == ':'
                    && colons_counter < 2 =>
            {
                colons_counter += 1;
                opened_struct = false;
                let field_tokens = std::mem::take(&mut current_field_tokens);
                if !fold_field_into_struct_name(field_tokens, &mut current_struct_name_tokens) {
                    return Err(format!(
                        "Unexpected punctuation input for struct path group parameters: {:?}",
                        punct
                    ));
                }
            }
            TokenTree::Punct(punct) if opened_struct && (punct == '.' || punct == '~') => {
                if current_field_tokens.is_empty() {
                    return Err(format!(
                        "Unexpected punctuation input for struct path group parameters: {:?}",
                        punct
                    ));
                }
                current_field_tokens.push(TokenTree::Punct(punct));
            }
            TokenTree::Group(group) if opened_struct && current_field_tokens.is_empty() => {
                parse_multiple_fields(group.stream(), &mut current_struct_fields)?
            }
            TokenTree::Punct(punct) if !options_opened && opened_struct && punct == ',' => {
                opened_struct = false;
                colons_counter = 0;
                if current_struct_name_tokens.is_empty() {
                    return Err("Unexpected comma with empty definitions!".to_string());
                }
                if !current_field_tokens.is_empty() {
                    current_struct_fields.push(std::mem::take(&mut current_field_tokens));
                }
                if current_struct_fields.is_empty() {
                    return Err(format!(
                        "Unexpected comma with empty fields for {}!",
                        render_text(&current_struct_name_tokens)
                    ));
                }
                found_structs.push((
                    std::mem::take(&mut current_struct_name_tokens),
                    std::mem::take(&mut current_struct_fields),
                ));
            }
            TokenTree::Punct(punct) if punct == ';' && opened_struct && !options_opened => {
                options_opened = true;
                opened_struct = false;
            }
            TokenTree::Ident(id) if options_opened && !expect_option_value => {
                current_option_name = Some(id.to_string())
            }
            TokenTree::Ident(id) if options_opened && expect_option_value => {
                expect_option_value = false;
                match current_option_name.take() {
                    Some(option_name) => {
                        options.insert(option_name, id.to_string());
                    }
                    _ => {
                        return Err("Wrong options format".to_string());
                    }
                }
            }
            TokenTree::Literal(lit) if options_opened && expect_option_value => {
                expect_option_value = false;
                match current_option_name.take() {
                    Some(option_name) => {
                        options.insert(option_name, unquote_literal(&lit)?);
                    }
                    _ => {
                        return Err("Wrong options format".to_string());
                    }
                }
            }
            TokenTree::Punct(punct) if options_opened && punct == '=' => {
                expect_option_value = true;
            }
            TokenTree::Punct(punct) if options_opened && punct == ',' => {
                expect_option_value = false;
            }
            // A second (or later) `;` starts another options group, so a
            // wrapper macro can append its own options after the caller's.
            // Groups share one key space; a repeated key takes its last value.
            TokenTree::Punct(punct) if options_opened && punct == ';' => {
                expect_option_value = false;
            }
            others => {
                return Err(format!(
                    "Unexpected input for struct path parameters: {:?}",
                    others
                ));
            }
        }
    }

    if !current_field_tokens.is_empty() {
        current_struct_fields.push(std::mem::take(&mut current_field_tokens));
    }
    if current_struct_name_tokens.is_empty() {
        return Err("Unexpected comma with empty definitions!".to_string());
    }
    if current_struct_fields.is_empty() {
        return Err(format!(
            "Unexpected comma with empty fields for {}!",
            render_text(&current_struct_name_tokens)
        ));
    }
    found_structs.push((current_struct_name_tokens, current_struct_fields));

    let all_check_functions = generate_checks_code_for(&found_structs);

    let mut all_final_fields: Vec<String> = Vec::with_capacity(16);

    for (_, fields) in &found_structs {
        for field_tokens in fields {
            let mut final_field_path = render_text(field_tokens).replace('~', ".");
            if !options.is_empty() {
                final_field_path = apply_options(&options, final_field_path)?;
            }
            all_final_fields.push(format!("\"{}\"", final_field_path))
        }
    }

    let fields_str = format!("[{}]", all_final_fields.join(","));
    let fields_tokens: TokenStream = fields_str
        .parse()
        .map_err(|_| format!("Generated code failed to parse: {}", fields_str))?;
    let mut block_contents = all_check_functions;
    block_contents.extend(fields_tokens);
    Ok(TokenStream::from(TokenTree::Group(Group::new(
        Delimiter::Brace,
        block_contents,
    ))))
}

/// Reclassifies a field-path segment that turned out to be a further
/// `::`-qualified part of the type (`tests` in `crate::tests::Struct::field`)
/// back into the type path. Returns `false` when the pending segment is not
/// exactly one identifier, which has no valid representation as a type-path
/// segment; the caller then reports the input as malformed instead of
/// building a check around it.
fn fold_field_into_struct_name(
    field_tokens: Vec<TokenTree>,
    struct_name_tokens: &mut Vec<TokenTree>,
) -> bool {
    let is_single_ident = matches!(field_tokens.as_slice(), [TokenTree::Ident(_)]);
    if is_single_ident {
        struct_name_tokens.extend("::".parse::<TokenStream>().expect("`::` always parses"));
        struct_name_tokens.extend(field_tokens);
    }
    is_single_ident
}

/// Renders parsed path tokens back to their text as written, `~` included,
/// so a caller replacing it with a delimiter still sees each collection step.
fn render_text(tokens: &[TokenTree]) -> String {
    tokens.iter().map(|token| token.to_string()).collect()
}

fn parse_multiple_fields(
    group_stream: TokenStream,
    found_struct_fields: &mut Vec<Vec<TokenTree>>,
) -> Result<(), String> {
    let mut current_field_tokens: Vec<TokenTree> = Vec::new();

    for token_tree in group_stream.into_iter() {
        match token_tree {
            TokenTree::Ident(id) => current_field_tokens.push(TokenTree::Ident(id)),
            TokenTree::Punct(punct) if punct == ',' => {
                if current_field_tokens.is_empty() {
                    return Err(format!(
                        "Unexpected punctuation input for struct path group parameters: {:?}",
                        punct
                    ));
                }
                found_struct_fields.push(std::mem::take(&mut current_field_tokens));
            }
            TokenTree::Punct(punct) if punct == '.' => {
                if current_field_tokens.is_empty() {
                    return Err(format!(
                        "Unexpected punctuation input for struct path group parameters: {:?}",
                        punct
                    ));
                }
                current_field_tokens.push(TokenTree::Punct(punct));
            }
            others => {
                return Err(format!(
                    "Unexpected input for struct path group parameters: {:?}",
                    others
                ));
            }
        }
    }

    if !current_field_tokens.is_empty() {
        found_struct_fields.push(current_field_tokens);
    }
    Ok(())
}

/// Recognizes the one shape `*` is allowed in: `Type::*` (optionally
/// `crate::mod::Type::*`), followed by nothing or `; options`. Returns
/// `None` when the input has no top-level `*` at all, so the caller falls
/// through to the ordinary field-list parser unchanged. Any other
/// placement of `*` (mixed with another struct or field group) is an error
/// here rather than a fall-through, because the combined array length
/// would then be unknown to the macro.
fn try_parse_all_fields(struct_path_stream: &TokenStream) -> Option<Result<TokenStream, String>> {
    let tokens: Vec<TokenTree> = struct_path_stream.clone().into_iter().collect();
    if !tokens
        .iter()
        .any(|t| matches!(t, TokenTree::Punct(p) if *p == '*'))
    {
        return None;
    }
    Some(parse_all_fields_at(&tokens))
}

/// The only options `Type::*` recognizes; any other key is a `compile_error!`
/// rather than a silently ignored typo, since there is no field list here for
/// the user to cross-check the result against.
const ALL_FIELDS_OPTION_KEYS: &[&str] = &["visibility", "case"];

/// Reported when the `*` sits beside a second struct or field group, whether
/// before it (`B::y, A::*`) or after (`A::*, B::y`): the combined array's
/// length would then be unknown to the macro.
const CANNOT_COMBINE_STAR_MESSAGE: &str = "`Type::*` cannot be combined with another struct or field group: its length is unknown to the macro";

/// Reported when the type-name position is not a plain `Type::*` /
/// `crate::module::Type::*` path and there is no comma marking a second
/// group either -- generics on the type, a `Type::<'a>::*` turbofish, a
/// `$t:ty` macro fragment, or a stray trailing separator.
const EXPECTED_TYPE_PATH_MESSAGE: &str =
    "expected a type path such as `Type::*` or `crate::module::Type::*`";

/// Reported when the parenthesized group holds tokens after its own `*`:
/// options belong after the closing `)`, not inside it.
const NOTHING_AFTER_NESTED_STAR_MESSAGE: &str = "nothing may follow a nested `Type::*` inside the parentheses; put options after the closing `)`";

/// Reported when a nested `Type::*` is followed by another struct or field
/// group: like the bare form, its result's length is unknown to the macro
/// once combined with anything else.
const CANNOT_COMBINE_NESTED_STAR_MESSAGE: &str = "a nested `Type::*` cannot be combined with another struct or field group: its length is unknown to the macro";

/// Reported when the nested form's own `.(`/`~(` has nothing valid before
/// it: no field name and connector at all (`Type::(a, *)`), or a stray
/// punct where a field name was expected (`Parent::..(Child::*)`). Named
/// after the connector rather than after whichever token was actually found,
/// since callers hit this from more than one parse state.
const NESTED_STAR_MISSING_FIELD_MESSAGE: &str = "expected a field name before `.(` / `~(`";

/// Reported when a nested `Type::*`'s own parentheses hold no `*` at all
/// (`Parent::child.(f)`): the field name and connector before the parens are
/// fine, but their content is not `Inner::*`.
const NESTED_STAR_INNER_EXPECTED_MESSAGE: &str = "inside the parens, expected `Type::*`";

/// Recognizes `paths!`'s nested `Type::*` form -- `Parent::field(.field|
/// ~field)*.(Inner::*)` or the same ending in `~(Inner::*)`, optionally
/// followed by `; options`. A `(...)` group on its own is not enough to mark
/// this form: `paths!(Type::(a, b))` is master's plain field-group syntax in
/// parenthesis rather than braces, and must still reach `parse_multiple_fields`
/// unchanged. Only a `(...)` group directly preceded by `.`/`~`, or one that
/// itself contains a `*`, is claimed here; every other input, including one
/// with a `(...)` group elsewhere, falls through to the parsers that handled
/// it before this form existed. Every top-level `(...)` group is checked in
/// order, not just the first: `A::(x), B::c.(C::*)` has a plain field-group
/// paren before the nested form's own, and the first one alone would never
/// claim this input.
fn try_parse_nested_star(tokens: &[TokenTree]) -> Option<Result<TokenStream, String>> {
    let paren_idx = tokens.iter().enumerate().find_map(|(i, t)| {
        let group = match t {
            TokenTree::Group(g) if g.delimiter() == Delimiter::Parenthesis => g,
            _ => return None,
        };
        let follows_connector = i
            .checked_sub(1)
            .is_some_and(|j| matches!(&tokens[j], TokenTree::Punct(p) if *p == '.' || *p == '~'));
        let contains_star = group
            .stream()
            .into_iter()
            .any(|t| matches!(t, TokenTree::Punct(p) if p == '*'));
        (follows_connector || contains_star).then_some(i)
    })?;
    Some(parse_nested_star_at(tokens, paren_idx))
}

fn parse_nested_star_at(tokens: &[TokenTree], paren_idx: usize) -> Result<TokenStream, String> {
    let prefix_region = &tokens[..paren_idx];
    // A second struct or field group before the nested form (`Other::x,
    // Parent::child.(Child::*)`) would otherwise reach `parse_type_and_field_path`
    // as one malformed type path and get the generic "expected a type path"
    // message; the comma marks the real problem, the same way
    // `parse_all_fields_at` tells the two apart for the bare form. Checked
    // before the `{ ... }` group check below, since a comma marks the same
    // "second group" mistake whether or not a `{ ... }` group happens to be
    // one of the groups involved (`A::{x}, B::c.(C::*)` and `A::[x], B::c.(C::*)`
    // are the same mistake and must report it the same way).
    if contains_top_level_comma(prefix_region) {
        return Err(CANNOT_COMBINE_NESTED_STAR_MESSAGE.to_string());
    }
    // With no comma present, a `{ ... }` field group still names one specific
    // mistake more precisely than the generic type-path error below would.
    if prefix_region
        .iter()
        .any(|t| matches!(t, TokenTree::Group(g) if g.delimiter() == Delimiter::Brace))
    {
        return Err(
            "a `{ ... }` field group cannot appear before a nested `Type::*`; use a plain field path such as `Parent::child.(Child::*)`".to_string(),
        );
    }

    let connector = match paren_idx.checked_sub(1).map(|i| &tokens[i]) {
        Some(TokenTree::Punct(p)) if *p == '.' || *p == '~' => p.clone(),
        _ => return Err(NESTED_STAR_MISSING_FIELD_MESSAGE.to_string()),
    };
    let head = &prefix_region[..prefix_region.len() - 1];
    let (parent_tokens, field_tokens) = parse_type_and_field_path(head)?;
    if field_tokens.is_empty() {
        return Err(
            "expected a field before the nested `Type::*`, e.g. `Parent::child.(Child::*)`"
                .to_string(),
        );
    }
    // A repeated or malformed connector (`P::o~.(C::*)`, `P::c..(C::*)`,
    // `P::o~~(C::*)`) leaves a trailing `.`/`~` in the field path once the
    // one connector directly before the parens is stripped off into `head`;
    // left unchecked, that trailing punct becomes a dangling `.` in the
    // generated check and fails with a confusing "unexpected token `;`".
    if !matches!(field_tokens.last(), Some(TokenTree::Ident(_))) {
        return Err(
            "expected a field name immediately before the nested `Type::*`'s connector, e.g. `Parent::child.(Child::*)`".to_string(),
        );
    }

    let paren_group = match &tokens[paren_idx] {
        TokenTree::Group(g) => g,
        _ => unreachable!(),
    };
    let inner_tokens: Vec<TokenTree> = paren_group.stream().into_iter().collect();
    if inner_tokens
        .iter()
        .any(|t| matches!(t, TokenTree::Group(_)))
    {
        return Err("nesting a parenthesized group inside `Type::*` is not supported".to_string());
    }
    let (inner_type_tokens, star_span) = parse_bare_star_type(&inner_tokens)?;

    let rest = &tokens[paren_idx + 1..];
    let options = match rest {
        [] => Vec::new(),
        [TokenTree::Punct(p), remainder @ ..] if *p == ';' => parse_all_fields_options(remainder)?,
        // A lone trailing comma with nothing following it is not a second
        // group, just malformed input -- the same call `parse_all_fields_at`
        // makes for the bare form's own `TestStruct::*,`, so both forms
        // report the same message for the same shape of mistake.
        [TokenTree::Punct(p)] if *p == ',' => return Err(EXPECTED_TYPE_PATH_MESSAGE.to_string()),
        _ => return Err(CANNOT_COMBINE_NESTED_STAR_MESSAGE.to_string()),
    };
    // `visibility`/`case` pick the inner type's names const exactly as the
    // bare form does; `delim` additionally separates the prefix's own
    // segments and joins the prefix to each name -- there being a prefix
    // here is what the bare form has no `delim` option for.
    const NESTED_STAR_OPTION_KEYS: &[&str] = &["visibility", "case", "delim"];
    if let Some((unknown, _)) = options
        .iter()
        .find(|(key, _)| !NESTED_STAR_OPTION_KEYS.contains(&key.as_str()))
    {
        return Err(format!("Unknown option is specified: {}", unknown));
    }
    let (visibility_suffix, case_suffix) = names_const_suffixes(&options)?;
    let options_map: HashMap<String, String> = options.into_iter().collect();

    // `~` marks a collection step and must become `.` before options are
    // applied, or a segment joined by `~` is treated as one field name
    // instead of two and never gets the chosen delim or per-segment case
    // conversion -- the same rule `path!` applies to its own field path.
    let raw_prefix = render_text(&field_tokens).replace('~', ".");
    let prefix_string = apply_options(&options_map, raw_prefix)?;
    let delim_string = options_map
        .get("delim")
        .cloned()
        .unwrap_or_else(|| ".".to_string());

    let inner_type_stream: TokenStream = inner_type_tokens.iter().cloned().collect();
    let parent_stream: TokenStream = parent_tokens.iter().cloned().collect();

    // `.` reads the field by reference and relies on deref coercion for a
    // `Box<Inner>` field; `~` reads it through `iter()` instead, which
    // already yields a reference, so no leading `&` is added there. `SELF`
    // is spanned with `star_span` rather than this call's own `Span::call_site()`,
    // matching the closure parameter `|t: &PARENT|` the outer `fill` below
    // builds with `star_span` too: the two must share one hygiene context or
    // the closure body fails to resolve its own parameter with "cannot find
    // value `t` in this scope" once this whole call is itself expanded from
    // inside a wrapping `macro_rules!`. The surrounding `.iter()`/`.next()`/
    // `.unwrap()` glue keeps `Span::call_site()` so it is still recognized
    // as macro-generated rather than linted as if the user had written it.
    let check_template = if connector == '~' {
        "let _: &INNER = SELF.FIELD.iter().next().unwrap();"
    } else {
        "let _: &INNER = &SELF.FIELD;"
    };
    let self_param_tokens: TokenStream =
        TokenStream::from(TokenTree::Ident(Ident::new("t", star_span)));
    let check = fill(
        check_template,
        Span::call_site(),
        &[
            ("SELF", &self_param_tokens),
            ("INNER", &inner_type_stream),
            ("FIELD", &field_check_tokens(&field_tokens)),
        ],
    );

    let names_path = format!(
        "INNER::__STRUCT_PATH_{}_FIELDS{}",
        visibility_suffix, case_suffix
    );
    let names_tokens = fill(&names_path, star_span, &[("INNER", &inner_type_stream)]);
    let prefix_tokens = quoted_string_tokens(&prefix_string, star_span)?;
    let delim_tokens = quoted_string_tokens(&delim_string, star_span)?;

    // `NAMES` is spliced twice here (the local const's own length and its
    // value) and nowhere else in the block, so a names const that a
    // downstream crate cannot see (an `ALL` array capped to `pub(crate)`)
    // reports at most these two sites instead of once per call below.
    // Binding the joined array itself to a `const`, rather than leaving it
    // a plain expression, forces the whole join to run at compile time: a
    // plain call, even to a `const fn` with only `const` inputs, is not
    // guaranteed to be folded away, so without this binding release builds
    // still call `core::str::from_utf8` at runtime for every `paths!` site.
    Ok(fill(
        "{
            const _: fn(&PARENT) = |t: &PARENT| { CHECK };
            const __STRUCT_PATH_NAMES: [&str; NAMES.len()] = NAMES;
            const __STRUCT_PATH_LEN: usize =
                INNER::__struct_path_joined_len(PREFIX, DELIM, &__STRUCT_PATH_NAMES);
            const __STRUCT_PATH_BYTES: [u8; __STRUCT_PATH_LEN] =
                INNER::__struct_path_joined_bytes::<__STRUCT_PATH_LEN>(PREFIX, DELIM, &__STRUCT_PATH_NAMES);
            const __STRUCT_PATH_OUT: [&str; __STRUCT_PATH_NAMES.len()] =
                INNER::__struct_path_joined(&__STRUCT_PATH_BYTES, PREFIX, DELIM, &__STRUCT_PATH_NAMES);
            __STRUCT_PATH_OUT
        }",
        star_span,
        &[
            ("PARENT", &parent_stream),
            ("CHECK", &check),
            ("INNER", &inner_type_stream),
            ("PREFIX", &prefix_tokens),
            ("DELIM", &delim_tokens),
            ("NAMES", &names_tokens),
        ],
    ))
}

/// Parses `tokens` as `Type::field(.field|~field)*`, the same shape a single
/// `path!` group accepts, but with no group and no options support since
/// the nested `Type::*` form's caller already ruled those out. Returns the
/// type's tokens and the field path's tokens (idents and `.`/`~` puncts, in
/// declaration order and still carrying the user's own spans); an empty
/// field path is valid here and left for the caller to judge, since
/// `Parent::(Child::*)` and a genuinely malformed prefix are different
/// errors.
fn parse_type_and_field_path(
    tokens: &[TokenTree],
) -> Result<(Vec<TokenTree>, Vec<TokenTree>), String> {
    let mut struct_name_tokens: Vec<TokenTree> = Vec::new();
    let mut field_tokens: Vec<TokenTree> = Vec::new();
    let mut opened_struct = false;
    let mut colons_counter = 0;

    for token_tree in tokens {
        match token_tree.clone() {
            TokenTree::Ident(id) if struct_name_tokens.is_empty() => {
                struct_name_tokens.push(TokenTree::Ident(id));
            }
            TokenTree::Punct(punct)
                if !struct_name_tokens.is_empty()
                    && !opened_struct
                    && punct == ':'
                    && colons_counter < 2 =>
            {
                colons_counter += 1;
                if colons_counter > 1 {
                    opened_struct = true;
                }
            }
            TokenTree::Ident(id) if opened_struct => {
                colons_counter = 0;
                field_tokens.push(TokenTree::Ident(id));
            }
            TokenTree::Punct(punct)
                if !struct_name_tokens.is_empty()
                    && opened_struct
                    && punct == ':'
                    && colons_counter < 2 =>
            {
                colons_counter += 1;
                opened_struct = false;
                let taken = std::mem::take(&mut field_tokens);
                if !fold_field_into_struct_name(taken, &mut struct_name_tokens) {
                    return Err(EXPECTED_TYPE_PATH_MESSAGE.to_string());
                }
            }
            TokenTree::Punct(punct) if opened_struct && (punct == '.' || punct == '~') => {
                if field_tokens.is_empty() {
                    return Err(NESTED_STAR_MISSING_FIELD_MESSAGE.to_string());
                }
                field_tokens.push(TokenTree::Punct(punct));
            }
            _ => return Err(EXPECTED_TYPE_PATH_MESSAGE.to_string()),
        }
    }
    if struct_name_tokens.is_empty() || !opened_struct {
        return Err(EXPECTED_TYPE_PATH_MESSAGE.to_string());
    }
    Ok((struct_name_tokens, field_tokens))
}

/// Splits `tokens` on its first `*`, checked to directly follow `Type::`,
/// into the type path before it, the `*`'s own span, and whatever tokens
/// remain after it. Shared by the nested form's inner type, which allows no
/// `rest` at all, and the bare form, which allows `; options` or a second
/// group there; each checks `rest` itself since the two forms disagree on
/// what may follow.
fn split_star_type(tokens: &[TokenTree]) -> Result<(&[TokenTree], Span, &[TokenTree]), String> {
    let star_pos = tokens
        .iter()
        .position(|t| matches!(t, TokenTree::Punct(p) if *p == '*'))
        .ok_or_else(|| EXPECTED_TYPE_PATH_MESSAGE.to_string())?;
    if star_pos < 2
        || !matches!(&tokens[star_pos - 1], TokenTree::Punct(p) if *p == ':')
        || !matches!(&tokens[star_pos - 2], TokenTree::Punct(p) if *p == ':')
    {
        return Err("`*` must directly follow `Type::`".to_string());
    }
    let star_span = match &tokens[star_pos] {
        TokenTree::Punct(p) => p.span(),
        _ => unreachable!(),
    };
    Ok((&tokens[..star_pos - 2], star_span, &tokens[star_pos + 1..]))
}

/// Whether `tokens` is a type path that starts with `Self`, the one type
/// a nested `Type::*`'s inner type must reject regardless of what follows
/// (`Self`, `Self::Child`, ...): the join it drives is wrapped in a
/// block-local `const`, and `Self` cannot be named from a nested item, only
/// from the enclosing `impl` block itself (E0401).
fn is_self_type_path(tokens: &[TokenTree]) -> bool {
    matches!(tokens.first(), Some(TokenTree::Ident(id)) if id.to_string() == "Self")
}

/// Parses the parenthesized group's content as a bare `Type::*` with
/// nothing else inside -- no options, since those belong after the closing
/// `)`, and no second group, already ruled out by the caller. Returns the
/// inner type's tokens and the `*`'s span, used to anchor the generated
/// call so a missing derive or a mismatched type is reported there.
fn parse_bare_star_type(tokens: &[TokenTree]) -> Result<(Vec<TokenTree>, Span), String> {
    // Checked ahead of `split_star_type`, which has no `*` to report a span
    // for otherwise: the field name and connector before the parens are
    // already known good at this call site, so the more specific message
    // points at the parens' own content rather than repeating the generic
    // type-path message that content with no `*` anywhere else falls back to.
    if !tokens
        .iter()
        .any(|t| matches!(t, TokenTree::Punct(p) if *p == '*'))
    {
        return Err(NESTED_STAR_INNER_EXPECTED_MESSAGE.to_string());
    }
    let (type_tokens, star_span, rest) = split_star_type(tokens)?;
    if type_tokens.is_empty() || !is_bare_type_path(type_tokens) {
        return Err(EXPECTED_TYPE_PATH_MESSAGE.to_string());
    }
    if is_self_type_path(type_tokens) {
        return Err(
            "`Self` cannot be named inside a nested `Type::*`; name the type directly, e.g. `Node::next~(Node::*)`".to_string(),
        );
    }
    if !rest.is_empty() {
        return Err(NOTHING_AFTER_NESTED_STAR_MESSAGE.to_string());
    }
    Ok((type_tokens.to_vec(), star_span))
}

/// Splices `value`, still carrying its source escape sequences the way
/// `unquote_literal` returns them, directly between quotes and parses the
/// result as a `&'static str` literal spanned at `span` -- the same
/// splice-and-parse `paths_impl` uses for its own returned field path, so a
/// delimiter or prefix containing `delim = "\t"` decodes to the same
/// character both places instead of the doubled backslash that
/// `Literal::string` (which escapes its input rather than reusing it as
/// already-escaped source text) produced here before.
fn quoted_string_tokens(value: &str, span: Span) -> Result<TokenStream, String> {
    let text = format!("\"{}\"", value);
    let tokens: TokenStream = text
        .parse()
        .map_err(|_| format!("Generated code failed to parse: {}", text))?;
    Ok(tokens
        .into_iter()
        .map(|mut token| {
            token.set_span(span);
            token
        })
        .collect())
}

fn parse_all_fields_at(tokens: &[TokenTree]) -> Result<TokenStream, String> {
    let (type_tokens, star_span, rest) = split_star_type(tokens)?;
    if type_tokens.is_empty() {
        return Err("Unexpected `*` with an empty type!".to_string());
    }
    if !is_bare_type_path(type_tokens) {
        // A second `Type::field` or `Type::*` group before this one folds
        // into `type_tokens` rather than being rejected outright, since
        // nothing here stops at the group's own `,`; a top-level comma is
        // what tells that shape apart from a type path that is simply
        // malformed on its own (generics, a turbofish, a macro fragment),
        // which gets the other message instead.
        return Err(if contains_top_level_comma(type_tokens) {
            CANNOT_COMBINE_STAR_MESSAGE.to_string()
        } else {
            EXPECTED_TYPE_PATH_MESSAGE.to_string()
        });
    }

    let options = match rest {
        [] => Vec::new(),
        [TokenTree::Punct(p), remainder @ ..] if *p == ';' => parse_all_fields_options(remainder)?,
        // A second group after the `*` (`A::*, B::y`) is the same unknown-
        // length combination as one before it; a lone trailing comma with
        // nothing following it is not a second group, just malformed input.
        [TokenTree::Punct(p), more @ ..] if *p == ',' && !more.is_empty() => {
            return Err(CANNOT_COMBINE_STAR_MESSAGE.to_string())
        }
        _ => return Err(EXPECTED_TYPE_PATH_MESSAGE.to_string()),
    };
    if let Some((unknown, _)) = options
        .iter()
        .find(|(key, _)| !ALL_FIELDS_OPTION_KEYS.contains(&key.as_str()))
    {
        return Err(format!("Unknown option is specified: {}", unknown));
    }

    let (visibility_suffix, case_suffix) = names_const_suffixes(&options)?;

    let const_path = format!(
        "TYPE::__STRUCT_PATH_{}_FIELDS{}",
        visibility_suffix, case_suffix
    );
    let type_stream: TokenStream = type_tokens.iter().cloned().collect();
    Ok(fill(&const_path, star_span, &[("TYPE", &type_stream)]))
}

/// Picks the `__STRUCT_PATH_{PUB|ALL}_FIELDS[_CAMEL|_PASCAL]` const suffix
/// pair named by a `Type::*` call's `visibility`/`case` options, shared by
/// the bare and nested forms so the two can never disagree on what a given
/// option value selects.
fn names_const_suffixes(
    options: &[(String, String)],
) -> Result<(&'static str, &'static str), String> {
    let option_value = |name: &str| {
        options
            .iter()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value.as_str())
    };
    let visibility_suffix = match option_value("visibility") {
        None | Some("pub") => "PUB",
        Some("all") => "ALL",
        Some(other) => return Err(format!("Unknown visibility is specified: {}", other)),
    };
    let case_suffix = match option_value("case") {
        None => "",
        Some("camel") => "_CAMEL",
        Some("pascal") => "_PASCAL",
        Some(other) => return Err(format!("Unknown case is specified: {}", other)),
    };
    Ok((visibility_suffix, case_suffix))
}

/// Whether `tokens` contains a `,` at the top level -- the mark of a second
/// struct or field group folded in beside `Type::*`, as opposed to a type
/// path that is simply malformed on its own. Depth-aware over `<...>`, so a
/// generic parameter list's own comma (`S<'a, 'b>::*`) is not mistaken for
/// one, the same depth tracking `split_top_level_commas` uses for a field's
/// generic type.
fn contains_top_level_comma(tokens: &[TokenTree]) -> bool {
    split_top_level_commas(tokens).len() > 1
}

/// Reports whether `tokens` is a bare type path -- an optional leading `::`
/// followed by one or more identifiers joined by `::`, and nothing else.
/// `Type::*`'s type name must be exactly this shape; anything wider (a
/// trailing field group, a second `Type::*` group, generics, stray
/// punctuation) is rejected by the caller before it is spliced into the
/// generated code.
fn is_bare_type_path(tokens: &[TokenTree]) -> bool {
    let mut i = 0;
    if matches!(tokens.first(), Some(TokenTree::Punct(p)) if *p == ':')
        && matches!(tokens.get(1), Some(TokenTree::Punct(p)) if *p == ':')
    {
        i = 2;
    }
    loop {
        if !matches!(tokens.get(i), Some(TokenTree::Ident(_))) {
            return false;
        }
        i += 1;
        if i == tokens.len() {
            return true;
        }
        let is_double_colon = matches!(tokens.get(i), Some(TokenTree::Punct(p)) if *p == ':')
            && matches!(tokens.get(i + 1), Some(TokenTree::Punct(p)) if *p == ':');
        if !is_double_colon {
            return false;
        }
        i += 2;
    }
}

/// The one grammar `Type::*;` options accept: one or more `;`-separated
/// groups of `key = "value"` pairs, the pairs within a group separated by
/// `,`, each value a quoted string or char literal. A group may be empty.
/// Unlike `path!`/`paths!`'s own option grammar -- parsed inline in their
/// own loops, with a field list to cross-check its result against and a
/// looser tolerance for malformed input -- `Type::*` has no such field list,
/// so this parser accepts nothing looser: no bare key, no unquoted value, no
/// two pairs run together without a separator, no `;` straight after a `,`,
/// and no key repeated, whether within one group or across groups.
enum OptionParseState {
    /// At the start of a group, where a `;` closes it as an empty group.
    GroupStart,
    /// After a `,`, where only an option name may follow.
    Key,
    Equals,
    Value,
    CommaOrEnd,
}

/// Parses the `key = "value", ...; key = "value", ...` option grammar
/// accepted after `Type::*;` (and, for the nested `Type::*` form, after the
/// closing `)`). `tokens` starts after the `;` that opens the first group.
/// Keeps source order so the caller can report the first unknown key as
/// written rather than in a hash map's arbitrary order, and rejects a key
/// repeated later in the options, in the same group or a later one, rather
/// than silently keeping whichever value a lookup finds first.
fn parse_all_fields_options(tokens: &[TokenTree]) -> Result<Vec<(String, String)>, String> {
    let mut options: Vec<(String, String)> = Vec::new();
    let mut pending_key: Option<String> = None;
    let mut state = OptionParseState::GroupStart;

    for token_tree in tokens {
        state = match (state, token_tree) {
            (OptionParseState::GroupStart | OptionParseState::Key, TokenTree::Ident(id)) => {
                pending_key = Some(id.to_string());
                OptionParseState::Equals
            }
            (OptionParseState::Equals, TokenTree::Punct(p)) if *p == '=' => OptionParseState::Value,
            (OptionParseState::Value, TokenTree::Literal(lit)) => {
                let key = pending_key.take().expect("set on entering Equals/Value");
                if options.iter().any(|(existing, _)| existing == &key) {
                    return Err(format!("Duplicate option is specified: {}", key));
                }
                options.push((key, unquote_literal(lit)?));
                OptionParseState::CommaOrEnd
            }
            (OptionParseState::CommaOrEnd, TokenTree::Punct(p)) if *p == ',' => {
                OptionParseState::Key
            }
            // Later groups exist so a wrapper macro can append its own
            // options after the caller's. They share one key space with the
            // first group: a key repeated in a later group is still a
            // duplicate, not an override.
            (OptionParseState::CommaOrEnd | OptionParseState::GroupStart, TokenTree::Punct(p))
                if *p == ';' =>
            {
                OptionParseState::GroupStart
            }
            (state, other) => {
                let expected = match state {
                    OptionParseState::GroupStart | OptionParseState::Key => "an option name",
                    OptionParseState::Equals => "`=`",
                    OptionParseState::Value => "a quoted string (\"...\") or char ('.') literal",
                    OptionParseState::CommaOrEnd => "`,` or `;`",
                };
                return Err(format!(
                    "Expected {} in `Type::*` options, found `{}`",
                    expected, other
                ));
            }
        };
    }

    match state {
        OptionParseState::GroupStart | OptionParseState::Key | OptionParseState::CommaOrEnd => {
            Ok(options)
        }
        OptionParseState::Equals | OptionParseState::Value => Err(format!(
            "Missing a value for option `{}`",
            pending_key.expect("set on entering Equals/Value")
        )),
    }
}

#[proc_macro]
pub fn path(struct_path_stream: TokenStream) -> TokenStream {
    match path_impl(struct_path_stream) {
        Ok(stream) => stream,
        Err(message) => compile_error_for(message),
    }
}

/// Whether `stream` contains a `*` at any depth, including inside a
/// parenthesized nested-`Type::*` group -- `path!` rejects both shapes with
/// the same message, so it needs the deeper scan `paths!`'s own two `*`
/// parsers do not, since each of those looks for a specific placement
/// rather than asking whether one exists anywhere at all.
fn contains_star(stream: TokenStream) -> bool {
    stream.into_iter().any(|token| match token {
        TokenTree::Punct(p) if p == '*' => true,
        TokenTree::Group(g) => contains_star(g.stream()),
        _ => false,
    })
}

fn path_impl(struct_path_stream: TokenStream) -> Result<TokenStream, String> {
    // `Type::*` (all declared fields) has an array result, so only `paths!`
    // can return it; `path!` always returns a single string. The bare form
    // sits at the top level, but the nested form's `*` is inside a
    // parenthesized group, so this checks every depth, not just the top one.
    if contains_star(struct_path_stream.clone()) {
        return Err(
            "`*` for all declared fields is only supported by paths!, not path!".to_string(),
        );
    }

    let mut current_struct_name_tokens: Vec<TokenTree> = Vec::new();

    let mut opened_struct = false;
    let mut colons_counter = 0;
    let mut options_opened = false;

    let mut current_field_tokens: Vec<TokenTree> = Vec::new();

    let mut current_option_name: Option<String> = None;
    let mut expect_option_value: bool = false;

    let mut options: HashMap<String, String> = HashMap::new();
    let mut found_structs: FoundStructs = Vec::new();

    for token_tree in struct_path_stream.into_iter() {
        match token_tree {
            TokenTree::Ident(id) if current_struct_name_tokens.is_empty() => {
                current_struct_name_tokens.push(TokenTree::Ident(id));
            }
            TokenTree::Punct(punct)
                if !current_struct_name_tokens.is_empty()
                    && !opened_struct
                    && punct == ':'
                    && colons_counter < 2 =>
            {
                colons_counter += 1;
                if colons_counter > 1 {
                    opened_struct = true;
                }
            }
            TokenTree::Ident(id) if opened_struct => {
                colons_counter = 0;
                current_field_tokens.push(TokenTree::Ident(id));
            }
            TokenTree::Punct(punct)
                if !current_struct_name_tokens.is_empty()
                    && opened_struct
                    && punct == ':'
                    && colons_counter < 2 =>
            {
                colons_counter += 1;
                opened_struct = false;
                let field_tokens = std::mem::take(&mut current_field_tokens);
                if !fold_field_into_struct_name(field_tokens, &mut current_struct_name_tokens) {
                    return Err(format!(
                        "Unexpected punctuation input for struct path group parameters: {:?}",
                        punct
                    ));
                }
            }
            TokenTree::Punct(punct) if opened_struct && (punct == '.' || punct == '~') => {
                if current_field_tokens.is_empty() {
                    return Err(format!(
                        "Unexpected punctuation input for struct path group parameters: {:?}",
                        punct
                    ));
                }
                current_field_tokens.push(TokenTree::Punct(punct));
            }
            TokenTree::Punct(punct) if !options_opened && opened_struct && punct == ',' => {
                opened_struct = false;
                colons_counter = 0;
                if current_struct_name_tokens.is_empty() {
                    return Err("Unexpected comma with empty definitions!".to_string());
                }
                if current_field_tokens.is_empty() {
                    return Err(format!(
                        "Unexpected comma with empty fields for {}!",
                        render_text(&current_struct_name_tokens)
                    ));
                }
                found_structs.push((
                    std::mem::take(&mut current_struct_name_tokens),
                    vec![std::mem::take(&mut current_field_tokens)],
                ));
            }
            TokenTree::Punct(punct) if punct == ';' && opened_struct && !options_opened => {
                options_opened = true;
                opened_struct = false;
            }
            TokenTree::Ident(id) if options_opened && !expect_option_value => {
                current_option_name = Some(id.to_string())
            }
            TokenTree::Ident(id) if options_opened && expect_option_value => {
                expect_option_value = false;
                match current_option_name.take() {
                    Some(option_name) => {
                        options.insert(option_name, id.to_string());
                    }
                    _ => {
                        return Err("Wrong options format".to_string());
                    }
                }
            }
            TokenTree::Literal(lit) if options_opened && expect_option_value => {
                expect_option_value = false;
                match current_option_name.take() {
                    Some(option_name) => {
                        options.insert(option_name, unquote_literal(&lit)?);
                    }
                    _ => {
                        return Err("Wrong options format".to_string());
                    }
                }
            }
            TokenTree::Punct(punct) if options_opened && punct == '=' => {
                expect_option_value = true;
            }
            TokenTree::Punct(punct) if options_opened && punct == ',' => {
                expect_option_value = false;
            }
            // A second (or later) `;` starts another options group, so a
            // wrapper macro can append its own options after the caller's.
            // Groups share one key space; a repeated key takes its last value.
            TokenTree::Punct(punct) if options_opened && punct == ';' => {
                expect_option_value = false;
            }
            others => {
                return Err(format!(
                    "Unexpected input for struct path parameters: {:?}",
                    others
                ));
            }
        }
    }

    if !current_struct_name_tokens.is_empty() && !current_field_tokens.is_empty() {
        found_structs.push((current_struct_name_tokens, vec![current_field_tokens]));
    }

    if found_structs.is_empty() {
        return Err("Unexpected empty path definition!".to_string());
    }

    let all_check_functions = generate_checks_code_for(&found_structs);
    // `~` marks a collection step and must become the path separator before
    // options are applied, or a segment joined by `~` is treated as one
    // field name instead of two and never gets the chosen delim or
    // per-segment case conversion.
    let full_field_path = found_structs
        .iter()
        .flat_map(|(_, fields)| fields.iter())
        .map(|tokens| render_text(tokens))
        .collect::<Vec<_>>()
        .join(".")
        .replace('~', ".");
    let final_field_path = apply_options(&options, full_field_path)?;
    let fields_str = format!("\"{}\"", final_field_path);
    let fields_tokens: TokenStream = fields_str
        .parse()
        .map_err(|_| format!("Generated code failed to parse: {}", fields_str))?;
    let mut block_contents = all_check_functions;
    block_contents.extend(fields_tokens);
    Ok(TokenStream::from(TokenTree::Group(Group::new(
        Delimiter::Brace,
        block_contents,
    ))))
}

/// Builds the `const _: fn(&Type) = |t: &Type| { let _ = &t.field; };`
/// check for every discovered `Type::field` pair. The user's type and field
/// tokens keep their spans, so a type error is reported on the exact token
/// that is wrong; each `~` becomes `.iter().next().unwrap().` spanned at that
/// `~`, so a stepped-into type without `iter()` is blamed on the `~`.
fn generate_checks_code_for(found_structs: &FoundStructs) -> TokenStream {
    let mut all_check_functions = TokenStream::new();
    for (struct_name_tokens, struct_fields) in found_structs {
        let struct_name: TokenStream = struct_name_tokens.iter().cloned().collect();
        for field_tokens in struct_fields {
            all_check_functions.extend(fill(
                "const _: fn(&STRUCT) = |t: &STRUCT| { let _ = &t.FIELD; };",
                Span::call_site(),
                &[
                    ("STRUCT", &struct_name),
                    ("FIELD", &field_check_tokens(field_tokens)),
                ],
            ));
        }
    }
    all_check_functions
}

/// Maps a field path's tokens to themselves, except a `~` step, which
/// becomes `.iter().next().unwrap().` spanned at that `~` so a stepped-into
/// type without `iter()` is blamed on the `~` rather than on the check as a
/// whole. Shared by every check this macro emits, flat or nested, so they
/// can never disagree on what `~` means.
fn field_check_tokens(field_tokens: &[TokenTree]) -> TokenStream {
    field_tokens
        .iter()
        .map(|token| match token {
            TokenTree::Punct(punct) if *punct == '~' => {
                fill(".iter().next().unwrap().", punct.span(), &[])
            }
            token => token.clone().into(),
        })
        .collect()
}

/// Parses `template` into tokens spanned at `span`, replacing each ident
/// named in `substitutions` with the given tokens, which keep their own
/// spans. `template` must be valid Rust tokens.
fn fill(template: &str, span: Span, substitutions: &[(&str, &TokenStream)]) -> TokenStream {
    fn walk(stream: TokenStream, span: Span, subs: &[(&str, &TokenStream)]) -> TokenStream {
        stream
            .into_iter()
            .map(|mut token| {
                match &token {
                    TokenTree::Ident(ident) => {
                        let name = ident.to_string();
                        if let Some((_, tokens)) = subs.iter().find(|(n, _)| *n == name) {
                            return (*tokens).clone();
                        }
                    }
                    TokenTree::Group(group) => {
                        let stream = walk(group.stream(), span, subs);
                        token = TokenTree::Group(Group::new(group.delimiter(), stream));
                    }
                    _ => {}
                }
                token.set_span(span);
                token.into()
            })
            .collect()
    }
    walk(
        template.parse().expect("templates are valid tokens"),
        span,
        substitutions,
    )
}

/// Strips the surrounding quotes from a plain string (`"..."`) or char
/// (`'.'`) literal. Escapes keep their source spelling because the value is
/// pasted back into a string literal in the generated code; decoding them
/// would change the output. Any other literal kind (numeric, byte string,
/// byte char, raw string) is rejected, since its text has no such quotes to
/// strip and would produce invalid generated code.
fn unquote_literal(lit: &proc_macro::Literal) -> Result<String, String> {
    let text = lit.to_string();
    let bytes = text.as_bytes();
    let is_quoted = bytes.len() >= 2
        && ((bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')
            || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''));
    if is_quoted {
        Ok(text[1..text.len() - 1].to_string())
    } else {
        Err(format!(
            "Unsupported option value {}: expected a string (\"...\") or char ('.') literal",
            text
        ))
    }
}

/// The case conversion shared by `path!`/`paths!`'s `case = "..."` option
/// and `#[derive(StructPath)]`'s `_CAMEL`/`_PASCAL` field-name constants, so
/// the two can never disagree on what "camel" or "pascal" means for a
/// snake_case field name.
fn convert_case_by_name(field_name: &str, case_name: &str) -> Result<String, String> {
    match case_name {
        "camel" => Ok(field_name.from_case(Case::Snake).to_case(Case::Camel)),
        "pascal" => Ok(field_name.from_case(Case::Snake).to_case(Case::Pascal)),
        another => Err(format!("Unknown case is specified: {}", another)),
    }
}

/// Converts every name in `names` with `convert_case_by_name`, for the two
/// known case names the derive itself always passes; a case name it does
/// not recognize is a bug in the derive, not a user input to report.
fn convert_all(names: &[String], case_name: &str) -> Vec<String> {
    names
        .iter()
        .map(|n| {
            convert_case_by_name(n, case_name)
                .unwrap_or_else(|_| panic!("{:?} is always a known case", case_name))
        })
        .collect()
}

fn apply_options(options: &HashMap<String, String>, field_path: String) -> Result<String, String> {
    let delim = options
        .get("delim")
        .as_ref()
        .map(|s| s.as_str())
        .unwrap_or(".");
    let case = options.get("case");
    let segments = field_path
        .split('.')
        .map(|field_name| match case {
            Some(case_value) => convert_case_by_name(field_name, case_value),
            None => Ok(field_name.to_string()),
        })
        .collect::<Result<Vec<String>, String>>()?;
    Ok(segments.join(delim))
}

/// `#[derive(StructPath)]` records a struct's declared field names as
/// `#[doc(hidden)]` associated consts, so `paths!(Type::*)` can return them
/// without the caller listing every field by hand. Supports only a struct
/// with named fields and, at most, lifetime generic parameters; anything
/// else is a `compile_error!` on the offending item, spanned at the
/// specific token that disqualifies it.
#[proc_macro_derive(StructPath)]
pub fn derive_struct_path(input: TokenStream) -> TokenStream {
    match derive_struct_path_impl(input) {
        Ok(stream) => stream,
        Err(error_stream) => error_stream,
    }
}

/// One field found in a derived struct's body: its declared name, with any
/// `r#` prefix stripped since the generated string is a JSON-path-style
/// segment rather than a Rust identifier, and whether it was declared with
/// plain `pub` — `pub(crate)`, `pub(super)`, `pub(in ..)` and private
/// fields are all "not plain pub".
struct DerivedField {
    name: String,
    is_plain_pub: bool,
}

fn derive_struct_path_impl(input: TokenStream) -> Result<TokenStream, TokenStream> {
    let tokens: Vec<TokenTree> = input.into_iter().collect();
    let mut pos = 0;

    skip_attributes(&tokens, &mut pos);

    let visibility_start = pos;
    let (vis_len, item_is_plain_pub) = parse_visibility_prefix(&tokens[pos..]);
    pos += vis_len;
    let visibility_tokens: TokenStream = tokens[visibility_start..pos].iter().cloned().collect();

    let (keyword, keyword_span) = match tokens.get(pos) {
        Some(TokenTree::Ident(id)) => (id.to_string(), id.span()),
        _ => {
            return Err(compile_error_at(
                "StructPath: unable to parse the derived item",
                Span::call_site(),
            ))
        }
    };
    if keyword != "struct" {
        return Err(compile_error_at(
            &format!(
                "StructPath supports structs with named fields only, not {}s",
                keyword
            ),
            keyword_span,
        ));
    }
    pos += 1;

    let name_ident = match tokens.get(pos) {
        Some(TokenTree::Ident(id)) => id.clone(),
        _ => {
            return Err(compile_error_at(
                "StructPath: expected a struct name",
                keyword_span,
            ))
        }
    };
    let name_span = name_ident.span();
    pos += 1;

    let (generics_impl, generics_type) = parse_lifetime_generics(&tokens, &mut pos)?;
    let (where_clause, fields_group) = find_fields_group(&tokens[pos..])?;
    let fields = parse_derived_fields(fields_group.stream())?;

    let pub_names: Vec<String> = fields
        .iter()
        .filter(|f| f.is_plain_pub)
        .map(|f| f.name.clone())
        .collect();
    let all_names: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();

    let name_tokens = TokenStream::from(TokenTree::Ident(name_ident));
    let pub_array = array_literal_tokens(&pub_names);
    let pub_camel_array = array_literal_tokens(&convert_all(&pub_names, "camel"));
    let pub_pascal_array = array_literal_tokens(&convert_all(&pub_names, "pascal"));
    let all_array = array_literal_tokens(&all_names);
    let all_camel_array = array_literal_tokens(&convert_all(&all_names, "camel"));
    let all_pascal_array = array_literal_tokens(&convert_all(&all_names, "pascal"));
    let n_pub: TokenStream = pub_names
        .len()
        .to_string()
        .parse()
        .expect("a field count always parses as a literal");
    let n_all: TokenStream = all_names
        .len()
        .to_string()
        .parse()
        .expect("a field count always parses as a literal");

    // `__STRUCT_PATH_ALL_FIELDS*` exposes every declared field's name,
    // private ones included. A plain `pub` struct's consts are capped to
    // `pub(crate)`, so a downstream crate cannot read private field names
    // through them and adding a private field is not a breaking change to a
    // `pub` array type. Any other struct visibility -- private, `pub(crate)`,
    // `pub(super)`, `pub(in ..)` -- reuses the struct's own visibility tokens
    // instead, so these consts are never wider than the struct they describe.
    // The `__STRUCT_PATH_PUB_FIELDS*` consts only ever list fields already
    // visible outside the crate, so they keep the struct's own visibility
    // unconditionally.
    let all_fields_visibility: TokenStream = if item_is_plain_pub {
        "pub(crate)".parse().expect("`pub(crate)` always parses")
    } else {
        visibility_tokens.clone()
    };

    // The three helpers below take a names array as a runtime-shaped
    // parameter rather than reading `Self::__STRUCT_PATH_*_FIELDS`
    // themselves, so paths!'s nested `Type::*` form can pass either the PUB
    // or the ALL array through the same three functions. Their own
    // visibility therefore stays at the struct's own tokens, the same as
    // `__STRUCT_PATH_PUB_FIELDS*` above, rather than the `pub(crate)` cap
    // applied to `__STRUCT_PATH_ALL_FIELDS*`: every `paths!` call that uses
    // the PUB array, including from a downstream crate, calls these
    // helpers too, so capping them the same way as the ALL array would
    // break that ordinary case, not just a downstream crate's use of ALL.
    let generated = fill(
        "impl<GENERICS_IMPL> NAME<GENERICS_TYPE> WHERE_CLAUSE {
            #[doc(hidden)]
            VIS const __STRUCT_PATH_PUB_FIELDS: [&'static str; N_PUB] = PUB_FIELDS;
            #[doc(hidden)]
            VIS const __STRUCT_PATH_PUB_FIELDS_CAMEL: [&'static str; N_PUB] = PUB_FIELDS_CAMEL;
            #[doc(hidden)]
            VIS const __STRUCT_PATH_PUB_FIELDS_PASCAL: [&'static str; N_PUB] = PUB_FIELDS_PASCAL;
            #[doc(hidden)]
            ALL_VIS const __STRUCT_PATH_ALL_FIELDS: [&'static str; N_ALL] = ALL_FIELDS;
            #[doc(hidden)]
            ALL_VIS const __STRUCT_PATH_ALL_FIELDS_CAMEL: [&'static str; N_ALL] = ALL_FIELDS_CAMEL;
            #[doc(hidden)]
            ALL_VIS const __STRUCT_PATH_ALL_FIELDS_PASCAL: [&'static str; N_ALL] = ALL_FIELDS_PASCAL;

            #[doc(hidden)]
            #[must_use]
            VIS const fn __struct_path_joined_len(prefix: &str, delim: &str, names: &[&str]) -> usize {
                let mut total = 0;
                let mut i = 0;
                while i < names.len() {
                    total += prefix.len() + delim.len() + names[i].len();
                    i += 1;
                }
                total
            }

            #[doc(hidden)]
            #[must_use]
            VIS const fn __struct_path_joined_bytes<const TOTAL: usize>(
                prefix: &str,
                delim: &str,
                names: &[&str],
            ) -> [u8; TOTAL] {
                let mut buf = [0u8; TOTAL];
                let mut pos = 0;
                let mut i = 0;
                while i < names.len() {
                    let parts = [prefix.as_bytes(), delim.as_bytes(), names[i].as_bytes()];
                    let mut p = 0;
                    while p < parts.len() {
                        let mut b = 0;
                        while b < parts[p].len() {
                            buf[pos] = parts[p][b];
                            pos += 1;
                            b += 1;
                        }
                        p += 1;
                    }
                    i += 1;
                }
                buf
            }

            #[doc(hidden)]
            #[must_use]
            VIS const fn __struct_path_joined<const N: usize, const TOTAL: usize>(
                bytes: &'static [u8; TOTAL],
                prefix: &str,
                delim: &str,
                names: &[&str; N],
            ) -> [&'static str; N] {
                let mut out = [\"\"; N];
                let mut pos = 0;
                let mut i = 0;
                while i < N {
                    let len = prefix.len() + delim.len() + names[i].len();
                    let (_, rest) = bytes.split_at(pos);
                    let (piece, _) = rest.split_at(len);
                    out[i] = match core::str::from_utf8(piece) {
                        Ok(s) => s,
                        Err(_) => panic!(\"struct-path: joined path is not valid UTF-8\"),
                    };
                    pos += len;
                    i += 1;
                }
                out
            }
        }",
        name_span,
        &[
            ("GENERICS_IMPL", &generics_impl),
            ("GENERICS_TYPE", &generics_type),
            ("NAME", &name_tokens),
            ("WHERE_CLAUSE", &where_clause),
            ("VIS", &visibility_tokens),
            ("ALL_VIS", &all_fields_visibility),
            ("N_PUB", &n_pub),
            ("N_ALL", &n_all),
            ("PUB_FIELDS", &pub_array),
            ("PUB_FIELDS_CAMEL", &pub_camel_array),
            ("PUB_FIELDS_PASCAL", &pub_pascal_array),
            ("ALL_FIELDS", &all_array),
            ("ALL_FIELDS_CAMEL", &all_camel_array),
            ("ALL_FIELDS_PASCAL", &all_pascal_array),
        ],
    );
    Ok(generated)
}

/// Skips a run of `#[...]` attributes (including `#[doc = "..."]` doc
/// comments), advancing `pos` past each one.
fn skip_attributes(tokens: &[TokenTree], pos: &mut usize) {
    while matches!(tokens.get(*pos), Some(TokenTree::Punct(p)) if *p == '#') {
        *pos += 1;
        if matches!(tokens.get(*pos), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket)
        {
            *pos += 1;
        }
    }
}

/// Reports how many raw tokens at the front of `tokens` are a `pub`/
/// `pub(...)` visibility prefix -- 0 for private, 1 for plain `pub`, 2 for
/// `pub(crate)`/`pub(super)`/`pub(in ..)` -- and whether that prefix is
/// plain `pub`. A `$v:vis`/`$fv:vis` macro_rules fragment reaches the derive
/// re-emitted as a `Group(Delimiter::None)`, empty when the fragment matched
/// private and containing the literal `pub`/`pub(...)` tokens otherwise;
/// this unwraps exactly one such group before classifying, and reports its
/// prefix length as the single outer token regardless of what was inside.
fn parse_visibility_prefix(tokens: &[TokenTree]) -> (usize, bool) {
    if let Some(TokenTree::Group(g)) = tokens.first() {
        if g.delimiter() == Delimiter::None {
            let inner: Vec<TokenTree> = g.stream().into_iter().collect();
            let (_, is_plain_pub) = parse_visibility_prefix(&inner);
            return (1, is_plain_pub);
        }
    }
    if matches!(tokens.first(), Some(TokenTree::Ident(id)) if id.to_string() == "pub") {
        if matches!(tokens.get(1), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
        {
            return (2, false);
        }
        return (1, true);
    }
    (0, false)
}

/// Advances `pos` past a field's visibility and reports whether it was
/// plain `pub`: `pub(crate)`, `pub(super)`, `pub(in ..)` and private fields
/// all return `false`, since none of them are visible outside the crate
/// the way plain `pub` is.
fn parse_field_visibility(tokens: &[TokenTree], pos: &mut usize) -> bool {
    let (len, is_plain_pub) = parse_visibility_prefix(&tokens[*pos..]);
    *pos += len;
    is_plain_pub
}

/// Splits `tokens` on commas that are not inside `<...>`, so a field's
/// type, e.g. `HashMap<String, u64>`, keeps its own comma out of the split.
/// Angle brackets are plain `Punct` tokens here, not a delimited `Group`, so
/// depth has to be tracked explicitly. A trailing comma produces no empty
/// trailing segment. Shared by generic-parameter and struct-field splitting.
///
/// The `>` of a `->` return-type arrow is not a closing angle bracket, so it
/// must not decrement `depth`; it is told apart from a real one by the `-`
/// immediately before it being tokenized `Joint` (no space before this `>`),
/// which is otherwise only true of operators Rust's grammar never places
/// right before `>`. Depth is also floored at 0, so a field list with no
/// generics at all (where an arrow's `>` would otherwise be the only `<`/`>`
/// seen) cannot be pushed negative and starve every comma split after it.
fn split_top_level_commas(tokens: &[TokenTree]) -> Vec<Vec<TokenTree>> {
    let mut segments = Vec::new();
    let mut current = Vec::new();
    let mut depth: i32 = 0;
    let mut prev_was_arrow_dash = false;
    for token in tokens {
        match token {
            TokenTree::Punct(p) if *p == '<' => {
                depth += 1;
                current.push(token.clone());
            }
            TokenTree::Punct(p) if *p == '>' => {
                if !prev_was_arrow_dash {
                    depth = (depth - 1).max(0);
                }
                current.push(token.clone());
            }
            TokenTree::Punct(p) if *p == ',' && depth == 0 => {
                segments.push(std::mem::take(&mut current));
            }
            other => current.push(other.clone()),
        }
        prev_was_arrow_dash =
            matches!(token, TokenTree::Punct(p) if *p == '-' && p.spacing() == Spacing::Joint);
    }
    if !current.is_empty() {
        segments.push(current);
    }
    segments
}

/// Recognizes a single generic parameter as a lifetime, optionally with
/// lifetime bounds (`'a`, `'a:`, or `'a: 'b + 'c`), and returns just the
/// bare `'a` tokens for use in the derived impl's `Name<'a>`. Returns `None`
/// for a type or const parameter, which `StructPath` does not support.
fn lifetime_param_name(segment: &[TokenTree]) -> Option<Vec<TokenTree>> {
    if segment.len() < 2 {
        return None;
    }
    if !matches!(&segment[0], TokenTree::Punct(p) if *p == '\'') {
        return None;
    }
    if !matches!(&segment[1], TokenTree::Ident(_)) {
        return None;
    }
    let bare = segment[0..2].to_vec();
    if segment.len() == 2 {
        return Some(bare);
    }
    if !matches!(&segment[2], TokenTree::Punct(p) if *p == ':') {
        return None;
    }
    if segment.len() == 3 {
        // `'a:` with no bound after the colon -- valid Rust, equivalent to
        // no colon at all.
        return Some(bare);
    }
    let mut i = 3;
    loop {
        if i + 1 >= segment.len() {
            return None;
        }
        let is_lifetime = matches!(&segment[i], TokenTree::Punct(p) if *p == '\'')
            && matches!(&segment[i + 1], TokenTree::Ident(_));
        if !is_lifetime {
            return None;
        }
        i += 2;
        if i == segment.len() {
            break;
        }
        if !matches!(&segment[i], TokenTree::Punct(p) if *p == '+') {
            return None;
        }
        i += 1;
    }
    Some(bare)
}

/// Parses the optional `<...>` generic parameter list starting at `*pos`,
/// advancing `pos` past it, and returns the tokens for `impl<GENERICS_IMPL>`
/// and the bare lifetime names for `Name<GENERICS_TYPE>`. Both are empty
/// when the struct has no generics.
fn parse_lifetime_generics(
    tokens: &[TokenTree],
    pos: &mut usize,
) -> Result<(TokenStream, TokenStream), TokenStream> {
    if !matches!(tokens.get(*pos), Some(TokenTree::Punct(p)) if *p == '<') {
        return Ok((TokenStream::new(), TokenStream::new()));
    }
    let open_span = match &tokens[*pos] {
        TokenTree::Punct(p) => p.span(),
        _ => unreachable!(),
    };
    *pos += 1;
    let start = *pos;
    let mut depth = 1;
    while depth > 0 {
        match tokens.get(*pos) {
            Some(TokenTree::Punct(p)) if *p == '<' => depth += 1,
            Some(TokenTree::Punct(p)) if *p == '>' => depth -= 1,
            Some(_) => {}
            None => {
                return Err(compile_error_at(
                    "StructPath: unterminated generic parameter list",
                    open_span,
                ))
            }
        }
        *pos += 1;
    }
    let generics_tokens = &tokens[start..*pos - 1];

    let mut bare_lifetimes: Vec<TokenTree> = Vec::new();
    for (i, segment) in split_top_level_commas(generics_tokens)
        .into_iter()
        .enumerate()
    {
        if i > 0 {
            bare_lifetimes.extend(fill(",", open_span, &[]));
        }
        match lifetime_param_name(&segment) {
            Some(bare) => bare_lifetimes.extend(bare),
            None => {
                let span = segment.first().map(|t| t.span()).unwrap_or(open_span);
                return Err(compile_error_at(
                    "StructPath only supports lifetime generic parameters",
                    span,
                ));
            }
        }
    }

    let generics_impl: TokenStream = generics_tokens.iter().cloned().collect();
    let generics_type: TokenStream = bare_lifetimes.into_iter().collect();
    Ok((generics_impl, generics_type))
}

/// Finds the struct's field body in `remaining` (everything after its name
/// and generics) and returns the `where` clause tokens in front of it, if
/// any, alongside it. The body's shape is read off the item's *last* token:
/// a `{ ... }` group for named fields (returned with any `where` clause
/// before it), or a trailing `;` for a tuple or unit struct (both rejected,
/// since only named fields have names to record). Deciding this from the
/// end, rather than scanning for the first `(...)` or `{...}` seen, is what
/// keeps a `(...)` written inside the `where` clause itself (e.g.
/// `where (): Sized`) from being mistaken for a tuple-struct body: nothing
/// before the item's own last token can be that body.
fn find_fields_group(remaining: &[TokenTree]) -> Result<(TokenStream, Group), TokenStream> {
    match remaining.last() {
        Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => {
            let where_clause: TokenStream =
                remaining[..remaining.len() - 1].iter().cloned().collect();
            Ok((where_clause, g.clone()))
        }
        Some(TokenTree::Punct(p)) if *p == ';' => match remaining.first() {
            Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis => {
                Err(compile_error_at(
                    "StructPath supports structs with named fields only, not tuple structs",
                    g.span(),
                ))
            }
            _ => Err(compile_error_at(
                "StructPath supports structs with named fields only, not unit structs",
                p.span(),
            )),
        },
        _ => Err(compile_error_at(
            "StructPath: expected a struct body with named fields",
            Span::call_site(),
        )),
    }
}

/// Parses a named-field struct body into its field names and plain-`pub`
/// flags, in declaration order. A field's type is skipped rather than
/// parsed: the derive never needs to reference a field's value, only its
/// name, so the type tokens (however they nest, e.g. `HashMap<String,
/// u64>`) are dropped once the name before the first top-level `:` is
/// found.
fn parse_derived_fields(fields_stream: TokenStream) -> Result<Vec<DerivedField>, TokenStream> {
    let tokens: Vec<TokenTree> = fields_stream.into_iter().collect();
    let mut fields = Vec::new();
    for segment in split_top_level_commas(&tokens) {
        let mut pos = 0;
        skip_attributes(&segment, &mut pos);
        let is_plain_pub = parse_field_visibility(&segment, &mut pos);
        let name_ident = match segment.get(pos) {
            Some(TokenTree::Ident(id)) => id,
            _ => {
                return Err(compile_error_at(
                    "StructPath: expected a field name",
                    segment
                        .first()
                        .map(|t| t.span())
                        .unwrap_or_else(Span::call_site),
                ))
            }
        };
        let name = name_ident.to_string();
        let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
        fields.push(DerivedField { name, is_plain_pub });
    }
    Ok(fields)
}

/// Builds a `[&'static str; N]` initializer literal from field-name
/// strings, which are always valid identifiers (or their camelCase/
/// PascalCase conversions), so no escaping beyond wrapping each one in
/// quotes is needed.
fn array_literal_tokens(values: &[String]) -> TokenStream {
    let joined = values
        .iter()
        .map(|v| format!("\"{}\"", v))
        .collect::<Vec<_>>()
        .join(",");
    format!("[{}]", joined)
        .parse()
        .expect("field names always produce a valid array literal")
}