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
#![warn(missing_docs)]
#![warn(rustdoc::missing_doc_code_examples)]
#![allow(clippy::needless_doctest_main)]

//! Lightweight and flexible command line argument parser with derive and combinatoric style API

//! # Derive and combinatoric API
//!
//! `bpaf` supports both combinatoric and derive APIs and it's possible to mix and match both APIs
//! at once. Both APIs provide access to mostly the same features, some things are more convenient
//! to do with derive (usually less typing), some - with combinatoric (usually maximum flexibility
//! and reducing boilerplate structs). In most cases using just one would suffice. Whenever
//! possible APIs share the same keywords and overall structure. Documentation for combinatoric API
//! also explains how to perform the same action in derive style.
//!
//! `bpaf` supports dynamic shell completion for `bash`, `zsh`, `fish` and `elvish`.

//! # Quick links
//!
//! - [Derive tutorial](crate::_derive_tutorial)
//! - [Combinatoric tutorial](crate::_combinatoric_tutorial)
//! - [Some very unusual cases](crate::_unusual)
// - [Picking the right words](crate::_flow)
//! - [Batteries included](crate::batteries)
//! - [Q&A](https://github.com/pacak/bpaf/discussions/categories/q-a)

//! # Quick start, derive edition
//!
//! 1. Add `bpaf` under `[dependencies]` in your `Cargo.toml`
//! ```toml
//! [dependencies]
//! bpaf = { version = "0.6", features = ["derive"] }
//! ```
//!
//! 2. Define a structure containing command line attributes and run generated function
//! ```no_run
//! use bpaf::Bpaf;
//!
//! #[derive(Clone, Debug, Bpaf)]
//! #[bpaf(options, version)]
//! /// Accept speed and distance, print them
//! struct SpeedAndDistance {
//!     /// Speed in KPH
//!     speed: f64,
//!     /// Distance in miles
//!     distance: f64,
//! }
//!
//! fn main() {
//!     // #[derive(Bpaf)] generates `speed_and_distance` function
//!     let opts = speed_and_distance().run();
//!     println!("Options: {:?}", opts);
//! }
//! ```
//!
//! 3. Try to run the app
//! ```console
//! % very_basic --help
//! Accept speed and distance, print them
//!
//! Usage: --speed ARG --distance ARG
//!
//! Available options:
//!         --speed <ARG>     Speed in KPH
//!         --distance <ARG>  Distance in miles
//!     -h, --help            Prints help information
//!     -V, --version         Prints version information
//!
//! % very_basic --speed 100
//! Expected --distance ARG, pass --help for usage information
//!
//! % very_basic --speed 100 --distance 500
//! Options: SpeedAndDistance { speed: 100.0, distance: 500.0 }
//!
//! % very_basic --version
//! Version: 0.5.0 (taken from Cargo.toml by default)
//!```

//! # Quick start, combinatoric edition
//!
//! 1. Add `bpaf` under `[dependencies]` in your `Cargo.toml`
//! ```toml
//! [dependencies]
//! bpaf = "0.6"
//! ```
//!
//! 2. Declare parsers for components, combine them and run it
//! ```no_run
//! use bpaf::{construct, long, Parser};
//! #[derive(Clone, Debug)]
//! struct SpeedAndDistance {
//!     /// Dpeed in KPH
//!     speed: f64,
//!     /// Distance in miles
//!     distance: f64,
//! }
//!
//! fn main() {
//!     // primitive parsers
//!     let speed = long("speed")
//!         .help("Speed in KPG")
//!         .argument::<f64>("SPEED");
//!
//!     let distance = long("distance")
//!         .help("Distance in miles")
//!         .argument::<f64>("DIST");
//!
//!     // parser containing information about both speed and distance
//!     let parser = construct!(SpeedAndDistance { speed, distance });
//!
//!     // option parser with metainformation attached
//!     let speed_and_distance
//!         = parser
//!         .to_options()
//!         .descr("Accept speed and distance, print them");
//!
//!     let opts = speed_and_distance.run();
//!     println!("Options: {:?}", opts);
//! }
//! ```
//!
//! 3. Try to run it, output should be similar to derive version

//! # Design goals: flexibility, reusability, correctness

//! Library allows to consume command line arguments by building up parsers for individual
//! arguments and combining those primitive parsers using mostly regular Rust code plus one macro.
//! For example it's possible to take a parser that requires a single floating point number and
//! transform it to a parser that takes several of them or takes it optionally so different
//! subcommands or binaries can share a lot of the code:

//! ```rust
//! # use bpaf::*;
//! // a regular function that doesn't depend on any context, you can export it
//! // and share across subcommands and binaries
//! fn speed() -> impl Parser<f64> {
//!     long("speed")
//!         .help("Speed in KPH")
//!         .argument::<f64>("SPEED")
//! }
//!
//! // this parser accepts multiple `--speed` flags from a command line when used,
//! // collecting results into a vector
//! fn multiple_args() -> impl Parser<Vec<f64>> {
//!     speed().many()
//! }
//!
//! // this parser checks if `--speed` is present and uses value of 42.0 if it's not
//! fn with_fallback() -> impl Parser<f64> {
//!     speed().fallback(42.0)
//! }
//! ```
//!
//! At any point you can apply additional validation or fallback values in terms of current parsed
//! state of each subparser and you can have several stages as well:
//!
//! ```rust
//! # use bpaf::*;
//! #[derive(Clone, Debug)]
//! struct Speed(f64);
//! fn speed() -> impl Parser<Speed> {
//!     long("speed")
//!         .help("Speed in KPH")
//!         .argument::<f64>("SPEED")
//!
//!         // You can perform additional validation with `parse` and `guard` functions
//!         // in as many steps as required.
//!         // Before and after next two applications the type is still `impl Parser<f64>`
//!         .guard(|&speed| speed >= 0.0, "You need to buy a DLC to move backwards")
//!         .guard(|&speed| speed <= 100.0, "You need to buy a DLC to break the speed limits")
//!
//!         // You can transform contained values, next line gives `impl Parser<Speed>` as a result
//!         .map(|speed| Speed(speed))
//! }
//! ```
//!
//! Library follows **parse, don’t validate** approach to validation when possible. Usually you parse
//! your values just once and get the results as a rust struct/enum with strict types rather than a
//! stringly typed hashmap with stringly typed values in both combinatoric and derive APIs.

//! # Design goals: restrictions
//!
//! The main restricting library sets is that you can't use parsed values (but not the fact that
//! parser succeeded or failed) to decide how to parse subsequent values. In other words parsers
//! don't have the monadic strength, only the applicative one.
//!
//! To give an example, you can implement this description:
//!
//! > Program takes one of `--stdout` or `--file` flag to specify the output target, when it's `--file`
//! > program also requires `-f` attribute with the filename
//!
//! But not this one:
//!
//! > Program takes an `-o` attribute with possible values of `'stdout'` and `'file'`, when it's `'file'`
//! > program also requires `-f` attribute with the filename
//!
//! This set of restrictions allows `bpaf` to extract information about the structure of the computations
//! to generate help, dynamic completion and overall results in less confusing enduser experience
//!
//! `bpaf` performs no parameter names validation, in fact having multiple parameters
//! with the same name is fine and you can combine them as alternatives and performs no fallback
//! other than [`fallback`](Parser::fallback). You need to pay attention to the order of the
//! alternatives inside the macro: parser that consumes the left most available argument on a
//! command line wins, if this is the same - left most parser wins. So to parse a parameter
//! `--test` that can be both [`switch`](NamedArg::switch) and [`argument`](NamedArg::argument) you
//! should put the argument one first.
//!
//! You must place [`positional`] items at the end of a structure in derive API or consume them
//! as last arguments in derive API.

//! # Dynamic shell completion
//!
//! `bpaf` implements shell completion to allow to automatically fill in not only flag and command
//! names, but also argument and positional item values.
//!
//! 1. Enable `autocomplete` feature:
//!    ```toml
//!    bpaf = { version = "0.6.0", features = ["autocomplete"] }
//!    ```
//! 2. Decorate [`argument`](NamedArg::argument) and [`positional`] parsers with
//!    [`complete`](Parser::complete) to autocomplete argument values
//!
//! 3. Depending on your shell generate appropriate completion file and place it to whereever your
//!    shell is going to look for it, name of the file should correspond in some way to name of
//!    your program. Consult manual for your shell for the location and named conventions:
//!    1. **bash**: for the first `bpaf` completion you need to install the whole script
//!        ```console
//!        $ your_program --bpaf-complete-style-bash >> ~/.bash_completion
//!        ```
//!        but since the script doesn't depend on a program name - it's enough to do this for
//!        each next program
//!        ```console
//!        echo "complete -F _bpaf_dynamic_completion your_program" >> ~/.bash_completion
//!        ```
//!    2. **zsh**: note `_` at the beginning of the filename
//!       ```console
//!       $ your_program --bpaf-complete-style-zsh > ~/.zsh/_your_program
//!       ```
//!    3. **fish**
//!       ```console
//!       $ your_program --bpaf-complete-style-fish > ~/.config/fish/completions/your_program.fish
//!       ```
//!    4. **elvish** - not sure where to put it, documentation is a bit cryptic
//!       ```console
//!       $ your_program --bpaf-complete-style-elvish
//!       ```
//! 4. Restart your shell - you need to done it only once or optionally after bpaf major version
//!    upgrade: generated completion files contain only instructions how to ask your program for
//!    possible completions and don't change even if options are different.
//!
//! 5. Generated scripts rely on your program being accessible in $PATH

//! # Design non goals: performance
//!
//! Library aims to optimize for flexibility, reusability and compilation time over runtime
//! performance which means it might perform some additional clones, allocations and other less
//! optimal things. In practice unless you are parsing tens of thousands of different parameters
//! and your app exits within microseconds - this won't affect you. That said - any actual
//! performance related problems with real world applications is a bug.

//! # More examples
//!
//! You can find a bunch more examples here: <https://github.com/pacak/bpaf/tree/master/examples>
//!
//!
//! They're usually documented or at least contain an explanation to important bits and you can see
//! how they work by cloning the repo and running
//! ```shell
//! $ cargo run --example example_name
//! ```

//! # Testing your own parsers
//!
//! You can test your own parsers to maintain compatibility or simply checking expected output
//! with [`run_inner`](OptionParser::run_inner)
//!
//! ```rust
//! # use bpaf::*;
//! #[derive(Debug, Clone, Bpaf)]
//! #[bpaf(options)]
//! pub struct Options {
//!     pub user: String
//! }
//!
//! #[test]
//! fn test_my_options() {
//!     let help = options()
//!         .run_inner(Args::from(&["--help"]))
//!         .unwrap_err()
//!         .unwrap_stdout();
//!     let expected_help = "\
//! Usage --user <ARG>
//! <skip>
//! ";
//!
//!     assert_eq!(help, expected_help);
//! }
//! ```
//!

//! # Cargo features
//!
//! - `derive`: adds a dependency on `bpaf_derive` crate and reexport `Bpaf` derive macro. You
//!   need to enable it to use derive API. Disabled by default.
//!
//! - `extradocs`: used internally to include tutorials to <https://docs.rs/bpaf>, no reason to
//! enable it for local development unless you want to build your own copy of the documentation
//! (<https://github.com/rust-lang/cargo/issues/8905>). Disabled by default.
//!
//! - `batteries`: helpers implemented with public `bpaf` API. Enabled by default.
//!
//! - `autocomplete`: enables support for shell autocompletion. Disabled by default.

#[cfg(feature = "extradocs")]
pub mod _combinatoric_tutorial;
#[cfg(feature = "extradocs")]
pub mod _derive_tutorial;
#[cfg(feature = "extradocs")]
mod _flow;
#[cfg(feature = "extradocs")]
pub mod _unusual;
mod arg;
mod args;
#[cfg(feature = "batteries")]
pub mod batteries;
#[cfg(feature = "autocomplete")]
mod complete_gen;
#[cfg(feature = "autocomplete")]
mod complete_run;
mod info;
mod item;
mod meta;
mod meta_help;
mod meta_usage;
mod meta_youmean;
pub mod params;
mod structs;
#[cfg(test)]
mod tests;

#[doc(hidden)]
pub use crate::info::Error;
use crate::item::Item;
use std::marker::PhantomData;
#[doc(hidden)]
pub use structs::{ParseBox, ParseCon};

pub mod parsers {
    //! This module exposes parsers that accept further configuration with builder pattern
    //!
    //! In most cases you won't be using those names directly, they're only listed here to provide
    //! access to documentation
    pub use crate::params::{NamedArg, ParseArgument, ParseCommand, ParsePositional};
    pub use crate::structs::{ParseBox, ParseMany, ParseOptional, ParseSome};
}

use structs::{
    ParseAdjacent, ParseAnywhere, ParseFail, ParseFallback, ParseFallbackWith, ParseGroupHelp,
    ParseGuard, ParseHide, ParseMany, ParseMap, ParseOptional, ParseOrElse, ParsePure, ParseSome,
    ParseWith,
};

#[cfg(feature = "autocomplete")]
use structs::{ParseComp, ParseCompStyle};

#[doc(inline)]
pub use crate::args::Args;
pub use crate::from_os_str::{FromOsStr, FromUtf8};
pub use crate::info::OptionParser;
pub use crate::meta::Meta;

#[doc(inline)]
pub use crate::params::{any, command, env, long, positional, short};

#[cfg(doc)]
pub(self) use crate::parsers::NamedArg;

#[doc(inline)]
#[cfg(feature = "bpaf_derive")]
pub use bpaf_derive::Bpaf;
mod from_os_str;
pub use from_os_str::*;

/// Compose several parsers to produce a single result
///
/// # Usage reference
/// ```rust
/// # use bpaf::*;
/// # { struct Res(bool, bool, bool);
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // structs with unnamed fields:
/// construct!(Res(a, b, c));
/// # }
///
/// # { struct Res { a: bool, b: bool, c: bool }
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // structs with named fields:
/// construct!(Res {a, b, c});
/// # }
///
/// # { enum Ty { Res(bool, bool, bool) }
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // enums with unnamed fields:
/// construct!(Ty::Res(a, b, c));
/// # }
///
/// # { enum Ty { Res { a: bool, b: bool, c: bool } }
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // enums with named fields:
/// construct!(Ty::Res {a, b, c});
/// # }
///
/// # { let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // tuples:
/// construct!(a, b, c);
/// # }
///
/// # { let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // parallel composition, tries all parsers, picks succeeding left most one:
/// construct!([a, b, c]);
/// # }
///
/// // defining primitive parsers inside construct macro :)
/// construct!(a(short('a').switch()), b(long("arg").argument::<usize>("ARG")));
/// ```
///
/// # Combinatoric usage
/// `construct!` can compose parsers sequentially or in parallel.
///
/// Sequential composition runs each parser and if all of them succeed you get a parser object of a
/// new type back. Placeholder names for values inside `construct!` macro must correspond to both
/// struct/enum names and parser names present in scope. In examples below `a` corresponds to a
/// function and `b` corresponds to a variable name. Note parens in `a()`, you must to use them to
/// indicate function parsers.
///
/// Inside the parens you can put a whole expression to use instead of
/// having to define them in advance: `a(positional::<String>("POS"))`. Probably a good idea to use this
/// approach only for simple parsers.
///
/// ```rust
/// # use bpaf::*;
/// struct Res (u32, u32);
/// enum Ul { T { a: u32, b: u32 } }
///
/// // You can share parameters across multiple construct invocations
/// // if defined as functions
/// fn a() -> impl Parser<u32> {
///     short('a').argument::<u32>("N")
/// }
///
/// // You can construct structs or enums with unnamed fields
/// fn res() -> impl Parser<Res> {
///     let b = short('b').argument::<u32>("n");
///     construct!(Res ( a(), b ))
/// }
///
/// // You can construct structs or enums with named fields
/// fn ult() -> impl Parser<Ul> {
///     let b = short('b').argument::<u32>("n");
///     construct!(Ul::T { a(), b })
/// }
///
/// // You can also construct simple tuples
/// fn tuple() -> impl Parser<(u32, u32)> {
///     let b = short('b').argument::<u32>("n");
///     construct!(a(), b)
/// }
///
/// // You can create boxed version of parsers so the type matches as long
/// // as return type is the same - can be useful for all sort of dynamic parsers
/// fn boxed() -> impl Parser<u32> {
///     let a = short('a').argument::<u32>("n");
///     construct!(a)
/// }
///
/// // In addition to having primitives defined before using them - you can also define
/// // them directly inside construct macro. Probably only a good idea if you have only simple
/// // components
/// struct Options {
///     arg: u32,
///     switch: bool,
/// }
///
/// fn coyoda() -> impl Parser<Options> {
///     construct!(Options {
///         arg(short('a').argument::<u32>("ARG")),
///         switch(short('s').switch())
///     })
/// }
/// ```
///
/// Parallel composition picks one of several available parsers (result types must match) and returns a
/// parser object of the same type. Similar to sequential composition you can use parsers from variables
/// or functions:
///
/// ```rust
/// # use bpaf::*;
/// fn b() -> impl Parser<u32> {
///     short('b').argument::<u32>("NUM")
/// }
///
/// fn a_or_b() -> impl Parser<u32> {
///     let a = short('a').argument::<u32>("NUM");
///     // equivalent way of writing this would be `a.or_else(b())`
///     construct!([a, b()])
/// }
/// ```
///
/// # Derive usage
///
/// `bpaf_derive` would combine fields of struct or enum constructors sequentially and enum
/// variants in parallel.
/// ```rust
/// # use bpaf::*;
/// // to satisfy this parser user needs to pass both -a and -b
/// #[derive(Debug, Clone, Bpaf)]
/// struct Res {
///     a: u32,
///     b: u32,
/// }
///
/// // to satisfy this parser user needs to pass one (and only one) of -a, -b, -c or -d
/// #[derive(Debug, Clone, Bpaf)]
/// enum Enumeraton {
///     A { a: u32 },
///     B { b: u32 },
///     C { c: u32 },
///     D { d: u32 },
/// }
///
/// // here user needs to pass either both -a AND -b or both -c AND -d
/// #[derive(Debug, Clone, Bpaf)]
/// enum Ult {
///     AB { a: u32, b: u32 },
///     CD { c: u32, d: u32 }
/// }
/// ```

#[macro_export]
macro_rules! construct {
    // construct!(Enum::Cons { a, b, c })
    ($(::)? $ns:ident $(:: $con:ident)* { $($tokens:tt)* }) => {{ $crate::construct!(@prepare [named [$ns $(:: $con)*]] [] $($tokens)*) }};

    // construct!(Enum::Cons ( a, b, c ))
    ($(::)? $ns:ident $(:: $con:ident)* ( $($tokens:tt)* )) => {{ $crate::construct!(@prepare [pos [$ns $(:: $con)*]] [] $($tokens)*) }};

    // construct!( a, b, c )
    ($first:ident $($tokens:tt)*) => {{ $crate::construct!(@prepare [pos] [] $first $($tokens)*) }};

    // construct![a, b, c]
    ([$first:ident $($tokens:tt)*]) => {{ $crate::construct!(@prepare [alt] [] $first $($tokens)*) }};

    (@prepare $ty:tt [$($fields:tt)*] $field:ident () $(, $($rest:tt)*)? ) => {{
        let $field = $field();
        $crate::construct!(@prepare $ty [$($fields)* $field] $($($rest)*)?)
    }};
    (@prepare $ty:tt [$($fields:tt)*] $field:ident ($expr:expr) $(, $($rest:tt)*)?) => {{
        let $field = $expr;
        $crate::construct!(@prepare $ty [$($fields)* $field] $($($rest)*)?)
    }};
    (@prepare $ty:tt [$($fields:tt)*] $field:ident $(, $($rest:tt)*)? ) => {{
        $crate::construct!(@prepare $ty [$($fields)* $field] $($($rest)* )?)
    }};

    (@prepare [alt] [$first:ident $($fields:ident)*]) => {
        #[allow(deprecated)]
        { use $crate::Parser; $first $(.or_else($fields))* }
    };

    (@prepare $ty:tt [$($fields:tt)*]) => {
        $crate::__cons_prepare!($ty [$($fields)*])
    };

    (@make [named [$($con:tt)+]] [$($fields:ident)*]) => { $($con)+ { $($fields),* } };
    (@make [pos   [$($con:tt)+]] [$($fields:ident)*]) => { $($con)+ ( $($fields),* ) };
    (@make [pos] [$($fields:ident)*]) => { ( $($fields),* ) };
}

#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "autocomplete"))]
/// to avoid extra parsing when autocomplete feature is off
macro_rules! __cons_prepare {
    ([pos] [$field:ident]) => { $crate::ParseBox { inner: Box::new($field) } };

    ($ty:tt [$($fields:ident)+]) => {{
        use $crate::Parser;
        let meta = $crate::Meta::And(vec![ $($fields.meta()),+ ]);
        let inner = move |args: &mut $crate::Args| {
            $(let $fields = $fields.eval(args)?;)+
            args.current = None;
            ::std::result::Result::Ok::<_, $crate::Error>
                ($crate::construct!(@make $ty [$($fields)+]))
        };
        $crate::ParseCon { inner, meta }
    }};
}

#[macro_export]
#[doc(hidden)]
#[cfg(feature = "autocomplete")]
/// for completion bpaf needs to observe all the failures in a branch
macro_rules! __cons_prepare {
    ([pos] [$field:ident]) => { $crate::ParseBox { inner: Box::new($field) } };

    ($ty:tt [$($fields:ident)+]) => {{
        use $crate::Parser;
        let meta = $crate::Meta::And(vec![ $($fields.meta()),+ ]);
        let inner = move |args: &mut $crate::Args| {
            $(let $fields = if args.is_comp() {
                $fields.eval(args)
            } else {
                Ok($fields.eval(args)?)
            };)+
            $(let $fields = $fields?;)+

            args.current = None;
            ::std::result::Result::Ok::<_, $crate::Error>
                ($crate::construct!(@make $ty [$($fields)+]))
        };
        $crate::ParseCon { inner, meta }
    }};
}

#[cfg(doc)]
use std::str::FromStr;

/// Simple or composed argument parser
///
/// # Overview
///
/// It's best to think of an object implementing [`Parser`] trait as a container with a value
/// inside that are composable with other `Parser` containers using [`construct!`] and the only
/// way to extract this value is by transforming it to [`OptionParser`] with
/// [`to_options`](Parser::to_options) and running it with [`run`](OptionParser::run). At which
/// point you either get your value out or `bpaf` would generate a message describing a problem
/// (missing argument, validation failure, user requested help, etc) and the program would
/// exit.
///
/// Values inside can be of any type for as long as they implement `Debug`, `Clone` and
/// there's no lifetimes other than static.
///
/// When consuming the values you can jump straight to a value that implements either [`FromOsStr`] or
/// [`FromStr`] trait then transform into something that your program would actually use. Alternatively
/// you can consume either `String` or `OsString` and parse that by hand. It's better to perform
/// as much parsing and validation inside the `Parser` as possible so the program itself gets
/// strictly typed and correct value while user gets immediate feedback on what's wrong with the
/// arguments they pass.
///
/// For example suppose your program needs user to specify a dimensions of a rectangle, with sides
/// being 1..20 units long and the total area must not exceed 200 units square. A parser that
/// consumes it might look like this:
///
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Copy, Clone)]
/// struct Rectangle {
///     width: u32,
///     height: u32,
/// }
///
/// fn rectangle() -> impl Parser<Rectangle> {
///     let invalid_size = "Sides of a rectangle must be 1..20 units long";
///     let invalid_area = "Area of a rectangle must not exceed 200 units square";
///     let width = long("width")
///         .help("Width of the rectangle")
///         .argument::<u32>("PX")
///         .guard(|&x| 1 <= x && x <= 10, invalid_size);
///     let height = long("height")
///         .help("Height of the rectangle")
///         .argument::<u32>("PX")
///         .guard(|&x| 1 <= x && x <= 10, invalid_size);
///     construct!(Rectangle { width, height })
///         .guard(|&r| r.width * r.height <= 400, invalid_area)
/// }
/// ```
///
///
/// # Derive specific considerations
///
/// Every method defined on this trait belongs to the `postprocessing` section of the field
/// annotation. `bpaf_derive` would try to figure out what chain to use for as long as there's no
/// options changing the type: you can use [`fallback`](Parser::fallback_with),
/// [`fallback_with`](Parser::fallback_with), [`guard`](Parser::guard), [`hide`](Parser::hide`) and
/// [`group_help`](Parser::group_help) but not the rest of them.
///
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
///     // no annotation at all - `bpaf_derive` inserts implicit `argument` and gets the right type
///     number_1: u32,
///
///     // fallback isn't changing the type so `bpaf_derive` still handles it
///     #[bpaf(fallback(42))]
///     number_2: u32,
///
///     // `bpaf_derive` inserts implicit `argument`, `optional` and the right type
///     number_3: Option<u32>,
///
///     // fails to compile: you need to specify a consumer, `argument` or `argument_os`
///     // #[bpaf(optional)]
///     // number_4: Option<u32>
///
///     // fails to compile: you also need to specify how to go from String to u32
///     // #[bpaf(argument("N"), optional)]
///     // number_5: Option<u32>,
///
///     // explicit consumer and a full postprocessing chain
///     #[bpaf(argument::<u32>("N"), optional)]
///     number_6: Option<u32>,
/// }
/// ```
pub trait Parser<T> {
    /// Evaluate inner function
    ///
    /// Mostly internal implementation details, you can try using it to test your parsers
    // it's possible to move this function from the trait to the structs but having it
    // in the trait ensures the composition always works
    #[doc(hidden)]
    fn eval(&self, args: &mut Args) -> Result<T, Error>;

    /// Included information about the parser
    ///
    /// Mostly internal implementation details, you can try using it to test your parsers
    // it's possible to move this function from the trait to the structs but having it
    // in the trait ensures the composition always works
    #[doc(hidden)]
    fn meta(&self) -> Meta;

    // change shape
    // {{{ many
    /// Consume zero or more items from a command line and collect them into [`Vec`]
    ///
    /// `many` preserves any parsing falures and propagates them outwards, with extra
    /// [`catch`](ParseMany::catch) statement you can instead stop at the first value
    /// that failed to parse and ignore it and all the subsequent ones.
    ///
    /// `many` only collects elements that only consume something from the argument list.
    ///
    /// # Combinatoric usage:
    /// ```rust
    /// # use bpaf::*;
    /// fn numbers() -> impl Parser<Vec<u32>> {
    ///     short('n')
    ///         .argument::<u32>("NUM")
    ///         .many()
    /// }
    /// ```
    ///
    /// # Derive usage:
    /// `bpaf` would insert implicit `many` when resulting type is a vector
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(short, argument("NUM"))]
    ///     numbers: Vec<u32>
    /// }
    /// ```
    /// But it's also possible to specify it explicitly, both cases renerate the same code.
    /// Note, since using `many` resets the postprocessing chain - you also need to specify
    /// `argument`'s turbofish.
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(short, argument::<u32>("NUM"), many)]
    ///     numbers: Vec<u32>
    /// }
    /// ```
    ///
    ///
    /// # Example
    /// ```console
    /// $ app -n 1 -n 2 -n 3
    /// // [1, 2, 3]
    /// ```
    ///
    /// # See also
    /// [`some`](Parser::some) also collects results to a vector but requires at least one
    /// element to succeed
    fn many(self) -> ParseMany<Self>
    where
        Self: Sized,
    {
        ParseMany {
            inner: self,
            catch: false,
        }
    }
    // }}}

    // {{{ some
    /// Consume one or more items from a command line
    ///
    /// Takes a string used as an error message if there's no specified parameters
    ///
    /// `some` preserves any parsing falures and propagates them outwards, with extra
    /// [`catch`](ParseSome::catch) statement you can instead stop at the first value
    /// that failed to parse and ignore it and all the subsequent ones.
    ///
    /// `some` only collects elements that only consume something from the argument list.
    ///
    /// # Combinatoric usage:
    /// ```rust
    /// # use bpaf::*;
    /// let numbers
    ///     = short('n')
    ///     .argument::<u32>("NUM")
    ///     .some("Need at least one number");
    /// # drop(numbers);
    /// ```
    ///
    /// # Derive usage
    /// Since using `some` resets the postprocessing chain - you also might need to specify
    /// the type in turbofish:
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(short, argument::<u32>("NUM"), some("Need at least one number"))]
    ///     numbers: Vec<u32>
    /// }
    /// ```
    ///
    ///
    /// # Example
    /// ```console
    /// $ app
    /// // fails with "Need at least one number"
    /// $ app -n 1 -n 2 -n 3
    /// // [1, 2, 3]
    /// ```
    ///
    /// # See also
    /// [`many`](Parser::many) also collects results to a vector but succeeds with
    /// no matching values
    #[must_use]
    fn some(self, message: &'static str) -> ParseSome<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseSome {
            inner: self,
            message,
            catch: false,
        }
    }
    // }}}

    // {{{ optional
    /// Turn a required argument into optional one
    ///
    /// `optional` converts any missing items into is `None` and passes the remaining parsing
    /// failures untouched. With extra [`catch`](ParseOptional::catch) statement you can handle
    /// those failures too.
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn number() -> impl Parser<Option<u32>> {
    ///     short('n')
    ///         .argument::<u32>("NUM")
    ///         .optional()
    /// }
    /// ```
    ///
    /// # Derive usage
    ///
    /// By default `bpaf_derive` would automatically use optional for fields of type `Option<T>`,
    /// for as long as it's not prevented from doing so by present postprocessing options
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///    #[bpaf(short, argument("NUM"))]
    ///    number: Option<u32>
    /// }
    /// ```
    ///
    /// But it's also possible to specify it explicitly
    /// example.
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///    #[bpaf(short, argument::<u32>("NUM"), optional)]
    ///    number: Option<u32>
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app
    /// // None
    /// $ app -n 42
    /// // Some(42)
    /// ```
    #[must_use]
    fn optional(self) -> ParseOptional<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseOptional {
            inner: self,
            catch: false,
        }
    }
    // }}}

    // parse
    // {{{ parse
    /// Apply a failing transformation to a contained value
    ///
    /// Transformation preserves present/absent state of the value: to parse an optional value you
    /// can either first try to `parse` it and then mark as [`optional`](Parser::optional) or first
    /// deal with the optionality and then parse a value wrapped in [`Option`]. In most cases
    /// former approach is more concise.
    ///
    /// Similarly it is possible to parse multiple items with [`many`](Parser::many) or
    /// [`some`](Parser::some) by either parsing a single item first and then turning it into a [`Vec`]
    /// or collecting them into a [`Vec`] first and then parsing the whole vector. Former approach
    /// is more concise.
    ///
    /// This is a most general of transforming parsers and you can express
    /// [`map`](Parser::map) and [`guard`](Parser::guard) in terms of it.
    ///
    /// Examples given here are a bit artificail, to parse a value from string you can specify
    /// the type directly in `argument`'s turbofish
    ///
    /// # Combinatoric usage:
    /// ```rust
    /// # use bpaf::*;
    /// # use std::str::FromStr;
    /// fn number() -> impl Parser<u32> {
    ///     short('n')
    ///         .argument::<String>("NUM")
    ///         .parse(|s| u32::from_str(&s))
    /// }
    /// ```
    /// # Derive usage:
    /// `parse` takes a single parameter: function name to call. Function type should match
    /// parameter `F` used by `parse` in combinatoric API.
    /// ```rust
    /// # use bpaf::*;
    /// # use std::str::FromStr;
    /// # use std::num::ParseIntError;
    /// fn read_number(s: String) -> Result<u32, ParseIntError> {
    ///     u32::from_str(&s)
    /// }
    ///
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(short, argument::<String>("NUM"), parse(read_number))]
    ///     number: u32
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app -n 12
    /// // 12
    /// # app -n pi
    /// // fails with "Couldn't parse "pi": invalid numeric literal"
    /// ```
    ///
    fn parse<F, R, E>(self, f: F) -> ParseWith<T, Self, F, E, R>
    where
        Self: Sized + Parser<T>,
        F: Fn(T) -> Result<R, E>,
        E: ToString,
    {
        ParseWith {
            inner: self,
            inner_res: PhantomData,
            parse_fn: f,
            res: PhantomData,
            err: PhantomData,
        }
    }
    // }}}

    // {{{ map
    /// Apply a pure transformation to a contained value
    ///
    /// A common case of [`parse`](Parser::parse) method, exists mostly for convenience.
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn number() -> impl Parser<u32> {
    ///     short('n')
    ///         .argument::<u32>("NUM")
    ///         .map(|v| v * 2)
    /// }
    /// ```
    ///
    /// # Derive usage
    /// ```rust
    /// # use bpaf::*;
    /// fn double(num: u32) -> u32 {
    ///     num * 2
    /// }
    ///
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(short, argument::<u32>("NUM"), map(double))]
    ///     number: u32,
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app -n 21
    /// // 42
    /// ```
    fn map<F, R>(self, map: F) -> ParseMap<T, Self, F, R>
    where
        Self: Sized + Parser<T>,
        F: Fn(T) -> R + 'static,
    {
        ParseMap {
            inner: self,
            inner_res: PhantomData,
            map_fn: map,
            res: PhantomData,
        }
    }
    // }}}

    // {{{ guard
    /// Validate or fail with a message
    ///
    /// If value doesn't satisfy the constraint - parser fails with the specified error message.
    ///
    /// # Combinatoric usage
    ///
    /// ```rust
    /// # use bpaf::*;
    /// fn number() -> impl Parser<u32> {
    ///     short('n')
    ///         .argument::<u32>("NUM")
    ///         .guard(|n| *n <= 10, "Values greater than 10 are only available in the DLC pack!")
    /// }
    /// ```
    ///
    /// # Derive usage
    /// Unlike combinator counterpart, derive variant of `guard` takes a function name instead
    /// of a closure, mostly to keep things clean. Second argument can be either a string literal
    /// or a constant name for a static [`str`].
    ///
    /// ```rust
    /// # use bpaf::*;
    /// fn dlc_check(number: &u32) -> bool {
    ///     *number <= 10
    /// }
    ///
    /// const DLC_NEEDED: &str = "Values greater than 10 are only available in the DLC pack!";
    ///
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(short, argument("NUM"), guard(dlc_check, DLC_NEEDED))]
    ///     number: u32,
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app -n 100
    /// // fails with "Values greater than 10 are only available in the DLC pack!"
    /// $ app -n 5
    /// // 5
    /// ```
    #[must_use]
    fn guard<F>(self, check: F, message: &'static str) -> ParseGuard<Self, F>
    where
        Self: Sized + Parser<T>,
        F: Fn(&T) -> bool,
    {
        ParseGuard {
            inner: self,
            check,
            message,
        }
    }
    // }}}

    // combine
    // {{{ fallback
    /// Use this value as default if value isn't present on a command line
    ///
    /// Parser would still fail if value is present but failure comes from some transformation
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn number() -> impl Parser<u32> {
    ///     short('n')
    ///         .argument::<u32>("NUM")
    ///         .fallback(42)
    /// }
    /// ```
    ///
    /// # Derive usage
    /// Expression in parens should have the right type, this example uses `u32` literal,
    /// but it can also be your own type if that's what you are parsing, it can also be a function
    /// call.
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///    #[bpaf(short, argument("NUM"), fallback(42))]
    ///    number: u32
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app -n 100
    /// // 10
    /// $ app
    /// // 42
    /// $ app -n pi
    /// // fails with "Couldn't parse "pi": invalid numeric literal"
    /// ```
    ///
    /// # See also
    /// [`fallback_with`](Parser::fallback_with) would allow to try to fallback to a value that
    /// comes from a failing computation such as reading a file.
    #[must_use]
    fn fallback(self, value: T) -> ParseFallback<Self, T>
    where
        Self: Sized + Parser<T>,
    {
        ParseFallback { inner: self, value }
    }
    // }}}

    // {{{ fallback_with
    /// Use value produced by this function as default if value isn't present
    ///
    /// Would still fail if value is present but failure comes from some earlier transformation
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn username() -> impl Parser<String> {
    ///     long("user")
    ///         .argument::<String>("USER")
    ///         .fallback_with::<_, Box<dyn std::error::Error>>(||{
    ///             let output = std::process::Command::new("whoami")
    ///                 .stdout(std::process::Stdio::piped())
    ///                 .spawn()?
    ///                 .wait_with_output()?
    ///                 .stdout;
    ///             Ok(std::str::from_utf8(&output)?.to_owned())
    ///         })
    /// }
    /// ```
    ///
    /// # Derive usage
    /// ```rust
    /// # use bpaf::*;
    /// fn get_current_user() -> Result<String, Box<dyn std::error::Error>> {
    ///     let output = std::process::Command::new("whoami")
    ///         .stdout(std::process::Stdio::piped())
    ///         .spawn()?
    ///         .wait_with_output()?
    ///         .stdout;
    ///     Ok(std::str::from_utf8(&output)?.to_owned())
    /// }
    ///
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(long, argument("USER"), fallback_with(get_current_user))]
    ///     user: String,
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app --user bobert
    /// // "bobert"
    /// $ app
    /// // "pacak"
    /// ```
    ///
    /// # See also
    /// [`fallback`](Parser::fallback) implements similar logic expect that failures
    /// aren't expected.
    #[must_use]
    fn fallback_with<F, E>(self, fallback: F) -> ParseFallbackWith<T, Self, F, E>
    where
        Self: Sized + Parser<T>,
        F: Fn() -> Result<T, E>,
        E: ToString,
    {
        ParseFallbackWith {
            inner: self,
            inner_res: PhantomData,
            fallback,
            err: PhantomData,
        }
    }
    // }}}

    // {{{ or_else
    /// If first parser fails - try the second one
    ///
    /// For parser to succeed eiter of the components needs to succeed. If both succeed - `bpaf`
    /// would use output from one that consumed the left most value. The second flag on the command
    /// line remains unconsumed by `or_else`.
    ///
    /// # Combinatoric usage:
    /// There's two ways to write this combinator with identical results:
    /// ```rust
    /// # use bpaf::*;
    /// fn a() -> impl Parser<u32> {
    ///     short('a').argument::<u32>("NUM")
    /// }
    ///
    /// fn b() -> impl Parser<u32> {
    ///     short('b').argument::<u32>("NUM")
    /// }
    ///
    /// fn a_or_b_comb() -> impl Parser<u32> {
    ///     construct!([a(), b()])
    /// }
    ///
    /// fn a_or_b_comb2() -> impl Parser<u32> {
    ///     a().or_else(b())
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app -a 12 -b 3
    /// // 12
    /// $ app -b 3 -a 12
    /// // 3
    /// $ app -b 13
    /// // 13
    /// $ app
    /// // fails asking for either -a NUM or -b NUM
    /// ```
    ///
    /// # Derive usage:
    ///
    /// `bpaf_derive` translates enum into alternative combinations, different shapes of variants
    /// produce different results.
    ///
    ///
    /// ```bpaf
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// enum Flag {
    ///     A { a: u32 }
    ///     B { b: u32 }
    /// }
    /// ```
    ///
    /// ```console
    /// $ app -a 12 -b 3
    /// // Flag::A { a: 12 }
    /// $ app -b 3 -a 12
    /// // Flag::B { b: 3 }
    /// $ app -b 3
    /// // Flag::B { b: 3 }
    /// $ app
    /// // fails asking for either -a NUM or -b NUM
    /// ```
    ///
    /// # Performance
    ///
    /// `bpaf` tries to evaluate both branches regardless of the successes to produce a
    /// better error message for combinations of mutually exclusive parsers:
    /// Suppose program accepts one of two mutually exclusive switches `-a` and `-b`
    /// and both are present error message should point at the second flag
    #[doc(hidden)]
    #[deprecated(
        since = "0.5.0",
        note = "instead of a.or_else(b) you should use construct!([a, b])"
    )]
    fn or_else<P>(self, alt: P) -> ParseOrElse<Self, P>
    where
        Self: Sized + Parser<T>,
        P: Sized + Parser<T>,
    {
        ParseOrElse {
            this: self,
            that: alt,
        }
    }
    // }}}

    // misc
    // {{{ hide
    /// Ignore this parser during any sort of help generation
    ///
    /// Best used for optional parsers or parsers with a defined fallback, usually for implementing
    /// backward compatibility or hidden aliases
    ///
    /// # Combinatoric usage
    ///
    /// ```rust
    /// # use bpaf::*;
    /// /// bpaf would accept both `-W` and `-H` flags, but the help message
    /// /// would contain only `-H`
    /// fn rectangle() -> impl Parser<(u32, u32)> {
    ///     let width = short('W')
    ///         .argument::<u32>("PX")
    ///         .fallback(10)
    ///         .hide();
    ///     let height = short('H')
    ///         .argument::<u32>("PX")
    ///         .fallback(10)
    ///         .hide();
    ///     construct!(width, height)
    /// }
    /// ```
    /// # Example
    /// ```console
    /// $ app -W 12 -H 15
    /// // (12, 15)
    /// $ app -H 333
    /// // (10, 333)
    /// $ app --help
    /// // contains -H but not -W
    /// ```
    ///
    /// # Derive usage
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Rectangle {
    ///     #[bpaf(short('W'), argument("PX"), fallback(10), hide)]
    ///     width: u32,
    ///     #[bpaf(short('H'), argument("PX"))]
    ///     height: u32,
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app -W 12 -H 15
    /// // Rectangle { width: 12, height: 15 }
    /// $ app -H 333
    /// // Rectangle { width: 10, height: 333 }
    /// $ app --help
    /// // contains -H but not -W
    /// ```
    fn hide(self) -> ParseHide<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseHide { inner: self }
    }
    // }}}

    // {{{ group_help
    /// Attach help message to a complex parser
    ///
    /// `bpaf` inserts the group help message before the block with all the fields
    /// from the inner parser and an empty line after the block.
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn rectangle() -> impl Parser<(u32, u32)> {
    ///     let width = short('w')
    ///         .argument::<u32>("PX");
    ///     let height = short('h')
    ///         .argument::<u32>("PX");
    ///     construct!(width, height)
    ///         .group_help("Takes a rectangle")
    /// }
    /// ```
    /// # Example
    /// ```console
    /// $ app --help
    /// <skip>
    ///             Takes a rectangle
    ///    -w <PX>  Width of the rectangle
    ///    -h <PX>  Height of the rectangle
    ///
    /// <skip>
    /// ```
    ///
    /// # Derive usage
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Rectangle {
    ///     width: u32,
    ///     height: u32,
    /// }
    ///
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(external, group_help("Takes a rectangle"))]
    ///     rectangle: Rectangle
    /// }
    /// ```
    fn group_help(self, message: &'static str) -> ParseGroupHelp<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseGroupHelp {
            inner: self,
            message,
        }
    }
    // }}}

    // {{{ comp
    /// Dynamic shell completion
    ///
    /// Allows to generate autocompletion information for shell. Completer places generated input
    /// in place of metavar placeholders, so running `completer` on something that doesn't have a
    /// [`positional`] or an [`argument`](NamedArg::argument) (or their `_os` variants) doesn't make
    /// much sense.
    ///
    /// Takes a function as a parameter that tries to complete partial input to a full one with
    /// optional description. `bpaf` would substitute current positional item or an argument an empty
    /// string if a value isn't available yet so it's best to run `complete` where parsing can't fail:
    /// right after [`argument`](NamedArg::argument) or [`positional`], but this isn't enforced.
    ///
    /// `bpaf` doesn't support generating [`OsString`](std::ffi::OsString) completions: `bpaf` must
    /// print completions to console and for non-string values it's not possible (accurately).
    ///
    /// **Using this function requires enabling `"autocomplete"` feature, not enabled by default**.
    ///
    /// # Example
    /// ```console
    /// $ app --name L<TAB>
    /// $ app --name Lupusregina _
    /// ```
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn completer(input: &String) -> Vec<(&'static str, Option<&'static str>)> {
    ///     let names = ["Yuri", "Lupusregina", "Solution", "Shizu", "Entoma"];
    ///     names
    ///         .iter()
    ///         .filter(|name| name.starts_with(input))
    ///         .map(|name| (*name, None))
    ///         .collect::<Vec<_>>()
    /// }
    ///
    /// fn name() -> impl Parser<String> {
    ///     short('n')
    ///         .long("name")
    ///         .help("Specify character's name")
    ///         .argument::<String>("Name")
    ///         .complete(completer)
    /// }
    /// ```
    ///
    /// # Derive usage
    /// ```rust
    /// # use bpaf::*;
    /// fn completer(input: &String) -> Vec<(&'static str, Option<&'static str>)> {
    ///     let names = ["Yuri", "Lupusregina", "Solution", "Shizu", "Entoma"];
    ///     names
    ///         .iter()
    ///         .filter(|name| name.starts_with(input))
    ///         .map(|name| (*name, None))
    ///         .collect::<Vec<_>>()
    /// }
    ///
    /// #[derive(Debug, Clone, Bpaf)]
    /// struct Options {
    ///     #[bpaf(argument("NAME"), complete(completer))]
    ///     name: String,
    /// }
    /// ```
    #[cfg(feature = "autocomplete")]
    fn complete<M, F>(self, op: F) -> ParseComp<Self, F>
    where
        M: Into<String>,
        F: Fn(&T) -> Vec<(M, Option<M>)>,
        Self: Sized + Parser<T>,
    {
        ParseComp { inner: self, op }
    }
    // }}}

    // {{{ complete_style
    /// Add extra annotations to completion information
    ///
    /// Not all information is gets supported by all the shells
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn opts() -> impl Parser<(bool, bool)> {
    ///     let a = short('a').switch();
    ///     let b = short('b').switch();
    ///     let c = short('c').switch();
    ///     let d = short('d').switch();
    ///     let ab = construct!(a, b).complete_style(CompleteDecor::VisibleGroup("a and b"));
    ///     let cd = construct!(c, d).complete_style(CompleteDecor::VisibleGroup("c and d"));
    ///     construct!([ab, cd])
    /// }
    #[cfg(feature = "autocomplete")]
    fn complete_style(self, style: CompleteDecor) -> ParseCompStyle<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseCompStyle { inner: self, style }
    }
    // }}}

    // {{{ adjacent
    /// Automagically restrict the inner parser scope to accept adjacent values only
    ///
    /// `adjacent` can solve surprisingly wide variety of problems: sequential command chaining,
    /// multi-value arguments, option-structs to name a few. If you want to run a parser on a
    /// sequential subset of arguments - `adjacent` might be able to help you. Check the examples
    /// for better intuition.
    ///
    /// # Multi-value arguments
    ///
    /// Parsing things like `--foo ARG1 ARG2 ARG3`
    #[doc = include_str!("docs/adjacent_0.md")]
    ///
    /// # Structure groups
    ///
    /// Parsing things like `--foo --foo-1 ARG1 --foo-2 ARG2 --foo-3 ARG3`
    #[doc = include_str!("docs/adjacent_1.md")]
    ///
    /// # Chaining commands
    ///
    /// Parsing things like `cmd1 --arg1 cmd2 --arg2 --arg3 cmd3 --flag`
    ///
    #[doc = include_str!("docs/adjacent_2.md")]
    ///
    /// # Start and end markers
    ///
    /// Parsing things like `find . --exec foo {} -bar ; --more`
    ///
    #[doc = include_str!("docs/adjacent_3.md")]
    ///
    /// # Multi-value arguments with optional flags
    ///
    /// Parsing things like `--foo ARG1 --flag --inner ARG2`
    ///
    /// So you can parse things while parsing things. Not sure why you might need this, but you can
    /// :)
    ///
    #[doc = include_str!("docs/adjacent_4.md")]
    ///
    /// # Performance and other considerations
    ///
    /// `bpaf` can run adjacently restricted parsers multiple times to refine the guesses. It's
    /// best not to have complex inter-fields verification since they might trip up the detection
    /// logic: instead of destricting, for example "sum of two fields to be 5 or greater" *inside* the
    /// `adjacent` parser, you can restrict it *outside*, once `adjacent` done the parsing.
    ///
    /// `adjacent` is available on a trait for better discoverability, it doesn't make much sense to
    /// use it on something other than [`command`](OptionParser::command) or [`construct!`] encasing
    /// several fields.
    ///
    /// There's also similar method [`adjacent`](crate::parsers::ParseArgument) that allows to restrict argument
    /// parser to work only for arguments where both key and a value are in the same shell word:
    /// `-f=bar` or `-fbar`, but not `-f bar`.
    #[must_use]
    fn adjacent(self) -> ParseAdjacent<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseAdjacent { inner: self }
    }
    // }}}

    /// Parse anywhere
    ///
    /// Most generic escape hatch available, in combination with [`any`] allows to parse anything
    /// anywhere, works by repeatedly trying to run the inner parser on each subsequent context.
    /// Can be expensive performance wise especially if parser contains complex logic.
    ///
    #[doc = include_str!("docs/anywhere.md")]
    #[must_use]
    fn anywhere(self) -> ParseAnywhere<Self>
    where
        Self: Sized + Parser<T>,
    {
        ParseAnywhere { inner: self }
    }

    // consume
    // {{{ to_options
    /// Transform `Parser` into [`OptionParser`] to attach metadata and run
    ///
    /// # Combinatoric usage
    /// ```rust
    /// # use bpaf::*;
    /// fn parser() -> impl Parser<u32> {
    ///     short('i')
    ///         .argument::<u32>("ARG")
    /// }
    ///
    /// fn option_parser() -> OptionParser<u32> {
    ///     parser()
    ///         .to_options()
    ///         .version("3.1415")
    ///         .descr("This is a description")
    /// }
    /// ```
    ///
    /// See [`OptionParser`] for more methods available after conversion.
    ///
    /// # Derive usage
    /// Add a top level `options` annotation to generate [`OptionParser`] instead of default
    /// [`Parser`].
    ///
    /// In addition to `options` annotation you can also specify either `version` or
    /// `version(value)` annotation. Former uses version from `cargo`, later uses the
    /// specified value which should be an expression of type `&'static str`, see
    /// [`version`](OptionParser::version).
    ///
    /// ```rust
    /// # use bpaf::*;
    /// #[derive(Debug, Clone, Bpaf)]
    /// #[bpaf(options, version("3.1415"))]
    /// /// This is a description
    /// struct Options {
    ///    verbose: bool,
    /// }
    /// ```
    ///
    /// # Example
    /// ```console
    /// $ app --version
    /// // Version: 3.1415
    /// $ app --help
    /// <skip>
    /// This is a description
    /// <skip>
    /// ```
    fn to_options(self) -> OptionParser<T>
    where
        Self: Sized + Parser<T> + 'static,
    {
        OptionParser {
            info: info::Info::default(),
            inner_type: PhantomData,
            inner: Box::new(self),
        }
    }
    // }}}

    #[doc(hidden)]
    #[deprecated = "You should finalize the parser first: see Parser::to_options"]
    fn run(self) -> T
    where
        Self: Sized + Parser<T> + 'static,
    {
        self.to_options().run()
    }
}

#[non_exhaustive]
/// Various complete options decorations
///
/// Somewhat work in progress, only makes a difference in zsh
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn pair() -> impl Parser<(bool, bool)> {
///     let a = short('a').switch();
///     let b = short('b').switch();
///     construct!(a, b)
///         .complete_style(CompleteDecor::VisibleGroup("a and b"))
/// }
/// ```
///
/// # Derive usage
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// #[bpaf(complete_style(CompleteDecor::VisibleGroup("a and b")))]
/// struct Options {
///     a: bool,
///     b: bool,
/// }
/// ```
///
#[derive(Debug, Clone, Copy)]
#[cfg(feature = "autocomplete")]
pub enum CompleteDecor {
    /// Group items according to this group
    HiddenGroup(&'static str),
    /// Group items according to this group but also show the group name
    VisibleGroup(&'static str),
}

/// Wrap a value into a `Parser`
///
/// This parser produces `T` without consuming anything from the command line, can be useful
/// with [`construct!`]. As with any parsers `T` should be `Clone` and `Debug`.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn pair() -> impl Parser<(bool, u32)> {
///     let a = long("flag-a").switch();
///     let b = pure(42u32);
///     construct!(a, b)
/// }
/// ```
#[must_use]
pub fn pure<T>(val: T) -> ParsePure<T> {
    ParsePure(val)
}

/// Fail with a fixed error message
///
/// This parser produces `T` of any type but instead of producing it when asked - it fails
/// with a custom error message. Can be useful for creating custom logic
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn must_agree() -> impl Parser<()> {
///     let a = long("accept").req_flag(());
///     let no_a = fail("You must accept the license agreement with --agree before proceeding");
///     construct!([a, no_a])
/// }
/// ```
///
/// # Example
/// ```console
/// $ app
/// // exits with "You must accept the license agreement with --agree before proceeding"
/// $ app --agree
/// // succeeds
/// ```
#[must_use]
pub fn fail<T>(msg: &'static str) -> ParseFail<T> {
    ParseFail {
        field1: msg,
        field2: PhantomData,
    }
}

/// Unsuccessful command line parsing outcome, use it for unit tests
///
/// Useful for unit testing for user parsers, consume it with
/// [`ParseFailure::unwrap_stdout`] and [`ParseFailure::unwrap_stdout`]
#[derive(Clone, Debug)]
pub enum ParseFailure {
    /// Print this to stdout and exit with success code
    Stdout(String),
    /// Print this to stderr and exit with failure code
    Stderr(String),
}

impl ParseFailure {
    /// Returns the contained `stderr` values - for unit tests
    ///
    /// # Panics
    ///
    /// Panics if failure contains `stdout`
    #[allow(clippy::must_use_candidate)]
    #[track_caller]
    pub fn unwrap_stderr(self) -> String {
        match self {
            Self::Stderr(err) => err,
            Self::Stdout(_) => {
                panic!("not an stderr: {:?}", self)
            }
        }
    }

    /// Returns the contained `stdout` values - for unit tests
    ///
    /// # Panics
    ///
    /// Panics if failure contains `stderr`
    #[allow(clippy::must_use_candidate)]
    #[track_caller]
    pub fn unwrap_stdout(self) -> String {
        match self {
            Self::Stdout(err) => err,
            Self::Stderr(_) => {
                panic!("not an stdout: {:?}", self)
            }
        }
    }
}

/// Strip a command name if present at the front when used as a `cargo` command
///
/// See batteries::cargo_helper
#[must_use]
#[doc(hidden)]
pub fn cargo_helper<P, T>(cmd: &'static str, parser: P) -> impl Parser<T>
where
    T: 'static,
    P: Parser<T>,
{
    let skip = positional::<String>("cmd")
        .guard(move |s| s == cmd, "")
        .optional()
        .catch()
        .hide();
    construct!(skip, parser).map(|x| x.1)
}