utoipa_gen/
lib.rs

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
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
//! This is **private** utoipa codegen library and is not used alone.
//!
//! The library contains macro implementations for utoipa library. Content
//! of the library documentation is available through **utoipa** library itself.
//! Consider browsing via the **utoipa** crate so all links will work correctly.

#![warn(missing_docs)]
#![warn(rustdoc::broken_intra_doc_links)]

#[cfg(all(feature = "decimal", feature = "decimal_float"))]
compile_error!("`decimal` and `decimal_float` are mutually exclusive feature flags");

use std::{mem, ops::Deref};

use component::schema::Schema;
use doc_comment::CommentAttributes;

use component::into_params::IntoParams;
use ext::{PathOperationResolver, PathOperations, PathResolver};
use openapi::OpenApi;
use proc_macro::TokenStream;
use proc_macro_error::{abort, proc_macro_error};
use quote::{quote, ToTokens, TokenStreamExt};

use proc_macro2::{Group, Ident, Punct, Span, TokenStream as TokenStream2};
use syn::{
    bracketed,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    token::Bracket,
    DeriveInput, ExprPath, ItemFn, Lit, LitStr, Member, Token,
};

mod component;
mod doc_comment;
mod ext;
mod openapi;
mod path;
mod schema_type;
mod security_requirement;

use crate::path::{Path, PathAttr};

use self::{
    component::{
        features::{self, Feature},
        ComponentSchema, ComponentSchemaProps, TypeTree,
    },
    path::response::derive::{IntoResponses, ToResponse},
};

#[proc_macro_error]
#[proc_macro_derive(ToSchema, attributes(schema, aliases))]
/// Generate reusable OpenAPI schema to be used
/// together with [`OpenApi`][openapi_derive].
///
/// This is `#[derive]` implementation for [`ToSchema`][to_schema] trait. The macro accepts one
/// `schema`
/// attribute optionally which can be used to enhance generated documentation. The attribute can be placed
/// at item level or field level in struct and enums. Currently placing this attribute to unnamed field does
/// not have any effect.
///
/// You can use the Rust's own `#[deprecated]` attribute on any struct, enum or field to mark it as deprecated and it will
/// reflect to the generated OpenAPI spec.
///
/// `#[deprecated]` attribute supports adding additional details such as a reason and or since version but this is is not supported in
/// OpenAPI. OpenAPI has only a boolean flag to determine deprecation. While it is totally okay to declare deprecated with reason
/// `#[deprecated  = "There is better way to do this"]` the reason would not render in OpenAPI spec.
///
/// Doc comments on fields will resolve to field descriptions in generated OpenAPI doc. On struct
/// level doc comments will resolve to object descriptions.
///
/// ```rust
/// /// This is a pet
/// #[derive(utoipa::ToSchema)]
/// struct Pet {
///     /// Name for your pet
///     name: String,
/// }
/// ```
///
/// # Struct Optional Configuration Options for `#[schema(...)]`
/// * `example = ...` Can be _`json!(...)`_. _`json!(...)`_ should be something that
///   _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
/// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to Structs.
/// * `title = ...` Literal string value. Can be used to define title for struct in OpenAPI
///   document. Some OpenAPI code generation libraries also use this field as a name for the
///   struct.
/// * `rename_all = ...` Supports same syntax as _serde_ _`rename_all`_ attribute. Will rename all fields
///   of the structs accordingly. If both _serde_ `rename_all` and _schema_ _`rename_all`_ are defined
///   __serde__ will take precedence.
/// * `as = ...` Can be used to define alternative path and name for the schema what will be used in
///   the OpenAPI. E.g _`as = path::to::Pet`_. This would make the schema appear in the generated
///   OpenAPI spec as _`path.to.Pet`_.
/// * `default` Can be used to populate default values on all fields using the struct's
///   [`Default`](std::default::Default) implementation.
/// * `deprecated` Can be used to mark all fields as deprecated in the generated OpenAPI spec but
///   not in the code. If you'd like to mark the fields as deprecated in the code as well use
///   Rust's own `#[deprecated]` attribute instead.

/// # Enum Optional Configuration Options for `#[schema(...)]`
/// * `example = ...` Can be method reference or _`json!(...)`_.
/// * `default = ...` Can be method reference or _`json!(...)`_.
/// * `title = ...` Literal string value. Can be used to define title for enum in OpenAPI
///   document. Some OpenAPI code generation libraries also use this field as a name for the
///   enum. __Note!__  ___Complex enum (enum with other than unit variants) does not support title!___
/// * `rename_all = ...` Supports same syntax as _serde_ _`rename_all`_ attribute. Will rename all
///   variants of the enum accordingly. If both _serde_ `rename_all` and _schema_ _`rename_all`_
///   are defined __serde__ will take precedence.
/// * `as = ...` Can be used to define alternative path and name for the schema what will be used in
///   the OpenAPI. E.g _`as = path::to::Pet`_. This would make the schema appear in the generated
///   OpenAPI spec as _`path.to.Pet`_.
/// * `deprecated` Can be used to mark the enum as deprecated in the generated OpenAPI spec but
///   not in the code. If you'd like to mark the enum as deprecated in the code as well use
///   Rust's own `#[deprecated]` attribute instead.
///
/// # Enum Variant Optional Configuration Options for `#[schema(...)]`
/// Supports all variant specific configuration options e.g. if variant is _`UnnamedStruct`_ then
/// unnamed struct type configuration options are supported.
///
/// In addition to the variant type specific configuration options enum variants support custom
/// _`rename`_ attribute. It behaves similarly to serde's _`rename`_ attribute. If both _serde_
/// _`rename`_ and _schema_ _`rename`_ are defined __serde__ will take precedence.
///
/// # Unnamed Field Struct Optional Configuration Options for `#[schema(...)]`
/// * `example = ...` Can be method reference or _`json!(...)`_.
/// * `default = ...` Can be method reference or _`json!(...)`_. If no value is specified, and the struct has
///   only one field, the field's default value in the schema will be set from the struct's
///   [`Default`](std::default::Default) implementation.
/// * `format = ...` May either be variant of the [`KnownFormat`][known_format] enum, or otherwise
///   an open value as a string. By default the format is derived from the type of the property
///   according OpenApi spec.
/// * `value_type = ...` Can be used to override default type derived from type of the field used in OpenAPI spec.
///   This is useful in cases where the default type does not correspond to the actual type e.g. when
///   any third-party types are used which are not [`ToSchema`][to_schema]s nor [`primitive` types][primitive].
///   The value can be any Rust type what normally could be used to serialize to JSON or either virtual type _`Object`_
///   or _`Value`_, or an alias defined using `#[aliases(..)]`.
///   _`Object`_ will be rendered as generic OpenAPI object _(`type: object`)_.
///   _`Value`_ will be rendered as any OpenAPI value (i.e. no `type` restriction).
/// * `title = ...` Literal string value. Can be used to define title for struct in OpenAPI
///   document. Some OpenAPI code generation libraries also use this field as a name for the
///   struct.
/// * `as = ...` Can be used to define alternative path and name for the schema what will be used in
///   the OpenAPI. E.g _`as = path::to::Pet`_. This would make the schema appear in the generated
///   OpenAPI spec as _`path.to.Pet`_.
/// * `deprecated` Can be used to mark the field as deprecated in the generated OpenAPI spec but
///   not in the code. If you'd like to mark the field as deprecated in the code as well use
///   Rust's own `#[deprecated]` attribute instead.
///
/// # Named Fields Optional Configuration Options for `#[schema(...)]`
/// * `example = ...` Can be method reference or _`json!(...)`_.
/// * `default = ...` Can be method reference or _`json!(...)`_.
/// * `format = ...` May either be variant of the [`KnownFormat`][known_format] enum, or otherwise
///   an open value as a string. By default the format is derived from the type of the property
///   according OpenApi spec.
/// * `write_only` Defines property is only used in **write** operations *POST,PUT,PATCH* but not in *GET*
/// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH*
/// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to named fields.
///    See configuration options at xml attributes of [`ToSchema`][to_schema_xml]
/// * `value_type = ...` Can be used to override default type derived from type of the field used in OpenAPI spec.
///   This is useful in cases where the default type does not correspond to the actual type e.g. when
///   any third-party types are used which are not [`ToSchema`][to_schema]s nor [`primitive` types][primitive].
///   The value can be any Rust type what normally could be used to serialize to JSON, or either virtual type _`Object`_
///   or _`Value`_, or an alias defined using `#[aliases(..)]`.
///   _`Object`_ will be rendered as generic OpenAPI object _(`type: object`)_.
///   _`Value`_ will be rendered as any OpenAPI value (i.e. no `type` restriction).
/// * `inline` If the type of this field implements [`ToSchema`][to_schema], then the schema definition
///   will be inlined. **warning:** Don't use this for recursive data types!
/// * `required = ...` Can be used to enforce required status for the field. [See
///   rules][derive@ToSchema#field-nullability-and-required-rules]
/// * `nullable` Defines property is nullable (note this is different to non-required).
/// * `rename = ...` Supports same syntax as _serde_ _`rename`_ attribute. Will rename field
///   accordingly. If both _serde_ `rename` and _schema_ _`rename`_ are defined __serde__ will take
///   precedence.
/// * `multiple_of = ...` Can be used to define multiplier for a value. Value is considered valid
///   division will result an `integer`. Value must be strictly above _`0`_.
/// * `maximum = ...` Can be used to define inclusive upper bound to a `number` value.
/// * `minimum = ...` Can be used to define inclusive lower bound to a `number` value.
/// * `exclusive_maximum = ...` Can be used to define exclusive upper bound to a `number` value.
/// * `exclusive_minimum = ...` Can be used to define exclusive lower bound to a `number` value.
/// * `max_length = ...` Can be used to define maximum length for `string` types.
/// * `min_length = ...` Can be used to define minimum length for `string` types.
/// * `pattern = ...` Can be used to define valid regular expression in _ECMA-262_ dialect the field value must match.
/// * `max_items = ...` Can be used to define maximum items allowed for `array` fields. Value must
///   be non-negative integer.
/// * `min_items = ...` Can be used to define minimum items allowed for `array` fields. Value must
///   be non-negative integer.
/// * `schema_with = ...` Use _`schema`_ created by provided function reference instead of the
///   default derived _`schema`_. The function must match to `fn() -> Into<RefOr<Schema>>`. It does
///   not accept arguments and must return anything that can be converted into `RefOr<Schema>`.
/// * `additional_properties = ...` Can be used to define free form types for maps such as
///   [`HashMap`](std::collections::HashMap) and [`BTreeMap`](std::collections::BTreeMap).
///   Free form type enables use of arbitrary types within map values.
///   Supports formats _`additional_properties`_ and _`additional_properties = true`_.
/// * `deprecated` Can be used to mark the field as deprecated in the generated OpenAPI spec but
///   not in the code. If you'd like to mark the field as deprecated in the code as well use
///   Rust's own `#[deprecated]` attribute instead.
///
/// #### Field nullability and required rules
///
/// Field is considered _`required`_ if
/// * it is not `Option` field
/// * and it does not have _`skip_serializing_if`_ property
/// * and it does not have _`serde_with`_ _[`double_option`](https://docs.rs/serde_with/latest/serde_with/rust/double_option/index.html)_
/// * and it does not have default value provided with serde _`default`_
///   attribute
///
/// Field is considered _`nullable`_ when field type is _`Option`_.
///
/// ## Xml attribute Configuration Options
///
/// * `xml(name = "...")` Will set name for property or type.
/// * `xml(namespace = "...")` Will set namespace for xml element which needs to be valid uri.
/// * `xml(prefix = "...")` Will set prefix for name.
/// * `xml(attribute)` Will translate property to xml attribute instead of xml element.
/// * `xml(wrapped)` Will make wrapped xml element.
/// * `xml(wrapped(name = "wrap_name"))` Will override the wrapper elements name.
///
/// See [`Xml`][xml] for more details.
///
/// # Partial `#[serde(...)]` attributes support
///
/// ToSchema derive has partial support for [serde attributes]. These supported attributes will reflect to the
/// generated OpenAPI doc. For example if _`#[serde(skip)]`_ is defined the attribute will not show up in the OpenAPI spec at all since it will not never
/// be serialized anyway. Similarly the _`rename`_ and _`rename_all`_ will reflect to the generated OpenAPI doc.
///
/// * `rename_all = "..."` Supported at the container level.
/// * `rename = "..."` Supported **only** at the field or variant level.
/// * `skip = "..."` Supported  **only** at the field or variant level.
/// * `skip_serializing = "..."` Supported  **only** at the field or variant level.
/// * `skip_deserializing = "..."` Supported  **only** at the field or variant level.
/// * `skip_serializing_if = "..."` Supported  **only** at the field level.
/// * `with = ...` Supported **only at field level.**
/// * `tag = "..."` Supported at the container level. `tag` attribute works as a [discriminator field][discriminator] for an enum.
/// * `content = "..."` Supported at the container level, allows [adjacently-tagged enums](https://serde.rs/enum-representations.html#adjacently-tagged).
///   This attribute requires that a `tag` is present, otherwise serde will trigger a compile-time
///   failure.
/// * `untagged` Supported at the container level. Allows [untagged
/// enum representation](https://serde.rs/enum-representations.html#untagged).
/// * `default` Supported at the container level and field level according to [serde attributes].
/// * `deny_unknown_fields` Supported at the container level.
/// * `flatten` Supported at the field level.
///
/// Other _`serde`_ attributes works as is but does not have any effect on the generated OpenAPI doc.
///
/// **Note!** `tag` attribute has some limitations like it cannot be used
/// with **unnamed field structs** and **tuple types**.  See more at
/// [enum representation docs](https://serde.rs/enum-representations.html).
///
/// **Note!** `with` attribute is used in tandem with [serde_with](https://github.com/jonasbb/serde_with) to recognize
/// _[`double_option`](https://docs.rs/serde_with/latest/serde_with/rust/double_option/index.html)_ from **field value**.
/// _`double_option`_ is **only** supported attribute from _`serde_with`_ crate.
///
/// ```rust
/// # use serde::Serialize;
/// # use utoipa::ToSchema;
/// #[derive(Serialize, ToSchema)]
/// struct Foo(String);
///
/// #[derive(Serialize, ToSchema)]
/// #[serde(rename_all = "camelCase")]
/// enum Bar {
///     UnitValue,
///     #[serde(rename_all = "camelCase")]
///     NamedFields {
///         #[serde(rename = "id")]
///         named_id: &'static str,
///         name_list: Option<Vec<String>>
///     },
///     UnnamedFields(Foo),
///     #[serde(skip)]
///     SkipMe,
/// }
/// ```
///
/// _**Add custom `tag` to change JSON representation to be internally tagged.**_
/// ```rust
/// # use serde::Serialize;
/// # use utoipa::ToSchema;
/// #[derive(Serialize, ToSchema)]
/// struct Foo(String);
///
/// #[derive(Serialize, ToSchema)]
/// #[serde(tag = "tag")]
/// enum Bar {
///     UnitValue,
///     NamedFields {
///         id: &'static str,
///         names: Option<Vec<String>>
///     },
/// }
/// ```
///
/// _**Add serde `default` attribute for MyValue struct. Similarly `default` could be added to
/// individual fields as well. If `default` is given the field's affected will be treated
/// as optional.**_
/// ```rust
///  #[derive(utoipa::ToSchema, serde::Deserialize, Default)]
///  #[serde(default)]
///  struct MyValue {
///      field: String
///  }
/// ```
///
/// # `#[repr(...)]` attribute support
///
/// [Serde repr](https://github.com/dtolnay/serde-repr) allows field-less enums be represented by
/// their numeric value.
///
/// * `repr(u*)` for unsigned integer.
/// * `repr(i*)` for signed integer.
///
/// **Supported schema attributes**
///
/// * `example = ...` Can be method reference or _`json!(...)`_.
/// * `default = ...` Can be method reference or _`json!(...)`_.
/// * `title = ...` Literal string value. Can be used to define title for enum in OpenAPI
///   document. Some OpenAPI code generation libraries also use this field as a name for the
///   enum. __Note!__  ___Complex enum (enum with other than unit variants) does not support title!___
/// * `as = ...` Can be used to define alternative path and name for the schema what will be used in
///   the OpenAPI. E.g _`as = path::to::Pet`_. This would make the schema appear in the generated
///   OpenAPI spec as _`path.to.Pet`_.
///
/// _**Create enum with numeric values.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// #[repr(u8)]
/// #[schema(default = default_value, example = 2)]
/// enum Mode {
///     One = 1,
///     Two,
///  }
///
/// fn default_value() -> u8 {
///     1
/// }
/// ```
///
/// _**You can use `skip` and `tag` attributes from serde.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema, serde::Serialize)]
/// #[repr(i8)]
/// #[serde(tag = "code")]
/// enum ExitCode {
///     Error = -1,
///     #[serde(skip)]
///     Unknown = 0,
///     Ok = 1,
///  }
/// ```
///
/// # Generic schemas with aliases
///
/// Schemas can also be generic which allows reusing types. This enables certain behaviour patterns
/// where super type declares common code for type aliases.
///
/// In this example we have common `Status` type which accepts one generic type. It is then defined
/// with `#[aliases(...)]` that it is going to be used with [`String`](std::string::String) and [`i32`] values.
/// The generic argument could also be another [`ToSchema`][to_schema] as well.
/// ```rust
/// # use utoipa::{ToSchema, OpenApi};
/// #[derive(ToSchema)]
/// #[aliases(StatusMessage = Status<String>, StatusNumber = Status<i32>)]
/// struct Status<T> {
///     value: T
/// }
///
/// #[derive(OpenApi)]
/// #[openapi(
///     components(schemas(StatusMessage, StatusNumber))
/// )]
/// struct ApiDoc;
/// ```
///
/// The `#[aliases(...)]` is just syntactic sugar and will create Rust [type aliases](https://doc.rust-lang.org/reference/items/type-aliases.html)
/// behind the scenes which then can be later referenced anywhere in code.
///
/// **Note!** You should never register generic type itself in `components(...)` so according above example `Status<...>` should not be registered
/// because it will not render the type correctly and will cause an error in generated OpenAPI spec.
///
/// # Examples
///
/// _**Simple example of a Pet with descriptions and object level example.**_
/// ```rust
/// # use utoipa::ToSchema;
/// /// This is a pet.
/// #[derive(ToSchema)]
/// #[schema(example = json!({"name": "bob the cat", "id": 0}))]
/// struct Pet {
///     /// Unique id of a pet.
///     id: u64,
///     /// Name of a pet.
///     name: String,
///     /// Age of a pet if known.
///     age: Option<i32>,
/// }
/// ```
///
/// _**The `schema` attribute can also be placed at field level as follows.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// struct Pet {
///     #[schema(example = 1, default = 0)]
///     id: u64,
///     name: String,
///     age: Option<i32>,
/// }
/// ```
///
/// _**You can also use method reference for attribute values.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// struct Pet {
///     #[schema(example = u64::default, default = u64::default)]
///     id: u64,
///     #[schema(default = default_name)]
///     name: String,
///     age: Option<i32>,
/// }
///
/// fn default_name() -> String {
///     "bob".to_string()
/// }
/// ```
///
/// _**For enums and unnamed field structs you can define `schema` at type level.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// #[schema(example = "Bus")]
/// enum VehicleType {
///     Rocket, Car, Bus, Submarine
/// }
/// ```
///
/// _**Also you write complex enum combining all above types.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// enum ErrorResponse {
///     InvalidCredentials,
///     #[schema(default = String::default, example = "Pet not found")]
///     NotFound(String),
///     System {
///         #[schema(example = "Unknown system failure")]
///         details: String,
///     }
/// }
/// ```
///
/// _**It is possible to specify the title of each variant to help generators create named structures.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// enum ErrorResponse {
///     #[schema(title = "InvalidCredentials")]
///     InvalidCredentials,
///     #[schema(title = "NotFound")]
///     NotFound(String),
/// }
/// ```
///
/// _**Use `xml` attribute to manipulate xml output.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// #[schema(xml(name = "user", prefix = "u", namespace = "https://user.xml.schema.test"))]
/// struct User {
///     #[schema(xml(attribute, prefix = "u"))]
///     id: i64,
///     #[schema(xml(name = "user_name", prefix = "u"))]
///     username: String,
///     #[schema(xml(wrapped(name = "linkList"), name = "link"))]
///     links: Vec<String>,
///     #[schema(xml(wrapped, name = "photo_url"))]
///     photos_urls: Vec<String>
/// }
/// ```
///
/// _**Use of Rust's own `#[deprecated]` attribute will reflect to generated OpenAPI spec.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// #[deprecated]
/// struct User {
///     id: i64,
///     username: String,
///     links: Vec<String>,
///     #[deprecated]
///     photos_urls: Vec<String>
/// }
/// ```
///
/// _**Enforce type being used in OpenAPI spec to [`String`] with `value_type` and set format to octet stream
/// with [`SchemaFormat::KnownFormat(KnownFormat::Binary)`][binary].**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// struct Post {
///     id: i32,
///     #[schema(value_type = String, format = Binary)]
///     value: Vec<u8>,
/// }
/// ```
///
/// _**Enforce type being used in OpenAPI spec to [`String`] with `value_type` option.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #[derive(ToSchema)]
/// #[schema(value_type = String)]
/// struct Value(i64);
/// ```
///
/// _**Override the `Bar` reference with a `custom::NewBar` reference.**_
/// ```rust
/// # use utoipa::ToSchema;
/// #  mod custom {
/// #      struct NewBar;
/// #  }
/// #
/// # struct Bar;
/// #[derive(ToSchema)]
/// struct Value {
///     #[schema(value_type = custom::NewBar)]
///     field: Bar,
/// };
/// ```
///
/// _**Use a virtual `Object` type to render generic `object` _(`type: object`)_ in OpenAPI spec.**_
/// ```rust
/// # use utoipa::ToSchema;
/// # mod custom {
/// #    struct NewBar;
/// # }
/// #
/// # struct Bar;
/// #[derive(ToSchema)]
/// struct Value {
///     #[schema(value_type = Object)]
///     field: Bar,
/// };
/// ```
///
/// _**Serde `rename` / `rename_all` will take precedence over schema `rename` / `rename_all`.**_
/// ```rust
/// #[derive(utoipa::ToSchema, serde::Deserialize)]
/// #[serde(rename_all = "lowercase")]
/// #[schema(rename_all = "UPPERCASE")]
/// enum Random {
///     #[serde(rename = "string_value")]
///     #[schema(rename = "custom_value")]
///     String(String),
///
///     Number {
///         id: i32,
///     }
/// }
/// ```
///
/// _**Add `title` to the enum.**_
/// ```rust
/// #[derive(utoipa::ToSchema)]
/// #[schema(title = "UserType")]
/// enum UserType {
///     Admin,
///     Moderator,
///     User,
/// }
/// ```
///
/// _**Example with validation attributes.**_
/// ```rust
/// #[derive(utoipa::ToSchema)]
/// struct Item {
///     #[schema(maximum = 10, minimum = 5, multiple_of = 2.5)]
///     id: i32,
///     #[schema(max_length = 10, min_length = 5, pattern = "[a-z]*")]
///     value: String,
///     #[schema(max_items = 5, min_items = 1)]
///     items: Vec<String>,
/// }
/// ````
///
/// _**Use `schema_with` to manually implement schema for a field.**_
/// ```rust
/// # use utoipa::openapi::schema::{Object, ObjectBuilder};
/// fn custom_type() -> Object {
///     ObjectBuilder::new()
///         .schema_type(utoipa::openapi::SchemaType::String)
///         .format(Some(utoipa::openapi::SchemaFormat::Custom(
///             "email".to_string(),
///         )))
///         .description(Some("this is the description"))
///         .build()
/// }
///
/// #[derive(utoipa::ToSchema)]
/// struct Value {
///     #[schema(schema_with = custom_type)]
///     id: String,
/// }
/// ```
///
/// _**Use `as` attribute to change the name and the path of the schema in the generated OpenAPI
/// spec.**_
/// ```rust
///  #[derive(utoipa::ToSchema)]
///  #[schema(as = api::models::person::Person)]
///  struct Person {
///      name: String,
///  }
/// ```
///
/// More examples for _`value_type`_ in [`IntoParams` derive docs][into_params].
///
/// [to_schema]: trait.ToSchema.html
/// [known_format]: openapi/schema/enum.KnownFormat.html
/// [binary]: openapi/schema/enum.KnownFormat.html#variant.Binary
/// [xml]: openapi/xml/struct.Xml.html
/// [into_params]: derive.IntoParams.html
/// [primitive]: https://doc.rust-lang.org/std/primitive/index.html
/// [serde attributes]: https://serde.rs/attributes.html
/// [discriminator]: openapi/schema/struct.Discriminator.html
/// [enum_schema]: derive.ToSchema.html#enum-optional-configuration-options-for-schema
/// [openapi_derive]: derive.OpenApi.html
/// [to_schema_xml]: macro@ToSchema#xml-attribute-configuration-options
pub fn derive_to_schema(input: TokenStream) -> TokenStream {
    let DeriveInput {
        attrs,
        ident,
        data,
        generics,
        vis,
    } = syn::parse_macro_input!(input);

    let schema = Schema::new(&data, &attrs, &ident, &generics, &vis);

    schema.to_token_stream().into()
}

#[proc_macro_error]
#[proc_macro_attribute]
/// Path attribute macro implements OpenAPI path for the decorated function.
///
/// This is a `#[derive]` implementation for [`Path`][path] trait. Macro accepts set of attributes that can
/// be used to configure and override default values what are resolved automatically.
///
/// You can use the Rust's own `#[deprecated]` attribute on functions to mark it as deprecated and it will
/// reflect to the generated OpenAPI spec. Only **parameters** has a special **deprecated** attribute to define them as deprecated.
///
/// `#[deprecated]` attribute supports adding additional details such as a reason and or since version but this is is not supported in
/// OpenAPI. OpenAPI has only a boolean flag to determine deprecation. While it is totally okay to declare deprecated with reason
/// `#[deprecated  = "There is better way to do this"]` the reason would not render in OpenAPI spec.
///
/// Doc comment at decorated function will be used for _`description`_ and _`summary`_ of the path.
/// First line of the doc comment will be used as the _`summary`_ while the remaining lines will be
/// used as _`description`_.
/// ```rust
/// /// This is a summary of the operation
/// ///
/// /// The rest of the doc comment will be included to operation description.
/// #[utoipa::path(get, path = "/operation")]
/// fn operation() {}
/// ```
///
/// # Path Attributes
///
/// * `operation` _**Must be first parameter!**_ Accepted values are known http operations such as
///   _`get, post, put, delete, head, options, connect, patch, trace`_.
///
/// * `path = "..."` Must be OpenAPI format compatible str with arguments within curly braces. E.g _`{id}`_
///
/// * `impl_for = ...` Optional type to implement the [`Path`][path] trait. By default a new type
///   is used for the implementation.
///
/// * `operation_id = ...` Unique operation id for the endpoint. By default this is mapped to function name.
///   The operation_id can be any valid expression (e.g. string literals, macro invocations, variables) so long
///   as its result can be converted to a `String` using `String::from`.
///
/// * `context_path = "..."` Can add optional scope for **path**. The **context_path** will be prepended to beginning of **path**.
///   This is particularly useful when **path** does not contain the full path to the endpoint. For example if web framework
///   allows operation to be defined under some context path or scope which does not reflect to the resolved path then this
///   **context_path** can become handy to alter the path.
///
/// * `tag = "..."` Can be used to group operations. Operations with same tag are grouped together. By default
///   this is derived from the handler that is given to [`OpenApi`][openapi]. If derive results empty str
///   then default value _`crate`_ is used instead.
///
/// * `request_body = ... | request_body(...)` Defining request body indicates that the request is expecting request body within
///   the performed request.
///
/// * `responses(...)` Slice of responses the endpoint is going to possibly return to the caller.
///
/// * `params(...)` Slice of params that the endpoint accepts.
///
/// * `security(...)` List of [`SecurityRequirement`][security]s local to the path operation.
///
/// # Request Body Attributes
///
/// **Simple format definition by `request_body = ...`**
/// * _`request_body = Type`_, _`request_body = inline(Type)`_ or _`request_body = ref("...")`_.
///   The given _`Type`_ can be any Rust type that is JSON parseable. It can be Option, Vec or Map etc.
///   With _`inline(...)`_ the schema will be inlined instead of a referenced which is the default for
///   [`ToSchema`][to_schema] types. _`ref("./external.json")`_ can be used to reference external
///   json file for body schema. **Note!** Utoipa does **not** guarantee that free form _`ref`_ is accessible via
///   OpenAPI doc or Swagger UI, users are responsible for making these guarantees.
///
/// **Advanced format definition by `request_body(...)`**
/// * `content = ...` Can be _`content = Type`_, _`content = inline(Type)`_ or _`content = ref("...")`_. The
///   given _`Type`_ can be any Rust type that is JSON parseable. It can be Option, Vec
///   or Map etc. With _`inline(...)`_ the schema will be inlined instead of a referenced
///   which is the default for [`ToSchema`][to_schema] types. _`ref("./external.json")`_
///   can be used to reference external json file for body schema. **Note!** Utoipa does **not** guarantee
///   that free form _`ref`_ is accessible via OpenAPI doc or Swagger UI, users are responsible for making
///   these guarantees.
///
/// * `description = "..."` Define the description for the request body object as str.
///
/// * `content_type = "..."` Can be used to override the default behavior of auto resolving the content type
///   from the `content` attribute. If defined the value should be valid content type such as
///   _`application/json`_. By default the content type is _`text/plain`_ for
///   [primitive Rust types][primitive], `application/octet-stream` for _`[u8]`_ and
///   _`application/json`_ for struct and complex enum types.
///
/// * `example = ...` Can be _`json!(...)`_. _`json!(...)`_ should be something that
///   _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///
/// * `examples(...)` Define multiple examples for single request body. This attribute is mutually
///   exclusive to the _`example`_ attribute and if both are defined this will override the _`example`_.
///   This has same syntax as _`examples(...)`_ in [Response Attributes](#response-attributes)
///   _examples(...)_
///
/// _**Example request body definitions.**_
/// ```text
///  request_body(content = String, description = "Xml as string request", content_type = "text/xml"),
///  request_body = Pet,
///  request_body = Option<[Pet]>,
/// ```
///
/// # Response Attributes
///
/// * `status = ...` Is either a valid http status code integer. E.g. _`200`_ or a string value representing
///   a range such as _`"4XX"`_ or `"default"` or a valid _`http::status::StatusCode`_.
///   _`StatusCode`_ can either be use path to the status code or _status code_ constant directly.
///
/// * `description = "..."` Define description for the response as str.
///
/// * `body = ...` Optional response body object type. When left empty response does not expect to send any
///   response body. Can be _`body = Type`_, _`body = inline(Type)`_, or _`body = ref("...")`_.
///   The given _`Type`_ can be any Rust type that is JSON parseable. It can be Option, Vec or Map etc.
///   With _`inline(...)`_ the schema will be inlined instead of a referenced which is the default for
///   [`ToSchema`][to_schema] types. _`ref("./external.json")`_
///   can be used to reference external json file for body schema. **Note!** Utoipa does **not** guarantee
///   that free form _`ref`_ is accessible via OpenAPI doc or Swagger UI, users are responsible for making
///   these guarantees.
///
/// * `content_type = "..." | content_type = [...]` Can be used to override the default behavior of auto resolving the content type
///   from the `body` attribute. If defined the value should be valid content type such as
///   _`application/json`_. By default the content type is _`text/plain`_ for
///   [primitive Rust types][primitive], `application/octet-stream` for _`[u8]`_ and
///   _`application/json`_ for struct and complex enum types.
///   Content type can also be slice of **content_type** values if the endpoint support returning multiple
///  response content types. E.g _`["application/json", "text/xml"]`_ would indicate that endpoint can return both
///  _`json`_ and _`xml`_ formats. **The order** of the content types define the default example show first in
///  the Swagger UI. Swagger UI will use the first _`content_type`_ value as a default example.
///
/// * `headers(...)` Slice of response headers that are returned back to a caller.
///
/// * `example = ...` Can be _`json!(...)`_. _`json!(...)`_ should be something that
///   _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///
/// * `response = ...` Type what implements [`ToResponse`][to_response_trait] trait. This can alternatively be used to
///    define response attributes. _`response`_ attribute cannot co-exist with other than _`status`_ attribute.
///
/// * `content((...), (...))` Can be used to define multiple return types for single response status. Supported format for single
///   _content_ is `(content_type = response_body, example = "...", examples(...))`. _`example`_
///   and _`examples`_ are optional arguments. Examples attribute behaves exactly same way as in
///   the response and is mutually exclusive with the example attribute.
///
/// * `examples(...)` Define multiple examples for single response. This attribute is mutually
///   exclusive to the _`example`_ attribute and if both are defined this will override the _`example`_.
///     * `name = ...` This is first attribute and value must be literal string.
///     * `summary = ...` Short description of example. Value must be literal string.
///     * `description = ...` Long description of example. Attribute supports markdown for rich text
///       representation. Value must be literal string.
///     * `value = ...` Example value. It must be _`json!(...)`_. _`json!(...)`_ should be something that
///       _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///     * `external_value = ...` Define URI to literal example value. This is mutually exclusive to
///       the _`value`_ attribute. Value must be literal string.
///
///      _**Example of example definition.**_
///     ```text
///      ("John" = (summary = "This is John", value = json!({"name": "John"})))
///     ```
///
/// **Minimal response format:**
/// ```text
/// responses(
///     (status = 200, description = "success response"),
///     (status = 404, description = "resource missing"),
///     (status = "5XX", description = "server error"),
///     (status = StatusCode::INTERNAL_SERVER_ERROR, description = "internal server error"),
///     (status = IM_A_TEAPOT, description = "happy easter")
/// )
/// ```
///
/// **More complete Response:**
/// ```text
/// responses(
///     (status = 200, description = "Success response", body = Pet, content_type = "application/json",
///         headers(...),
///         example = json!({"id": 1, "name": "bob the cat"})
///     )
/// )
/// ```
///
/// **Response with multiple response content types:**
/// ```text
/// responses(
///     (status = 200, description = "Success response", body = Pet, content_type = ["application/json", "text/xml"])
/// )
/// ```
///
/// **Multiple response return types with _`content(...)`_ attribute:**
///
/// _**Define multiple response return types for single response status with their own example.**_
/// ```text
/// responses(
///    (status = 200, content(
///            ("application/vnd.user.v1+json" = User, example = json!(User {id: "id".to_string()})),
///            ("application/vnd.user.v2+json" = User2, example = json!(User2 {id: 2}))
///        )
///    )
/// )
/// ```
///
/// ### Using `ToResponse` for reusable responses
///
/// _**`ReusableResponse` must be a type that implements [`ToResponse`][to_response_trait].**_
/// ```text
/// responses(
///     (status = 200, response = ReusableResponse)
/// )
/// ```
///
/// _**[`ToResponse`][to_response_trait] can also be inlined to the responses map.**_
/// ```text
/// responses(
///     (status = 200, response = inline(ReusableResponse))
/// )
/// ```
///
/// ## Responses from `IntoResponses`
///
/// _**Responses for a path can be specified with one or more types that implement
/// [`IntoResponses`][into_responses_trait].**_
/// ```text
/// responses(MyResponse)
/// ```
///
/// # Response Header Attributes
///
/// * `name` Name of the header. E.g. _`x-csrf-token`_
///
/// * `type` Additional type of the header value. Can be `Type` or `inline(Type)`.
///   The given _`Type`_ can be any Rust type that is JSON parseable. It can be Option, Vec or Map etc.
///   With _`inline(...)`_ the schema will be inlined instead of a referenced which is the default for
///   [`ToSchema`][to_schema] types. **Reminder!** It's up to the user to use valid type for the
///   response header.
///
/// * `description = "..."` Can be used to define optional description for the response header as str.
///
/// **Header supported formats:**
///
/// ```text
/// ("x-csrf-token"),
/// ("x-csrf-token" = String, description = "New csrf token"),
/// ```
///
/// # Params Attributes
///
/// The list of attributes inside the `params(...)` attribute can take two forms: [Tuples](#tuples) or [IntoParams
/// Type](#intoparams-type).
///
/// ## Tuples
///
/// In the tuples format, parameters are specified using the following attributes inside a list of
/// tuples separated by commas:
///
/// * `name` _**Must be the first argument**_. Define the name for parameter.
///
/// * `parameter_type` Define possible type for the parameter. Can be `Type` or `inline(Type)`.
///   The given _`Type`_ can be any Rust type that is JSON parseable. It can be Option, Vec or Map etc.
///   With _`inline(...)`_ the schema will be inlined instead of a referenced which is the default for
///   [`ToSchema`][to_schema] types. Parameter type is placed after `name` with
///   equals sign E.g. _`"id" = String`_
///
/// * `in` _**Must be placed after name or parameter_type**_. Define the place of the parameter.
///   This must be one of the variants of [`openapi::path::ParameterIn`][in_enum].
///   E.g. _`Path, Query, Header, Cookie`_
///
/// * `deprecated` Define whether the parameter is deprecated or not. Can optionally be defined
///    with explicit `bool` value as _`deprecated = bool`_.
///
/// * `description = "..."` Define possible description for the parameter as str.
///
/// * `style = ...` Defines how parameters are serialized by [`ParameterStyle`][style]. Default values are based on _`in`_ attribute.
///
/// * `explode` Defines whether new _`parameter=value`_ is created for each parameter within _`object`_ or _`array`_.
///
/// * `allow_reserved` Defines whether reserved characters _`:/?#[]@!$&'()*+,;=`_ is allowed within value.
///
/// * `example = ...` Can method reference or _`json!(...)`_. Given example
///   will override any example in underlying parameter type.
///
/// ##### Parameter type attributes
///
/// These attributes supported when _`parameter_type`_ is present. Either by manually providing one
/// or otherwise resolved e.g from path macro argument when _`actix_extras`_ crate feature is
/// enabled.
///
/// * `format = ...` May either be variant of the [`KnownFormat`][known_format] enum, or otherwise
///   an open value as a string. By default the format is derived from the type of the property
///   according OpenApi spec.
///
/// * `write_only` Defines property is only used in **write** operations *POST,PUT,PATCH* but not in *GET*
///
/// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH*
///
/// * `xml(...)` Can be used to define [`Xml`][xml] object properties for the parameter type.
///    See configuration options at xml attributes of [`ToSchema`][to_schema_xml]
///
/// * `nullable` Defines property is nullable (note this is different to non-required).
///
/// * `multiple_of = ...` Can be used to define multiplier for a value. Value is considered valid
///   division will result an `integer`. Value must be strictly above _`0`_.
///
/// * `maximum = ...` Can be used to define inclusive upper bound to a `number` value.
///
/// * `minimum = ...` Can be used to define inclusive lower bound to a `number` value.
///
/// * `exclusive_maximum = ...` Can be used to define exclusive upper bound to a `number` value.
///
/// * `exclusive_minimum = ...` Can be used to define exclusive lower bound to a `number` value.
///
/// * `max_length = ...` Can be used to define maximum length for `string` types.
///
/// * `min_length = ...` Can be used to define minimum length for `string` types.
///
/// * `pattern = ...` Can be used to define valid regular expression in _ECMA-262_ dialect the field value must match.
///
/// * `max_items = ...` Can be used to define maximum items allowed for `array` fields. Value must
///   be non-negative integer.
///
/// * `min_items = ...` Can be used to define minimum items allowed for `array` fields. Value must
///   be non-negative integer.
///
/// **For example:**
///
/// ```text
/// params(
///     ("id" = String, Path, deprecated, description = "Pet database id"),
///     ("name", Path, deprecated, description = "Pet name"),
///     (
///         "value" = inline(Option<[String]>),
///         Query,
///         description = "Value description",
///         style = Form,
///         allow_reserved,
///         deprecated,
///         explode,
///         example = json!(["Value"])),
///         max_length = 10,
///         min_items = 1
///     )
/// )
/// ```
///
/// ## IntoParams Type
///
/// In the IntoParams parameters format, the parameters are specified using an identifier for a type
/// that implements [`IntoParams`][into_params]. See [`IntoParams`][into_params] for an
/// example.
///
/// ```text
/// params(MyParameters)
/// ```
///
/// **Note!** that `MyParameters` can also be used in combination with the [tuples
/// representation](#tuples) or other structs.
/// ```text
/// params(
///     MyParameters1,
///     MyParameters2,
///     ("id" = String, Path, deprecated, description = "Pet database id"),
/// )
/// ```
///
/// # Security Requirement Attributes
///
/// * `name` Define the name for security requirement. This must match to name of existing
///   [`SecuritySchema`][security_schema].
/// * `scopes = [...]` Define the list of scopes needed. These must be scopes defined already in
///   existing [`SecuritySchema`][security_schema].
///
/// **Security Requirement supported formats:**
///
/// ```text
/// (),
/// ("name" = []),
/// ("name" = ["scope1", "scope2"]),
/// ("name" = ["scope1", "scope2"], "name2" = []),
/// ```
///
/// Leaving empty _`()`_ creates an empty [`SecurityRequirement`][security] this is useful when
/// security requirement is optional for operation.
///
/// You can define multiple security requirements within same parenthesis separated by comma. This
/// allows you to define keys that must be simultaneously provided for the endpoint / API.
///
/// _**Following could be explained as: Security is optional and if provided it must either contain
/// `api_key` or `key AND key2`.**_
/// ```text
/// (),
/// ("api_key" = []),
/// ("key" = [], "key2" = []),
/// ```
///
/// # actix_extras feature support for actix-web
///
/// **actix_extras** feature gives **utoipa** ability to parse path operation information from **actix-web** types and macros.
///
/// 1. Ability to parse `path` from **actix-web** path attribute macros e.g. _`#[get(...)]`_.
/// 2. Ability to parse [`std::primitive`]  or [`String`] or [`tuple`] typed `path` parameters from **actix-web** _`web::Path<...>`_.
/// 3. Ability to parse `path` and `query` parameters form **actix-web** _`web::Path<...>`_, _`web::Query<...>`_ types
///    with [`IntoParams`][into_params] trait.
///
/// See the **actix_extras** in action in examples [todo-actix](https://github.com/juhaku/utoipa/tree/master/examples/todo-actix).
///
/// With **actix_extras** feature enabled the you can leave out definitions for **path**, **operation**
/// and **parameter types**.
/// ```rust
/// use actix_web::{get, web, HttpResponse, Responder};
/// use serde_json::json;
///
/// /// Get Pet by id
/// #[utoipa::path(
///     responses(
///         (status = 200, description = "Pet found from database")
///     ),
///     params(
///         ("id", description = "Pet id"),
///     )
/// )]
/// #[get("/pet/{id}")]
/// async fn get_pet_by_id(id: web::Path<i32>) -> impl Responder {
///     HttpResponse::Ok().json(json!({ "pet": format!("{:?}", &id.into_inner()) }))
/// }
/// ```
///
/// With **actix_extras** you may also not to list any _**params**_ if you do not want to specify any description for them. Params are
/// resolved from path and the argument types of handler
/// ```rust
/// use actix_web::{get, web, HttpResponse, Responder};
/// use serde_json::json;
///
/// /// Get Pet by id
/// #[utoipa::path(
///     responses(
///         (status = 200, description = "Pet found from database")
///     )
/// )]
/// #[get("/pet/{id}")]
/// async fn get_pet_by_id(id: web::Path<i32>) -> impl Responder {
///     HttpResponse::Ok().json(json!({ "pet": format!("{:?}", &id.into_inner()) }))
/// }
/// ```
///
/// # rocket_extras feature support for rocket
///
/// **rocket_extras** feature enhances path operation parameter support. It gives **utoipa** ability to parse `path`, `path parameters`
/// and `query parameters` based on arguments given to **rocket**  proc macros such as _**`#[get(...)]`**_.
///
/// 1. It is able to parse parameter types for [primitive types][primitive], [`String`], [`Vec`], [`Option`] or [`std::path::PathBuf`]
///    type.
/// 2. It is able to determine `parameter_in` for [`IntoParams`][into_params] trait used for `FromForm` type of query parameters.
///
/// See the **rocket_extras** in action in examples [rocket-todo](https://github.com/juhaku/utoipa/tree/master/examples/rocket-todo).
///
///
/// # axum_extras feature support for axum
///
/// **axum_extras** feature enhances parameter support for path operation in following ways.
///
/// 1. It allows users to use tuple style path parameters e.g. _`Path((id, name)): Path<(i32, String)>`_ and resolves
///    parameter names and types from it.
/// 2. It enhances [`IntoParams` derive][into_params_derive] functionality by automatically resolving _`parameter_in`_ from
///   _`Path<...>`_ or _`Query<...>`_ handler function arguments.
///
/// _**Resole path argument types from tuple style handler arguments.**_
/// ```rust
/// # use axum::extract::Path;
/// /// Get todo by id and name.
/// #[utoipa::path(
///     get,
///     path = "/todo/{id}",
///     params(
///         ("id", description = "Todo id"),
///         ("name", description = "Todo name")
///     ),
///     responses(
///         (status = 200, description = "Get todo success", body = String)
///     )
/// )]
/// async fn get_todo(
///     Path((id, name)): Path<(i32, String)>
/// ) -> String {
///     String::new()
/// }
/// ```
///
/// _**Use `IntoParams` to resolve query parameters.**_
/// ```rust
/// # use serde::Deserialize;
/// # use utoipa::IntoParams;
/// # use axum::{extract::Query, Json};
/// #[derive(Deserialize, IntoParams)]
/// struct TodoSearchQuery {
///     /// Search by value. Search is incase sensitive.
///     value: String,
///     /// Search by `done` status.
///     done: bool,
/// }
///
/// /// Search Todos by query params.
/// #[utoipa::path(
///     get,
///     path = "/todo/search",
///     params(
///         TodoSearchQuery
///     ),
///     responses(
///         (status = 200, description = "List matching todos by query", body = [String])
///     )
/// )]
/// async fn search_todos(
///     query: Query<TodoSearchQuery>,
/// ) -> Json<Vec<String>> {
///     Json(vec![])
/// }
/// ```
///
/// # Examples
///
/// _**More complete example.**_
/// ```rust
/// # struct Pet {
/// #    id: u64,
/// #    name: String,
/// # }
/// #
/// #[utoipa::path(
///    post,
///    operation_id = "custom_post_pet",
///    path = "/pet",
///    tag = "pet_handlers",
///    request_body(content = Pet, description = "Pet to store the database", content_type = "application/json"),
///    responses(
///         (status = 200, description = "Pet stored successfully", body = Pet, content_type = "application/json",
///             headers(
///                 ("x-cache-len" = String, description = "Cache length")
///             ),
///             example = json!({"id": 1, "name": "bob the cat"})
///         ),
///    ),
///    params(
///      ("x-csrf-token" = String, Header, deprecated, description = "Current csrf token of user"),
///    ),
///    security(
///        (),
///        ("my_auth" = ["read:items", "edit:items"]),
///        ("token_jwt" = [])
///    )
/// )]
/// fn post_pet(pet: Pet) -> Pet {
///     Pet {
///         id: 4,
///         name: "bob the cat".to_string(),
///     }
/// }
/// ```
///
/// _**More minimal example with the defaults.**_
/// ```rust
/// # struct Pet {
/// #    id: u64,
/// #    name: String,
/// # }
/// #
/// #[utoipa::path(
///    post,
///    path = "/pet",
///    request_body = Pet,
///    responses(
///         (status = 200, description = "Pet stored successfully", body = Pet,
///             headers(
///                 ("x-cache-len", description = "Cache length")
///             )
///         ),
///    ),
///    params(
///      ("x-csrf-token", Header, description = "Current csrf token of user"),
///    )
/// )]
/// fn post_pet(pet: Pet) -> Pet {
///     Pet {
///         id: 4,
///         name: "bob the cat".to_string(),
///     }
/// }
/// ```
///
/// _**Use of Rust's own `#[deprecated]` attribute will reflect to the generated OpenAPI spec and mark this operation as deprecated.**_
/// ```rust
/// # use actix_web::{get, web, HttpResponse, Responder};
/// # use serde_json::json;
/// #[utoipa::path(
///     responses(
///         (status = 200, description = "Pet found from database")
///     ),
///     params(
///         ("id", description = "Pet id"),
///     )
/// )]
/// #[get("/pet/{id}")]
/// #[deprecated]
/// async fn get_pet_by_id(id: web::Path<i32>) -> impl Responder {
///     HttpResponse::Ok().json(json!({ "pet": format!("{:?}", &id.into_inner()) }))
/// }
/// ```
///
/// _**Define context path for endpoint. The resolved **path** shown in OpenAPI doc will be `/api/pet/{id}`.**_
/// ```rust
/// # use actix_web::{get, web, HttpResponse, Responder};
/// # use serde_json::json;
/// #[utoipa::path(
///     context_path = "/api",
///     responses(
///         (status = 200, description = "Pet found from database")
///     )
/// )]
/// #[get("/pet/{id}")]
/// async fn get_pet_by_id(id: web::Path<i32>) -> impl Responder {
///     HttpResponse::Ok().json(json!({ "pet": format!("{:?}", &id.into_inner()) }))
/// }
/// ```
///
/// _**Example with multiple return types**_
/// ```rust
/// # trait User {}
/// # struct User1 {
/// #   id: String
/// # }
/// # impl User for User1 {}
/// #[utoipa::path(
///     get,
///     path = "/user",
///     responses(
///         (status = 200, content(
///                 ("application/vnd.user.v1+json" = User1, example = json!({"id": "id".to_string()})),
///                 ("application/vnd.user.v2+json" = User2, example = json!({"id": 2}))
///             )
///         )
///     )
/// )]
/// fn get_user() -> Box<dyn User> {
///   Box::new(User1 {id: "id".to_string()})
/// }
/// ````
///
/// _**Example with multiple examples on single response.**_
/// ```rust
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct User {
/// #   name: String
/// # }
/// #[utoipa::path(
///     get,
///     path = "/user",
///     responses(
///         (status = 200, body = User,
///             examples(
///                 ("Demo" = (summary = "This is summary", description = "Long description",
///                             value = json!(User{name: "Demo".to_string()}))),
///                 ("John" = (summary = "Another user", value = json!({"name": "John"})))
///              )
///         )
///     )
/// )]
/// fn get_user() -> User {
///   User {name: "John".to_string()}
/// }
/// ```
///
/// [in_enum]: openapi/path/enum.ParameterIn.html
/// [path]: trait.Path.html
/// [to_schema]: trait.ToSchema.html
/// [openapi]: derive.OpenApi.html
/// [security]: openapi/security/struct.SecurityRequirement.html
/// [security_schema]: openapi/security/enum.SecurityScheme.html
/// [primitive]: https://doc.rust-lang.org/std/primitive/index.html
/// [into_params]: trait.IntoParams.html
/// [style]: openapi/path/enum.ParameterStyle.html
/// [into_responses_trait]: trait.IntoResponses.html
/// [into_params_derive]: derive.IntoParams.html
/// [to_response_trait]: trait.ToResponse.html
/// [known_format]: openapi/schema/enum.KnownFormat.html
/// [xml]: openapi/xml/struct.Xml.html
/// [to_schema_xml]: macro@ToSchema#xml-attribute-configuration-options
pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream {
    let path_attribute = syn::parse_macro_input!(attr as PathAttr);

    #[cfg(any(
        feature = "actix_extras",
        feature = "rocket_extras",
        feature = "axum_extras",
        feature = "auto_into_responses"
    ))]
    let mut path_attribute = path_attribute;

    let ast_fn = syn::parse::<ItemFn>(item).unwrap_or_abort();
    let fn_name = &*ast_fn.sig.ident.to_string();

    #[cfg(feature = "auto_into_responses")]
    {
        if let Some(responses) = ext::auto_types::parse_fn_operation_responses(&ast_fn) {
            path_attribute.responses_from_into_responses(responses);
        };
    }

    let mut resolved_operation = PathOperations::resolve_operation(&ast_fn);
    let resolved_path = PathOperations::resolve_path(
        &resolved_operation
            .as_mut()
            .map(|operation| mem::take(&mut operation.path).to_string())
            .or_else(|| path_attribute.path.as_ref().map(|path| path.to_string())), // cannot use mem take because we need this later
    );

    #[cfg(any(
        feature = "actix_extras",
        feature = "rocket_extras",
        feature = "axum_extras"
    ))]
    let mut resolved_path = resolved_path;

    #[cfg(any(
        feature = "actix_extras",
        feature = "rocket_extras",
        feature = "axum_extras"
    ))]
    {
        use ext::ArgumentResolver;
        use path::parameter::Parameter;
        let args = resolved_path.as_mut().map(|path| mem::take(&mut path.args));
        let body = resolved_operation
            .as_mut()
            .map(|path| mem::take(&mut path.body))
            .unwrap_or_default();

        let (arguments, into_params_types, body) =
            PathOperations::resolve_arguments(&ast_fn.sig.inputs, args, body);

        let parameters = arguments
            .into_iter()
            .flatten()
            .map(Parameter::from)
            .chain(into_params_types.into_iter().flatten().map(Parameter::from));
        path_attribute.update_parameters_ext(parameters);

        path_attribute.update_request_body(body);
    }

    let path = Path::new(path_attribute, fn_name)
        .path_operation(resolved_operation.map(|operation| operation.path_operation))
        .path(|| resolved_path.map(|path| path.path))
        .doc_comments(CommentAttributes::from_attributes(&ast_fn.attrs).0)
        .deprecated(ast_fn.attrs.iter().find_map(|attr| {

            if !matches!(attr.path().get_ident(), Some(ident) if &*ident.to_string() == "deprecated")
            {
                None
            } else {
                Some(true)
            }
        }));

    quote! {
        #path
        #ast_fn
    }
    .into()
}

#[proc_macro_error]
#[proc_macro_derive(OpenApi, attributes(openapi))]
/// Generate OpenApi base object with defaults from
/// project settings.
///
/// This is `#[derive]` implementation for [`OpenApi`][openapi] trait. The macro accepts one `openapi` argument.
///
/// # OpenApi `#[openapi(...)]` attributes
///
/// * `paths(...)`  List of method references having attribute [`#[utoipa::path]`][path] macro.
/// * `components(schemas(...), responses(...))` Takes available _`component`_ configurations. Currently only
///    _`schema`_ and _`response`_ components are supported.
///    * `schemas(...)` List of [`ToSchema`][to_schema]s in OpenAPI schema.
///    * `responses(...)` List of types that implement
/// [`ToResponse`][to_response_trait].
/// * `modifiers(...)` List of items implementing [`Modify`][modify] trait for runtime OpenApi modification.
///   See the [trait documentation][modify] for more details.
/// * `security(...)` List of [`SecurityRequirement`][security]s global to all operations.
///   See more details in [`#[utoipa::path(...)]`][path] [attribute macro security options][path_security].
/// * `tags(...)` List of [`Tag`][tags] which must match the tag _**path operation**_. By default
///   the tag is derived from path given to **handlers** list or if undefined then `crate` is used by default.
///   Alternatively the tag name can be given to path operation via [`#[utoipa::path(...)]`][path] macro.
///   Tag can be used to define extra information for the api to produce richer documentation.
/// * `external_docs(...)` Can be used to reference external resource to the OpenAPI doc for extended documentation.
///   External docs can be in [`OpenApi`][openapi_struct] or in [`Tag`][tags] level.
/// * `servers(...)` Define [`servers`][servers] as derive argument to the _`OpenApi`_. Servers
///   are completely optional and thus can be omitted from the declaration.
/// * `info(...)` Declare [`Info`][info] attribute values used to override the default values
///   generated from Cargo environment variables. **Note!** Defined attributes will override the
///   whole attribute from generated values of Cargo environment variables. E.g. defining
///   `contact(name = ...)` will ultimately override whole contact of info and not just partially
///   the name.
///
/// OpenApi derive macro will also derive [`Info`][info] for OpenApi specification using Cargo
/// environment variables.
///
/// * env `CARGO_PKG_NAME` map to info `title`
/// * env `CARGO_PKG_VERSION` map to info `version`
/// * env `CARGO_PKG_DESCRIPTION` map info `description`
/// * env `CARGO_PKG_AUTHORS` map to contact `name` and `email` **only first author will be used**
/// * env `CARGO_PKG_LICENSE` map to info `license`
///
/// # `info(...)` attribute syntax
///
/// * `title = ...` Define title of the API. It can be literal string.
/// * `description = ...` Define description of the API. Markdown can be used for rich text
///   representation. It can be literal string or [`include_str!`] statement.
/// * `version = ...` Override default version from _`Cargo.toml`_. Value must be literal string.
/// * `contact(...)` Used to override the whole contact generated from environment variables.
///     * `name = ...` Define identifying name of contact person / organization. It Can be a literal string.
///     * `email = ...` Define email address of the contact person / organization. It can be a literal string.
///     * `url = ...` Define URL pointing to the contact information. It must be in URL formatted string.
/// * `license(...)` Used to override the whole license generated from environment variables.
///     * `name = ...` License name of the API. It can be a literal string.
///     * `url = ...` Define optional URL of the license. It must be URL formatted string.
///
/// # `servers(...)` attribute syntax
///
/// * `url = ...` Define the url for server. It can be literal string.
/// * `description = ...` Define description for the server. It can be literal string.
/// * `variables(...)` Can be used to define variables for the url.
///     * `name = ...` Is the first argument within parentheses. It must be literal string.
///     * `default = ...` Defines a default value for the variable if nothing else will be
///       provided. If _`enum_values`_ is defined the _`default`_ must be found within the enum
///       options. It can be a literal string.
///     * `description = ...` Define the description for the variable. It can be a literal string.
///     * `enum_values(...)` Define list of possible values for the variable. Values must be
///       literal strings.
///
/// _**Example server variable definition.**_
/// ```text
/// ("username" = (default = "demo", description = "Default username for API")),
/// ("port" = (enum_values("8080", "5000", "4545")))
/// ```
///
/// # Examples
///
/// _**Define OpenApi schema with some paths and components.**_
/// ```rust
/// # use utoipa::{OpenApi, ToSchema};
/// #
/// #[derive(ToSchema)]
/// struct Pet {
///     name: String,
///     age: i32,
/// }
///
/// #[derive(ToSchema)]
/// enum Status {
///     Active, InActive, Locked,
/// }
///
/// #[utoipa::path(get, path = "/pet")]
/// fn get_pet() -> Pet {
///     Pet {
///         name: "bob".to_string(),
///         age: 8,
///     }
/// }
///
/// #[utoipa::path(get, path = "/status")]
/// fn get_status() -> Status {
///     Status::Active
/// }
///
/// #[derive(OpenApi)]
/// #[openapi(
///     paths(get_pet, get_status),
///     components(schemas(Pet, Status)),
///     security(
///         (),
///         ("my_auth" = ["read:items", "edit:items"]),
///         ("token_jwt" = [])
///     ),
///     tags(
///         (name = "pets::api", description = "All about pets",
///             external_docs(url = "http://more.about.pets.api", description = "Find out more"))
///     ),
///     external_docs(url = "http://more.about.our.apis", description = "More about our APIs")
/// )]
/// struct ApiDoc;
/// ```
///
/// _**Define servers to OpenApi.**_
/// ```rust
/// # use utoipa::OpenApi;
/// #[derive(OpenApi)]
/// #[openapi(
///     servers(
///         (url = "http://localhost:8989", description = "Local server"),
///         (url = "http://api.{username}:{port}", description = "Remote API",
///             variables(
///                 ("username" = (default = "demo", description = "Default username for API")),
///                 ("port" = (default = "8080", enum_values("8080", "5000", "3030"), description = "Supported ports for API"))
///             )
///         )
///     )
/// )]
/// struct ApiDoc;
/// ```
///
/// _**Define info attribute values used to override auto generated ones from Cargo environment
/// variables.**_
/// ```compile_fail
/// # use utoipa::OpenApi;
/// #[derive(OpenApi)]
/// #[openapi(info(
///     title = "title override",
///     description = include_str!("./path/to/content"), // fail compile cause no such file
///     contact(name = "Test")
/// ))]
/// struct ApiDoc;
/// ```
///
/// _**Create OpenAPI with reusable response.**_
/// ```rust
/// #[derive(utoipa::ToSchema)]
/// struct Person {
///     name: String,
/// }
///
/// /// Person list response
/// #[derive(utoipa::ToResponse)]
/// struct PersonList(Vec<Person>);
///
/// #[utoipa::path(
///     get,
///     path = "/person-list",
///     responses(
///         (status = 200, response = PersonList)
///     )
/// )]
/// fn get_persons() -> Vec<Person> {
///     vec![]
/// }
///
/// #[derive(utoipa::OpenApi)]
/// #[openapi(
///     components(
///         schemas(Person),
///         responses(PersonList)
///     )
/// )]
/// struct ApiDoc;
/// ```
///
/// [openapi]: trait.OpenApi.html
/// [openapi_struct]: openapi/struct.OpenApi.html
/// [to_schema]: derive.ToSchema.html
/// [path]: attr.path.html
/// [modify]: trait.Modify.html
/// [info]: openapi/info/struct.Info.html
/// [security]: openapi/security/struct.SecurityRequirement.html
/// [path_security]: attr.path.html#security-requirement-attributes
/// [tags]: openapi/tag/struct.Tag.html
/// [to_response_trait]: trait.ToResponse.html
/// [servers]: openapi/server/index.html
pub fn openapi(input: TokenStream) -> TokenStream {
    let DeriveInput { attrs, ident, .. } = syn::parse_macro_input!(input);

    let openapi_attributes = openapi::parse_openapi_attrs(&attrs).expect_or_abort(
        "expected #[openapi(...)] attribute to be present when used with OpenApi derive trait",
    );

    let openapi = OpenApi(openapi_attributes, ident);

    openapi.to_token_stream().into()
}

#[proc_macro_error]
#[proc_macro_derive(IntoParams, attributes(param, into_params))]
/// Generate [path parameters][path_params] from struct's
/// fields.
///
/// This is `#[derive]` implementation for [`IntoParams`][into_params] trait.
///
/// Typically path parameters need to be defined within [`#[utoipa::path(...params(...))]`][path_params] section
/// for the endpoint. But this trait eliminates the need for that when [`struct`][struct]s are used to define parameters.
/// Still [`std::primitive`] and [`String`](std::string::String) path parameters or [`tuple`] style path parameters need to be defined
/// within `params(...)` section if description or other than default configuration need to be given.
///
/// You can use the Rust's own `#[deprecated]` attribute on field to mark it as
/// deprecated and it will reflect to the generated OpenAPI spec.
///
/// `#[deprecated]` attribute supports adding additional details such as a reason and or since version
/// but this is is not supported in OpenAPI. OpenAPI has only a boolean flag to determine deprecation.
/// While it is totally okay to declare deprecated with reason
/// `#[deprecated  = "There is better way to do this"]` the reason would not render in OpenAPI spec.
///
/// Doc comment on struct fields will be used as description for the generated parameters.
/// ```rust
/// #[derive(utoipa::IntoParams)]
/// struct Query {
///     /// Query todo items by name.
///     name: String
/// }
/// ```
///
/// # IntoParams Container Attributes for `#[into_params(...)]`
///
/// The following attributes are available for use in on the container attribute `#[into_params(...)]` for the struct
/// deriving `IntoParams`:
///
/// * `names(...)` Define comma separated list of names for unnamed fields of struct used as a path parameter.
///    __Only__ supported on __unnamed structs__.
/// * `style = ...` Defines how all parameters are serialized by [`ParameterStyle`][style]. Default
///    values are based on _`parameter_in`_ attribute.
/// * `parameter_in = ...` =  Defines where the parameters of this field are used with a value from
///    [`openapi::path::ParameterIn`][in_enum]. There is no default value, if this attribute is not
///    supplied, then the value is determined by the `parameter_in_provider` in
///    [`IntoParams::into_params()`](trait.IntoParams.html#tymethod.into_params).
/// * `rename_all = ...` Can be provided to alternatively to the serde's `rename_all` attribute. Effectively provides same functionality.
///
/// Use `names` to define name for single unnamed argument.
/// ```rust
/// # use utoipa::IntoParams;
/// #
/// #[derive(IntoParams)]
/// #[into_params(names("id"))]
/// struct Id(u64);
/// ```
///
/// Use `names` to define names for multiple unnamed arguments.
/// ```rust
/// # use utoipa::IntoParams;
/// #
/// #[derive(IntoParams)]
/// #[into_params(names("id", "name"))]
/// struct IdAndName(u64, String);
/// ```
///
/// # IntoParams Field Attributes for `#[param(...)]`
///
/// The following attributes are available for use in the `#[param(...)]` on struct fields:
///
/// * `style = ...` Defines how the parameter is serialized by [`ParameterStyle`][style]. Default values are based on _`parameter_in`_ attribute.
///
/// * `explode` Defines whether new _`parameter=value`_ pair is created for each parameter within _`object`_ or _`array`_.
///
/// * `allow_reserved` Defines whether reserved characters _`:/?#[]@!$&'()*+,;=`_ is allowed within value.
///
/// * `example = ...` Can be method reference or _`json!(...)`_. Given example
///   will override any example in underlying parameter type.
///
/// * `value_type = ...` Can be used to override default type derived from type of the field used in OpenAPI spec.
///   This is useful in cases where the default type does not correspond to the actual type e.g. when
///   any third-party types are used which are not [`ToSchema`][to_schema]s nor [`primitive` types][primitive].
///   The value can be any Rust type what normally could be used to serialize to JSON, or either virtual type _`Object`_
///   or _`Value`_, or an alias defined using `#[aliases(..)]`.
///   _`Object`_ will be rendered as generic OpenAPI object _(`type: object`)_.
///   _`Value`_ will be rendered as any OpenAPI value (i.e. no `type` restriction).
///
/// * `inline` If set, the schema for this field's type needs to be a [`ToSchema`][to_schema], and
///   the schema definition will be inlined.
///
/// * `default = ...` Can be method reference or _`json!(...)`_.
///
/// * `format = ...` May either be variant of the [`KnownFormat`][known_format] enum, or otherwise
///   an open value as a string. By default the format is derived from the type of the property
///   according OpenApi spec.
///
/// * `write_only` Defines property is only used in **write** operations *POST,PUT,PATCH* but not in *GET*.
///
/// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH*.
///
/// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to named fields.
///    See configuration options at xml attributes of [`ToSchema`][to_schema_xml]
///
/// * `nullable` Defines property is nullable (note this is different to non-required).
///
/// * `required = ...` Can be used to enforce required status for the parameter. [See
///    rules][derive@IntoParams#field-nullability-and-required-rules]
///
/// * `rename = ...` Can be provided to alternatively to the serde's `rename` attribute. Effectively provides same functionality.
///
/// * `multiple_of = ...` Can be used to define multiplier for a value. Value is considered valid
///   division will result an `integer`. Value must be strictly above _`0`_.
///
/// * `maximum = ...` Can be used to define inclusive upper bound to a `number` value.
///
/// * `minimum = ...` Can be used to define inclusive lower bound to a `number` value.
///
/// * `exclusive_maximum = ...` Can be used to define exclusive upper bound to a `number` value.
///
/// * `exclusive_minimum = ...` Can be used to define exclusive lower bound to a `number` value.
///
/// * `max_length = ...` Can be used to define maximum length for `string` types.
///
/// * `min_length = ...` Can be used to define minimum length for `string` types.
///
/// * `pattern = ...` Can be used to define valid regular expression in _ECMA-262_ dialect the field value must match.
///
/// * `max_items = ...` Can be used to define maximum items allowed for `array` fields. Value must
///   be non-negative integer.
///
/// * `min_items = ...` Can be used to define minimum items allowed for `array` fields. Value must
///   be non-negative integer.
///
/// * `schema_with = ...` Use _`schema`_ created by provided function reference instead of the
///   default derived _`schema`_. The function must match to `fn() -> Into<RefOr<Schema>>`. It does
///   not accept arguments and must return anything that can be converted into `RefOr<Schema>`.
///
/// * `additional_properties = ...` Can be used to define free form types for maps such as
///   [`HashMap`](std::collections::HashMap) and [`BTreeMap`](std::collections::BTreeMap).
///   Free form type enables use of arbitrary types within map values.
///   Supports formats _`additional_properties`_ and _`additional_properties = true`_.
///
/// #### Field nullability and required rules
///
/// Same rules for nullability and required status apply for _`IntoParams`_ field attributes as for
/// _`ToSchema`_ field attributes. [See the rules][`derive@ToSchema#field-nullability-and-required-rules`].
///
/// # Partial `#[serde(...)]` attributes support
///
/// IntoParams derive has partial support for [serde attributes]. These supported attributes will reflect to the
/// generated OpenAPI doc. The following attributes are currently supported:
///
/// * `rename_all = "..."` Supported at the container level.
/// * `rename = "..."` Supported **only** at the field level.
/// * `default` Supported at the container level and field level according to [serde attributes].
/// * `skip_serializing_if = "..."` Supported  **only** at the field level.
/// * `with = ...` Supported **only** at field level.
/// * `skip_serializing = "..."` Supported  **only** at the field or variant level.
/// * `skip_deserializing = "..."` Supported  **only** at the field or variant level.
/// * `skip = "..."` Supported  **only** at the field level.
///
/// Other _`serde`_ attributes will impact the serialization but will not be reflected on the generated OpenAPI doc.
///
/// # Examples
///
/// _**Demonstrate [`IntoParams`][into_params] usage with resolving `Path` and `Query` parameters
/// with _`actix-web`_**_.
/// ```rust
/// use actix_web::{get, HttpResponse, Responder};
/// use actix_web::web::{Path, Query};
/// use serde::Deserialize;
/// use serde_json::json;
/// use utoipa::IntoParams;
///
/// #[derive(Deserialize, IntoParams)]
/// struct PetPathArgs {
///     /// Id of pet
///     id: i64,
///     /// Name of pet
///     name: String,
/// }
///
/// #[derive(Deserialize, IntoParams)]
/// struct Filter {
///     /// Age filter for pets
///     #[deprecated]
///     #[param(style = Form, explode, allow_reserved, example = json!([10]))]
///     age: Option<Vec<i32>>,
/// }
///
/// #[utoipa::path(
///     params(PetPathArgs, Filter),
///     responses(
///         (status = 200, description = "success response")
///     )
/// )]
/// #[get("/pet/{id}/{name}")]
/// async fn get_pet(pet: Path<PetPathArgs>, query: Query<Filter>) -> impl Responder {
///     HttpResponse::Ok().json(json!({ "id": pet.id }))
/// }
/// ```
///
/// _**Demonstrate [`IntoParams`][into_params] usage with the `#[into_params(...)]` container attribute to
/// be used as a path query, and inlining a schema query field:**_
/// ```rust
/// use serde::Deserialize;
/// use utoipa::{IntoParams, ToSchema};
///
/// #[derive(Deserialize, ToSchema)]
/// #[serde(rename_all = "snake_case")]
/// enum PetKind {
///     Dog,
///     Cat,
/// }
///
/// #[derive(Deserialize, IntoParams)]
/// #[into_params(style = Form, parameter_in = Query)]
/// struct PetQuery {
///     /// Name of pet
///     name: Option<String>,
///     /// Age of pet
///     age: Option<i32>,
///     /// Kind of pet
///     #[param(inline)]
///     kind: PetKind
/// }
///
/// #[utoipa::path(
///     get,
///     path = "/get_pet",
///     params(PetQuery),
///     responses(
///         (status = 200, description = "success response")
///     )
/// )]
/// async fn get_pet(query: PetQuery) {
///     // ...
/// }
/// ```
///
/// _**Override `String` with `i64` using `value_type` attribute.**_
/// ```rust
/// # use utoipa::IntoParams;
/// #
/// #[derive(IntoParams)]
/// #[into_params(parameter_in = Query)]
/// struct Filter {
///     #[param(value_type = i64)]
///     id: String,
/// }
/// ```
///
/// _**Override `String` with `Object` using `value_type` attribute. _`Object`_ will render as `type: object` in OpenAPI spec.**_
/// ```rust
/// # use utoipa::IntoParams;
/// #
/// #[derive(IntoParams)]
/// #[into_params(parameter_in = Query)]
/// struct Filter {
///     #[param(value_type = Object)]
///     id: String,
/// }
/// ```
///
/// _**You can use a generic type to override the default type of the field.**_
/// ```rust
/// # use utoipa::IntoParams;
/// #
/// #[derive(IntoParams)]
/// #[into_params(parameter_in = Query)]
/// struct Filter {
///     #[param(value_type = Option<String>)]
///     id: String
/// }
/// ```
///
/// _**You can even override a [`Vec`] with another one.**_
/// ```rust
/// # use utoipa::IntoParams;
/// #
/// #[derive(IntoParams)]
/// #[into_params(parameter_in = Query)]
/// struct Filter {
///     #[param(value_type = Vec<i32>)]
///     id: Vec<String>
/// }
/// ```
///
/// _**We can override value with another [`ToSchema`][to_schema].**_
/// ```rust
/// # use utoipa::{IntoParams, ToSchema};
/// #
/// #[derive(ToSchema)]
/// struct Id {
///     value: i64,
/// }
///
/// #[derive(IntoParams)]
/// #[into_params(parameter_in = Query)]
/// struct Filter {
///     #[param(value_type = Id)]
///     id: String
/// }
/// ```
///
/// _**Example with validation attributes.**_
/// ```rust
/// #[derive(utoipa::IntoParams)]
/// struct Item {
///     #[param(maximum = 10, minimum = 5, multiple_of = 2.5)]
///     id: i32,
///     #[param(max_length = 10, min_length = 5, pattern = "[a-z]*")]
///     value: String,
///     #[param(max_items = 5, min_items = 1)]
///     items: Vec<String>,
/// }
/// ````
///
/// _**Use `schema_with` to manually implement schema for a field.**_
/// ```rust
/// # use utoipa::openapi::schema::{Object, ObjectBuilder};
/// fn custom_type() -> Object {
///     ObjectBuilder::new()
///         .schema_type(utoipa::openapi::SchemaType::String)
///         .format(Some(utoipa::openapi::SchemaFormat::Custom(
///             "email".to_string(),
///         )))
///         .description(Some("this is the description"))
///         .build()
/// }
///
/// #[derive(utoipa::IntoParams)]
/// #[into_params(parameter_in = Query)]
/// struct Query {
///     #[param(schema_with = custom_type)]
///     email: String,
/// }
/// ```
///
/// [to_schema]: trait.ToSchema.html
/// [known_format]: openapi/schema/enum.KnownFormat.html
/// [xml]: openapi/xml/struct.Xml.html
/// [into_params]: trait.IntoParams.html
/// [path_params]: attr.path.html#params-attributes
/// [struct]: https://doc.rust-lang.org/std/keyword.struct.html
/// [style]: openapi/path/enum.ParameterStyle.html
/// [in_enum]: openapi/path/enum.ParameterIn.html
/// [primitive]: https://doc.rust-lang.org/std/primitive/index.html
/// [serde attributes]: https://serde.rs/attributes.html
/// [to_schema_xml]: macro@ToSchema#xml-attribute-configuration-options
pub fn into_params(input: TokenStream) -> TokenStream {
    let DeriveInput {
        attrs,
        ident,
        generics,
        data,
        ..
    } = syn::parse_macro_input!(input);

    let into_params = IntoParams {
        attrs,
        generics,
        data,
        ident,
    };

    into_params.to_token_stream().into()
}

#[proc_macro_error]
#[proc_macro_derive(ToResponse, attributes(response, content, to_schema))]
/// Generate reusable OpenAPI response that can be used
/// in [`utoipa::path`][path] or in [`OpenApi`][openapi].
///
/// This is `#[derive]` implementation for [`ToResponse`][to_response] trait.
///
///
/// _`#[response]`_ attribute can be used to alter and add [response attributes](#toresponse-response-attributes).
///
/// _`#[content]`_ attributes is used to make enum variant a content of a specific type for the
/// response.
///
/// _`#[to_schema]`_ attribute is used to inline a schema for a response in unnamed structs or
/// enum variants with `#[content]` attribute. **Note!** [`ToSchema`] need to be implemented for
/// the field or variant type.
///
/// Type derived with _`ToResponse`_ uses provided doc comment as a description for the response. It
/// can alternatively be overridden with _`description = ...`_ attribute.
///
/// _`ToResponse`_ can be used in four different ways to generate OpenAPI response component.
///
/// 1. By decorating `struct` or `enum` with [`derive@ToResponse`] derive macro. This will create a
///    response with inlined schema resolved from the fields of the `struct` or `variants` of the
///    enum.
///
///    ```rust
///     # use utoipa::ToResponse;
///     #[derive(ToResponse)]
///     #[response(description = "Person response returns single Person entity")]
///     struct Person {
///         name: String,
///     }
///    ```
///
/// 2. By decorating unnamed field `struct` with [`derive@ToResponse`] derive macro. Unnamed field struct
///    allows users to use new type pattern to define one inner field which is used as a schema for
///    the generated response. This allows users to define `Vec` and `Option` response types.
///    Additionally these types can also be used with `#[to_schema]` attribute to inline the
///    field's type schema if it implements [`ToSchema`] derive macro.
///
///    ```rust
///     # #[derive(utoipa::ToSchema)]
///     # struct Person {
///     #     name: String,
///     # }
///     /// Person list response
///     #[derive(utoipa::ToResponse)]
///     struct PersonList(Vec<Person>);
///    ```
///
/// 3. By decorating unit struct with [`derive@ToResponse`] derive macro. Unit structs will produce a
///    response without body.
///
///    ```rust
///     /// Success response which does not have body.
///     #[derive(utoipa::ToResponse)]
///     struct SuccessResponse;
///    ```
///
/// 4. By decorating `enum` with variants having `#[content(...)]` attribute. This allows users to
///    define multiple response content schemas to single response according to OpenAPI spec.
///    **Note!** Enum with _`content`_ attribute in variants cannot have enum level _`example`_ or
///    _`examples`_ defined. Instead examples need to be defined per variant basis. Additionally
///    these variants can also be used with `#[to_schema]` attribute to inline the variant's type schema
///    if it implements [`ToSchema`] derive macro.
///
///    ```rust
///     #[derive(utoipa::ToSchema)]
///     struct Admin {
///         name: String,
///     }
///     #[derive(utoipa::ToSchema)]
///     struct Admin2 {
///         name: String,
///         id: i32,
///     }
///
///     #[derive(utoipa::ToResponse)]
///     enum Person {
///         #[response(examples(
///             ("Person1" = (value = json!({"name": "name1"}))),
///             ("Person2" = (value = json!({"name": "name2"})))
///         ))]
///         Admin(#[content("application/vnd-custom-v1+json")] Admin),
///
///         #[response(example = json!({"name": "name3", "id": 1}))]
///         Admin2(#[content("application/vnd-custom-v2+json")] #[to_schema] Admin2),
///     }
///    ```
///
/// # ToResponse `#[response(...)]` attributes
///
/// * `description = "..."` Define description for the response as str. This can be used to
///   override the default description resolved from doc comments if present.
///
/// * `content_type = "..." | content_type = [...]` Can be used to override the default behavior of auto resolving the content type
///   from the `body` attribute. If defined the value should be valid content type such as
///   _`application/json`_. By default the content type is _`text/plain`_ for
///   [primitive Rust types][primitive], `application/octet-stream` for _`[u8]`_ and
///   _`application/json`_ for struct and complex enum types.
///   Content type can also be slice of **content_type** values if the endpoint support returning multiple
///  response content types. E.g _`["application/json", "text/xml"]`_ would indicate that endpoint can return both
///  _`json`_ and _`xml`_ formats. **The order** of the content types define the default example show first in
///  the Swagger UI. Swagger UI will use the first _`content_type`_ value as a default example.
///
/// * `headers(...)` Slice of response headers that are returned back to a caller.
///
/// * `example = ...` Can be _`json!(...)`_. _`json!(...)`_ should be something that
///   _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///
/// * `examples(...)` Define multiple examples for single response. This attribute is mutually
///   exclusive to the _`example`_ attribute and if both are defined this will override the _`example`_.
///     * `name = ...` This is first attribute and value must be literal string.
///     * `summary = ...` Short description of example. Value must be literal string.
///     * `description = ...` Long description of example. Attribute supports markdown for rich text
///       representation. Value must be literal string.
///     * `value = ...` Example value. It must be _`json!(...)`_. _`json!(...)`_ should be something that
///       _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///     * `external_value = ...` Define URI to literal example value. This is mutually exclusive to
///       the _`value`_ attribute. Value must be literal string.
///
///      _**Example of example definition.**_
///     ```text
///      ("John" = (summary = "This is John", value = json!({"name": "John"})))
///     ```
///
/// # Examples
///
/// _**Use reusable response in operation handler.**_
/// ```rust
/// #[derive(utoipa::ToResponse)]
/// struct PersonResponse {
///    value: String
/// }
///
/// #[derive(utoipa::OpenApi)]
/// #[openapi(components(responses(PersonResponse)))]
/// struct Doc;
///
/// #[utoipa::path(
///     get,
///     path = "/api/person",
///     responses(
///         (status = 200, response = PersonResponse)
///     )
/// )]
/// fn get_person() -> PersonResponse {
///     PersonResponse { value: "person".to_string() }
/// }
/// ```
///
/// _**Create a response from named struct.**_
/// ```rust
///  /// This is description
///  ///
///  /// It will also be used in `ToSchema` if present
///  #[derive(utoipa::ToSchema, utoipa::ToResponse)]
///  #[response(
///      description = "Override description for response",
///      content_type = "text/xml"
///  )]
///  #[response(
///      example = json!({"name": "the name"}),
///      headers(
///          ("csrf-token", description = "response csrf token"),
///          ("random-id" = i32)
///      )
///  )]
///  struct Person {
///      name: String,
///  }
/// ```
///
/// _**Create inlined person list response.**_
/// ```rust
///  # #[derive(utoipa::ToSchema)]
///  # struct Person {
///  #     name: String,
///  # }
///  /// Person list response
///  #[derive(utoipa::ToResponse)]
///  struct PersonList(#[to_schema] Vec<Person>);
/// ```
///
/// _**Create enum response from variants.**_
/// ```rust
///  #[derive(utoipa::ToResponse)]
///  enum PersonType {
///      Value(String),
///      Foobar,
///  }
/// ```
///
/// [to_response]: trait.ToResponse.html
/// [primitive]: https://doc.rust-lang.org/std/primitive/index.html
/// [path]: attr.path.html
/// [openapi]: derive.OpenApi.html
pub fn to_response(input: TokenStream) -> TokenStream {
    let DeriveInput {
        attrs,
        ident,
        generics,
        data,
        ..
    } = syn::parse_macro_input!(input);

    let response = ToResponse::new(attrs, &data, generics, ident);

    response.to_token_stream().into()
}

#[proc_macro_error]
#[proc_macro_derive(
    IntoResponses,
    attributes(response, to_schema, ref_response, to_response)
)]
/// Generate responses with status codes what
/// can be attached to the [`utoipa::path`][path_into_responses].
///
/// This is `#[derive]` implementation of [`IntoResponses`][into_responses] trait. [`derive@IntoResponses`]
/// can be used to decorate _`structs`_ and _`enums`_ to generate response maps that can be used in
/// [`utoipa::path`][path_into_responses]. If _`struct`_ is decorated with [`derive@IntoResponses`] it will be
/// used to create a map of responses containing single response. Decorating _`enum`_ with
/// [`derive@IntoResponses`] will create a map of responses with a response for each variant of the _`enum`_.
///
/// Named field _`struct`_ decorated with [`derive@IntoResponses`] will create a response with inlined schema
/// generated from the body of the struct. This is a conveniency which allows users to directly
/// create responses with schemas without first creating a separate [response][to_response] type.
///
/// Unit _`struct`_ behaves similarly to then named field struct. Only difference is that it will create
/// a response without content since there is no inner fields.
///
/// Unnamed field _`struct`_ decorated with [`derive@IntoResponses`] will by default create a response with
/// referenced [schema][to_schema] if field is object or schema if type is [primitive
/// type][primitive]. _`#[to_schema]`_ attribute at field of unnamed _`struct`_ can be used to inline
/// the schema if type of the field implements [`ToSchema`][to_schema] trait. Alternatively
/// _`#[to_response]`_ and _`#[ref_response]`_ can be used at field to either reference a reusable
/// [response][to_response] or inline a reusable [response][to_response]. In both cases the field
/// type is expected to implement [`ToResponse`][to_response] trait.
///
///
/// Enum decorated with [`derive@IntoResponses`] will create a response for each variant of the _`enum`_.
/// Each variant must have it's own _`#[response(...)]`_ definition. Unit variant will behave same
/// as unit _`struct`_ by creating a response without content. Similarly named field variant and
/// unnamed field variant behaves the same as it was named field _`struct`_ and unnamed field
/// _`struct`_.
///
/// _`#[response]`_ attribute can be used at named structs, unnamed structs, unit structs and enum
/// variants to alter [response attributes](#intoresponses-response-attributes) of responses.
///
/// Doc comment on a _`struct`_ or _`enum`_ variant will be used as a description for the response.
/// It can also be overridden with _`description = "..."`_ attribute.
///
/// # IntoResponses `#[response(...)]` attributes
///
/// * `status = ...` Must be provided. Is either a valid http status code integer. E.g. _`200`_ or a
///   string value representing a range such as _`"4XX"`_ or `"default"` or a valid _`http::status::StatusCode`_.
///   _`StatusCode`_ can either be use path to the status code or _status code_ constant directly.
///
/// * `description = "..."` Define description for the response as str. This can be used to
///   override the default description resolved from doc comments if present.
///
/// * `content_type = "..." | content_type = [...]` Can be used to override the default behavior of auto resolving the content type
///   from the `body` attribute. If defined the value should be valid content type such as
///   _`application/json`_. By default the content type is _`text/plain`_ for
///   [primitive Rust types][primitive], `application/octet-stream` for _`[u8]`_ and
///   _`application/json`_ for struct and complex enum types.
///   Content type can also be slice of **content_type** values if the endpoint support returning multiple
///  response content types. E.g _`["application/json", "text/xml"]`_ would indicate that endpoint can return both
///  _`json`_ and _`xml`_ formats. **The order** of the content types define the default example show first in
///  the Swagger UI. Swagger UI will use the first _`content_type`_ value as a default example.
///
/// * `headers(...)` Slice of response headers that are returned back to a caller.
///
/// * `example = ...` Can be _`json!(...)`_. _`json!(...)`_ should be something that
///   _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///
/// * `examples(...)` Define multiple examples for single response. This attribute is mutually
///   exclusive to the _`example`_ attribute and if both are defined this will override the _`example`_.
///     * `name = ...` This is first attribute and value must be literal string.
///     * `summary = ...` Short description of example. Value must be literal string.
///     * `description = ...` Long description of example. Attribute supports markdown for rich text
///       representation. Value must be literal string.
///     * `value = ...` Example value. It must be _`json!(...)`_. _`json!(...)`_ should be something that
///       _`serde_json::json!`_ can parse as a _`serde_json::Value`_.
///     * `external_value = ...` Define URI to literal example value. This is mutually exclusive to
///       the _`value`_ attribute. Value must be literal string.
///
///      _**Example of example definition.**_
///     ```text
///      ("John" = (summary = "This is John", value = json!({"name": "John"})))
///     ```
///
/// # Examples
///
/// _**Use `IntoResponses` to define [`utoipa::path`][path] responses.**_
/// ```rust
/// #[derive(utoipa::ToSchema)]
/// struct BadRequest {
///     message: String,
/// }
///
/// #[derive(utoipa::IntoResponses)]
/// enum UserResponses {
///     /// Success response
///     #[response(status = 200)]
///     Success { value: String },
///
///     #[response(status = 404)]
///     NotFound,
///
///     #[response(status = 400)]
///     BadRequest(BadRequest),
/// }
///
/// #[utoipa::path(
///     get,
///     path = "/api/user",
///     responses(
///         UserResponses
///     )
/// )]
/// fn get_user() -> UserResponses {
///    UserResponses::NotFound
/// }
/// ```
/// _**Named struct response with inlined schema.**_
/// ```rust
/// /// This is success response
/// #[derive(utoipa::IntoResponses)]
/// #[response(status = 200)]
/// struct SuccessResponse {
///     value: String,
/// }
/// ```
///
/// _**Unit struct response without content.**_
/// ```rust
/// #[derive(utoipa::IntoResponses)]
/// #[response(status = NOT_FOUND)]
/// struct NotFound;
/// ```
///
/// _**Unnamed struct response with inlined response schema.**_
/// ```rust
/// # #[derive(utoipa::ToSchema)]
/// # struct Foo;
/// #[derive(utoipa::IntoResponses)]
/// #[response(status = 201)]
/// struct CreatedResponse(#[to_schema] Foo);
/// ```
///
/// _**Enum with multiple responses.**_
/// ```rust
/// # #[derive(utoipa::ToResponse)]
/// # struct Response {
/// #     message: String,
/// # }
/// # #[derive(utoipa::ToSchema)]
/// # struct BadRequest {}
/// #[derive(utoipa::IntoResponses)]
/// enum UserResponses {
///     /// Success response description.
///     #[response(status = 200)]
///     Success { value: String },
///
///     #[response(status = 404)]
///     NotFound,
///
///     #[response(status = 400)]
///     BadRequest(BadRequest),
///
///     #[response(status = 500)]
///     ServerError(#[ref_response] Response),
///
///     #[response(status = 418)]
///     TeaPot(#[to_response] Response),
/// }
/// ```
///
/// [into_responses]: trait.IntoResponses.html
/// [to_schema]: trait.ToSchema.html
/// [to_response]: trait.ToResponse.html
/// [path_into_responses]: attr.path.html#responses-from-intoresponses
/// [primitive]: https://doc.rust-lang.org/std/primitive/index.html
/// [path]: macro@crate::path
pub fn into_responses(input: TokenStream) -> TokenStream {
    let DeriveInput {
        attrs,
        ident,
        generics,
        data,
        ..
    } = syn::parse_macro_input!(input);

    let into_responses = IntoResponses {
        attributes: attrs,
        ident,
        generics,
        data,
    };

    into_responses.to_token_stream().into()
}

/// Create OpenAPI Schema from arbitrary type.
///
/// This macro provides a quick way to render arbitrary types as OpenAPI Schema Objects. It
/// supports two call formats.
/// 1. With type only
/// 2. With _`#[inline]`_ attribute to inline the referenced schemas.
///
/// By default the macro will create references `($ref)` for non primitive types like _`Pet`_.
/// However when used with _`#[inline]`_ the non [`primitive`][primitive] type schemas will
/// be inlined to the schema output.
///
/// ```rust
/// # #[derive(utoipa::ToSchema)]
/// # struct Pet {id: i32};
/// let schema = utoipa::schema!(Vec<Pet>);
///
/// // with inline
/// let schema = utoipa::schema!(#[inline] Vec<Pet>);
/// ```
///
/// # Examples
///
/// _**Create vec of pets schema.**_
/// ```rust
/// # use utoipa::openapi::schema::{Schema, Array, Object, ObjectBuilder, SchemaFormat,
/// # KnownFormat, SchemaType};
/// # use utoipa::openapi::RefOr;
/// #[derive(utoipa::ToSchema)]
/// struct Pet {
///     id: i32,
///     name: String,
/// }
///
/// let schema: RefOr<Schema> = utoipa::schema!(#[inline] Vec<Pet>).into();
/// // will output
/// let generated = RefOr::T(Schema::Array(
///     Array::new(
///         ObjectBuilder::new()
///             .property("id", ObjectBuilder::new()
///                 .schema_type(SchemaType::Integer)
///                 .format(Some(SchemaFormat::KnownFormat(KnownFormat::Int32)))
///                 .build())
///             .required("id")
///             .property("name", Object::with_type(SchemaType::String))
///             .required("name")
///     )
/// ));
/// # assert_json_diff::assert_json_eq!(serde_json::to_value(&schema).unwrap(), serde_json::to_value(&generated).unwrap());
/// ```
///
/// [primitive]: https://doc.rust-lang.org/std/primitive/index.html
#[proc_macro]
pub fn schema(input: TokenStream) -> TokenStream {
    struct Schema {
        inline: bool,
        ty: syn::Type,
    }
    impl Parse for Schema {
        fn parse(input: ParseStream) -> syn::Result<Self> {
            let inline = if input.peek(Token![#]) && input.peek2(Bracket) {
                input.parse::<Token![#]>()?;

                let inline;
                bracketed!(inline in input);
                let i = inline.parse::<Ident>()?;
                i == "inline"
            } else {
                false
            };

            let ty = input.parse()?;

            Ok(Self { inline, ty })
        }
    }

    let schema = syn::parse_macro_input!(input as Schema);
    let type_tree = TypeTree::from_type(&schema.ty);

    let schema = ComponentSchema::new(ComponentSchemaProps {
        features: Some(vec![Feature::Inline(schema.inline.into())]),
        type_tree: &type_tree,
        deprecated: None,
        description: None,
        object_name: "",
    });

    schema.to_token_stream().into()
}

/// Tokenizes slice or Vec of tokenizable items as array either with reference (`&[...]`)
/// or without correctly to OpenAPI JSON.
#[cfg_attr(feature = "debug", derive(Debug))]
enum Array<'a, T>
where
    T: Sized + ToTokens,
{
    Owned(Vec<T>),
    #[allow(dead_code)]
    Borrowed(&'a [T]),
}

impl<T> Array<'_, T> where T: ToTokens + Sized {}

impl<V> FromIterator<V> for Array<'_, V>
where
    V: Sized + ToTokens,
{
    fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
        Self::Owned(iter.into_iter().collect())
    }
}

impl<'a, T> Deref for Array<'a, T>
where
    T: Sized + ToTokens,
{
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Owned(vec) => vec.as_slice(),
            Self::Borrowed(slice) => slice,
        }
    }
}

impl<T> ToTokens for Array<'_, T>
where
    T: Sized + ToTokens,
{
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let values = match self {
            Self::Owned(values) => values.iter(),
            Self::Borrowed(values) => values.iter(),
        };

        tokens.append(Group::new(
            proc_macro2::Delimiter::Bracket,
            values
                .fold(Punctuated::new(), |mut punctuated, item| {
                    punctuated.push_value(item);
                    punctuated.push_punct(Punct::new(',', proc_macro2::Spacing::Alone));

                    punctuated
                })
                .to_token_stream(),
        ));
    }
}

#[cfg_attr(feature = "debug", derive(Debug))]
enum Deprecated {
    True,
    False,
}

impl From<bool> for Deprecated {
    fn from(bool: bool) -> Self {
        if bool {
            Self::True
        } else {
            Self::False
        }
    }
}

impl ToTokens for Deprecated {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        tokens.extend(match self {
            Self::False => quote! { utoipa::openapi::Deprecated::False },
            Self::True => quote! { utoipa::openapi::Deprecated::True },
        })
    }
}

#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
enum Required {
    True,
    False,
}

impl From<bool> for Required {
    fn from(bool: bool) -> Self {
        if bool {
            Self::True
        } else {
            Self::False
        }
    }
}

impl From<features::Required> for Required {
    fn from(value: features::Required) -> Self {
        let features::Required(required) = value;
        crate::Required::from(required)
    }
}

impl ToTokens for Required {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        tokens.extend(match self {
            Self::False => quote! { utoipa::openapi::Required::False },
            Self::True => quote! { utoipa::openapi::Required::True },
        })
    }
}

#[derive(Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
struct ExternalDocs {
    url: String,
    description: Option<String>,
}

impl Parse for ExternalDocs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        const EXPECTED_ATTRIBUTE: &str = "unexpected attribute, expected any of: url, description";

        let mut external_docs = ExternalDocs::default();

        while !input.is_empty() {
            let ident = input.parse::<Ident>().map_err(|error| {
                syn::Error::new(error.span(), format!("{EXPECTED_ATTRIBUTE}, {error}"))
            })?;
            let attribute_name = &*ident.to_string();

            match attribute_name {
                "url" => {
                    external_docs.url = parse_utils::parse_next_literal_str(input)?;
                }
                "description" => {
                    external_docs.description = Some(parse_utils::parse_next_literal_str(input)?);
                }
                _ => return Err(syn::Error::new(ident.span(), EXPECTED_ATTRIBUTE)),
            }

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

        Ok(external_docs)
    }
}

impl ToTokens for ExternalDocs {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let url = &self.url;
        tokens.extend(quote! {
            utoipa::openapi::external_docs::ExternalDocsBuilder::new()
                .url(#url)
        });

        if let Some(ref description) = self.description {
            tokens.extend(quote! {
                .description(Some(#description))
            });
        }

        tokens.extend(quote! { .build() })
    }
}

/// Represents OpenAPI Any value used in example and default fields.
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub(self) enum AnyValue {
    String(TokenStream2),
    Json(TokenStream2),
    DefaultTrait {
        struct_ident: Ident,
        field_ident: Member,
    },
}

impl AnyValue {
    /// Parse `json!(...)` as [`AnyValue::Json`]
    fn parse_json(input: ParseStream) -> syn::Result<Self> {
        parse_utils::parse_json_token_stream(input).map(AnyValue::Json)
    }

    fn parse_any(input: ParseStream) -> syn::Result<Self> {
        if input.peek(Lit) {
            if input.peek(LitStr) {
                let lit_str = input.parse::<LitStr>().unwrap().to_token_stream();

                Ok(AnyValue::Json(lit_str))
            } else {
                let lit = input.parse::<Lit>().unwrap().to_token_stream();

                Ok(AnyValue::Json(lit))
            }
        } else {
            let fork = input.fork();
            let is_json = if fork.peek(syn::Ident) && fork.peek2(Token![!]) {
                let ident = fork.parse::<Ident>().unwrap();
                ident == "json"
            } else {
                false
            };

            if is_json {
                let json = parse_utils::parse_json_token_stream(input)?;

                Ok(AnyValue::Json(json))
            } else {
                let method = input.parse::<ExprPath>().map_err(|error| {
                    syn::Error::new(
                        error.span(),
                        "expected literal value, json!(...) or method reference",
                    )
                })?;

                Ok(AnyValue::Json(quote! { #method() }))
            }
        }
    }

    fn parse_lit_str_or_json(input: ParseStream) -> syn::Result<Self> {
        if input.peek(LitStr) {
            Ok(AnyValue::String(
                input.parse::<LitStr>().unwrap().to_token_stream(),
            ))
        } else {
            Ok(AnyValue::Json(parse_utils::parse_json_token_stream(input)?))
        }
    }

    fn new_default_trait(struct_ident: Ident, field_ident: Member) -> Self {
        Self::DefaultTrait {
            struct_ident,
            field_ident,
        }
    }
}

impl ToTokens for AnyValue {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        match self {
            Self::Json(json) => tokens.extend(quote! {
                serde_json::json!(#json)
            }),
            Self::String(string) => string.to_tokens(tokens),
            Self::DefaultTrait {
                struct_ident,
                field_ident,
            } => tokens.extend(quote! {
                serde_json::to_value(#struct_ident::default().#field_ident).unwrap()
            }),
        }
    }
}

trait ResultExt<T> {
    fn unwrap_or_abort(self) -> T;
    fn expect_or_abort(self, message: &str) -> T;
}

impl<T> ResultExt<T> for Result<T, syn::Error> {
    fn unwrap_or_abort(self) -> T {
        match self {
            Ok(value) => value,
            Err(error) => abort!(error.span(), format!("{error}")),
        }
    }

    fn expect_or_abort(self, message: &str) -> T {
        match self {
            Ok(value) => value,
            Err(error) => abort!(error.span(), format!("{error}: {message}")),
        }
    }
}

trait OptionExt<T> {
    fn expect_or_abort(self, message: &str) -> T;
}

impl<T> OptionExt<T> for Option<T> {
    fn expect_or_abort(self, message: &str) -> T {
        self.unwrap_or_else(|| abort!(Span::call_site(), message))
    }
}

/// Parsing utils
mod parse_utils {
    use std::fmt::Display;

    use proc_macro2::{Group, Ident, TokenStream};
    use quote::{quote, ToTokens};
    use syn::{
        parenthesized,
        parse::{Parse, ParseStream},
        punctuated::Punctuated,
        token::Comma,
        Error, Expr, LitBool, LitStr, Token,
    };

    use crate::ResultExt;

    #[cfg_attr(feature = "debug", derive(Debug))]
    pub enum Value {
        LitStr(LitStr),
        Expr(Expr),
    }

    impl Value {
        pub(crate) fn is_empty(&self) -> bool {
            matches!(self, Self::LitStr(s) if s.value().is_empty())
        }
    }

    impl Default for Value {
        fn default() -> Self {
            Self::LitStr(LitStr::new("", proc_macro2::Span::call_site()))
        }
    }

    impl Parse for Value {
        fn parse(input: ParseStream) -> syn::Result<Self> {
            if input.peek(LitStr) {
                Ok::<Value, Error>(Value::LitStr(input.parse::<LitStr>()?))
            } else {
                Ok(Value::Expr(input.parse::<Expr>()?))
            }
        }
    }

    impl ToTokens for Value {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            match self {
                Self::LitStr(str) => str.to_tokens(tokens),
                Self::Expr(expr) => expr.to_tokens(tokens),
            }
        }
    }

    impl Display for Value {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::LitStr(str) => write!(f, "{str}", str = str.value()),
                Self::Expr(expr) => write!(f, "{expr}", expr = expr.into_token_stream()),
            }
        }
    }

    pub fn parse_next<T: Sized>(input: ParseStream, next: impl FnOnce() -> T) -> T {
        input
            .parse::<Token![=]>()
            .expect_or_abort("expected equals token before value assignment");
        next()
    }

    pub fn parse_next_literal_str(input: ParseStream) -> syn::Result<String> {
        Ok(parse_next(input, || input.parse::<LitStr>())?.value())
    }

    pub fn parse_next_literal_str_or_include_str(input: ParseStream) -> syn::Result<Str> {
        Ok(parse_next(input, || input.parse::<Str>())?)
    }

    pub fn parse_next_literal_str_or_expr(input: ParseStream) -> syn::Result<Value> {
        parse_next(input, || Value::parse(input)).map_err(|error| {
            syn::Error::new(
                error.span(),
                format!("expected literal string or expression argument: {error}"),
            )
        })
    }

    pub fn parse_groups<T, R>(input: ParseStream) -> syn::Result<R>
    where
        T: Sized,
        T: Parse,
        R: FromIterator<T>,
    {
        Punctuated::<Group, Comma>::parse_terminated(input).and_then(|groups| {
            groups
                .into_iter()
                .map(|group| syn::parse2::<T>(group.stream()))
                .collect::<syn::Result<R>>()
        })
    }

    pub fn parse_punctuated_within_parenthesis<T>(
        input: ParseStream,
    ) -> syn::Result<Punctuated<T, Comma>>
    where
        T: Parse,
    {
        let content;
        parenthesized!(content in input);
        Punctuated::<T, Comma>::parse_terminated(&content)
    }

    pub fn parse_bool_or_true(input: ParseStream) -> syn::Result<bool> {
        if input.peek(Token![=]) && input.peek2(LitBool) {
            input.parse::<Token![=]>()?;

            Ok(input.parse::<LitBool>()?.value())
        } else {
            Ok(true)
        }
    }

    /// Parse `json!(...)` as a [`TokenStream`].
    pub fn parse_json_token_stream(input: ParseStream) -> syn::Result<TokenStream> {
        if input.peek(syn::Ident) && input.peek2(Token![!]) {
            input.parse::<Ident>().and_then(|ident| {
                if ident != "json" {
                    return Err(Error::new(
                        ident.span(),
                        format!("unexpected token {ident}, expected: json!(...)"),
                    ));
                }

                Ok(ident)
            })?;
            input.parse::<Token![!]>()?;

            Ok(input.parse::<Group>()?.stream())
        } else {
            Err(Error::new(
                input.span(),
                "unexpected token, expected json!(...)",
            ))
        }
    }

    #[derive(Clone)]
    #[cfg_attr(feature = "debug", derive(Debug))]
    pub enum Str {
        String(String),
        IncludeStr(TokenStream),
    }

    impl Parse for Str {
        fn parse(input: ParseStream) -> syn::Result<Self> {
            if input.peek(LitStr) {
                Ok(Self::String(input.parse::<LitStr>()?.value()))
            } else {
                let include_str = input.parse::<Ident>()?;
                let bang = input.parse::<Option<Token![!]>>()?;
                if include_str != "include_str" || bang.is_none() {
                    return Err(Error::new(
                        include_str.span(),
                        "unexpected token, expected either literal string or include_str!(...)",
                    ));
                }
                Ok(Self::IncludeStr(input.parse::<Group>()?.stream()))
            }
        }
    }

    impl ToTokens for Str {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            match self {
                Self::String(str) => str.to_tokens(tokens),
                Self::IncludeStr(include_str) => {
                    tokens.extend(quote! { include_str!(#include_str) })
                }
            }
        }
    }
}