getargs-derive 0.1.0

Clap-style #[derive] command-line argument parser for no_std and embedded Rust: zero allocation, compile-time help, subcommands. Built on getargs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
use crate::{ArgInfo, Error};
use core::cell::Cell;

pub use crate::input::{
    Arg, Input, arg, bytes, opt, text, unexpected_argument, unknown_subcommand, unnamed,
};
#[cfg(feature = "std")]
pub use crate::os::{OsArg, args_os, os_str, path};
#[cfg(feature = "std")]
pub use std::ffi::OsStr;

/// One argument of the generated help: its labels, descriptions and placement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HelpEntry {
    /// The label of the help line, e.g. `<INPUT>` or `-o, --output <OUTPUT>`.
    pub label: &'static str,
    /// The label in the usage line for a positional argument, e.g. `[-- <REST>]`, empty for options.
    pub usage: &'static str,
    /// Whether the argument is positional.
    pub positional: bool,
    /// Whether the argument is hidden from the help.
    pub hidden: bool,
    /// Whether the argument is a `global` option, also listed in the help of subcommands.
    pub global: bool,
    /// The custom section of the argument, empty for the default `Arguments` or `Options` section.
    pub heading: &'static str,
    /// The explicit `display_order`, when `ordered` is set.
    pub order: usize,
    /// Whether the argument has an explicit `display_order`.
    pub ordered: bool,
    /// The description in the short help.
    pub short: &'static str,
    /// Whether the short description can be wrapped.
    pub short_wraps: bool,
    /// The description in the long help.
    pub long: &'static str,
    /// Whether the long description can be wrapped.
    pub long_wraps: bool,
}

impl HelpEntry {
    /// An empty entry, used to fill arrays before they are written.
    pub const EMPTY: HelpEntry = HelpEntry {
        label: "",
        usage: "",
        positional: false,
        hidden: true,
        global: false,
        heading: "",
        order: 0,
        ordered: false,
        short: "",
        short_wraps: true,
        long: "",
        long_wraps: true,
    };

    /// A generated flag of the parent, such as `-h, --help`.
    pub const fn reserved(label: &'static str, short: &'static str, long: &'static str) -> Self {
        HelpEntry {
            label,
            short,
            long,
            hidden: false,
            ..HelpEntry::EMPTY
        }
    }
}

/// Parsing state shared by a struct with the structs it flattens and its subcommands.
#[derive(Debug, Clone, Copy)]
pub struct Context<'a, 'r> {
    /// The last raw argument, used to recognise negative numbers.
    pub raw: Option<&'r Cell<Option<&'a [u8]>>>,
    /// Whether a `last` positional exists, so that arguments after `--` skip the other positionals.
    pub last: bool,
    /// Whether every option and positional accepts negative numbers.
    pub negative_numbers: bool,
    /// Whether a positional argument before the struct is still missing.
    pub blocked: bool,
    /// The short and long help of every command of the parsed command tree, in pre-order.
    pub helps: &'static [&'static str],
    /// The index of the command being parsed in the command tree.
    pub node: usize,
}

impl<'a, 'r> Context<'a, 'r> {
    /// The context of the struct being parsed.
    pub const fn new(raw: Option<&'r Cell<Option<&'a [u8]>>>) -> Self {
        Context {
            raw,
            last: false,
            negative_numbers: false,
            blocked: false,
            helps: &[],
            node: 0,
        }
    }

    /// The context of a struct with subcommands, whose command tree has the help texts `helps`.
    pub const fn with_helps(self, helps: &'static [&'static str]) -> Self {
        Context { helps, ..self }
    }

    /// The context of a flattened struct.
    pub const fn child(self, last: bool, negative_numbers: bool, blocked: bool) -> Self {
        Context {
            last: self.last || last,
            negative_numbers: self.negative_numbers || negative_numbers,
            blocked: self.blocked || blocked,
            ..self
        }
    }

    /// The context of the subcommand at index `node` of the command tree.
    pub const fn command(self, node: usize) -> Self {
        Context {
            raw: self.raw,
            last: false,
            negative_numbers: false,
            blocked: false,
            helps: self.helps,
            node,
        }
    }

    /// The short or long help of the command being parsed.
    pub fn help(&self, long: bool) -> &'static str {
        let index = 2 * self.node + usize::from(long);
        self.helps.get(index).copied().unwrap_or_default()
    }
}

/// Offers an argument to the `global` options of the parents of a subcommand. Returns `Ok(true)`
/// when one of them consumed it.
pub type Globals<'g, 'a, A, I> =
    dyn FnMut(Arg<'a, A>, &mut getargs::Options<A, I>) -> Result<bool, Error<'a>> + 'g;

/// The [`Globals`] of a command without parents.
pub fn no_globals<'a, A: Input<'a>, I: Iterator<Item = A>>(
    _argument: Arg<'a, A>,
    _options: &mut getargs::Options<A, I>,
) -> Result<bool, Error<'a>> {
    Ok(false)
}

/// Per-struct parsing API generated by `#[derive(GetArgs)]`, used by the parser of the struct itself
/// and of the structs that flatten it with `#[command(flatten)]`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not derive `GetArgs`",
    label = "flattened fields and newtype subcommand variants must wrap a type deriving `GetArgs`"
)]
pub trait Args<'a>: Sized {
    /// Values collected while parsing, before required arguments and relations are checked.
    type State;

    /// Help entries of the arguments, flattened structs included, in field order.
    const ENTRIES: &'static [HelpEntry];
    /// Short option names and aliases, flattened structs included.
    const SHORTS: &'static [char];
    /// Long option names and aliases, flattened structs included.
    const LONGS: &'static [&'static str];
    /// Whether each positional argument is optional, flattened structs included, in field order.
    const POSITIONALS: &'static [bool];
    /// Whether a positional argument uses `last`, flattened structs included.
    const LAST: bool;
    /// Whether an argument falls back to an environment variable, flattened structs included.
    type Env: EnvFlag;
    /// Whether a visible argument has a long help text, flattened structs included.
    const HAS_LONG_HELP: bool;
    /// Public metadata of the arguments, flattened structs included, in field order.
    const ARGS: &'static [ArgInfo];
    /// [`ARGS`](Self::ARGS) followed by the generated flags of the struct itself.
    const COMMAND_ARGS: &'static [ArgInfo];
    /// The help of the struct when it is used as a command or a subcommand.
    const COMMAND: CommandHelp;

    /// Returns the state before any argument is parsed.
    fn init() -> Self::State;

    /// Whether every positional argument, flattened structs included, has a value.
    fn filled(state: &Self::State) -> bool;

    /// Offers one argument to the struct. Returns `Ok(true)` when it was consumed, `Ok(false)`
    /// when the struct does not handle it.
    fn try_arg<A: Input<'a>, I: Iterator<Item = A>>(
        state: &mut Self::State,
        argument: Arg<'a, A>,
        options: &mut getargs::Options<A, I>,
        context: Context<'a, '_>,
        globals: &mut Globals<'_, 'a, A, I>,
    ) -> Result<bool, Error<'a>>;

    /// Offers one argument given after a subcommand to the `global` options of the struct,
    /// flattened structs included. Returns `Ok(true)` when it was consumed.
    fn try_global<A: Input<'a>, I: Iterator<Item = A>>(
        state: &mut Self::State,
        argument: Arg<'a, A>,
        options: &mut getargs::Options<A, I>,
        context: Context<'a, '_>,
    ) -> Result<bool, Error<'a>>;

    /// Checks relations, reads environment variables, applies defaults and builds the struct.
    fn finish<E: FnMut(&str) -> Option<&'a str>>(
        state: Self::State,
        env: &mut E,
    ) -> Result<Self, Error<'a>>;
}

/// Per-enum parsing API generated by `#[derive(Subcommand)]`, used by the struct holding the
/// `#[command(subcommand)]` field.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be used as a subcommand because it does not derive `Subcommand`",
    label = "subcommand field type must derive `Subcommand`"
)]
pub trait Subcommand<'a>: Sized {
    /// The parsed arguments of the selected subcommand, before they are checked.
    type State;
    /// Whether a subcommand reads environment variables.
    type Env: EnvFlag;

    /// The subcommands, in variant order.
    const COMMANDS: &'static [CommandEntry];
    /// The names and visible aliases of the visible subcommands, used for suggestions.
    const NAMES: &'static [&'static str];
    /// The names of the visible subcommands, reported when a required subcommand is missing.
    const VISIBLE: &'static [&'static str];
    /// The public metadata of the subcommands, in variant order.
    const INFOS: &'static [crate::CommandInfo];

    /// Parses the rest of the command line as the subcommand called `name`. Returns `Ok(None)`
    /// when no subcommand has this name or alias.
    fn try_command<A: Input<'a>, I: Iterator<Item = A>>(
        name: &'a str,
        options: &mut getargs::Options<A, I>,
        context: Context<'a, '_>,
        globals: &mut Globals<'_, 'a, A, I>,
    ) -> Result<Option<Self::State>, Error<'a>>;

    /// Checks the arguments of the selected subcommand and builds the variant.
    fn finish<E: FnMut(&str) -> Option<&'a str>>(
        state: Self::State,
        env: &mut E,
    ) -> Result<Self, Error<'a>>;
}

/// The help of a struct deriving `GetArgs`, from its own `#[command(...)]` attributes.
#[derive(Debug, Clone, Copy)]
pub struct CommandHelp {
    /// The command name, used in the usage line when the struct is parsed on its own.
    pub name: &'static str,
    /// The `before_help` text, empty when there is none.
    pub before_help: &'static str,
    /// The `about` text, empty when there is none.
    pub about: &'static str,
    /// The `long_about` text, empty when there is none.
    pub long_about: &'static str,
    /// The `after_help` text, empty when there is none.
    pub after_help: &'static str,
    /// The width to wrap at, or `0` not to wrap.
    pub term_width: usize,
    /// Whether the struct has the generated `-h`/`--help` flag.
    pub help_flag: bool,
    /// Whether the struct has the generated `-V`/`--version` flag.
    pub version: bool,
    /// The help entries of the arguments, flattened structs included.
    pub entries: &'static [HelpEntry],
    /// Whether a visible argument has a long help text.
    pub has_long_help: bool,
    /// The short option names and aliases.
    pub shorts: &'static [char],
    /// The long option names and aliases.
    pub longs: &'static [&'static str],
    /// The subcommands, empty when the struct has no `#[command(subcommand)]` field.
    pub commands: &'static [CommandEntry],
    /// Whether a subcommand must be given.
    pub subcommand_required: bool,
    /// The public metadata of the subcommands.
    pub infos: &'static [crate::CommandInfo],
}

/// The public metadata of a subcommand whose arguments are `args`, the generated help flag
/// included, and whose struct has the help `command`.
pub const fn subcommand_info(
    name: &'static str,
    about: &'static str,
    long_about: &'static str,
    args: &'static [ArgInfo],
    command: &CommandHelp,
) -> crate::CommandInfo {
    crate::CommandInfo::new(name)
        .about(about)
        .long_about(long_about)
        .args(args)
        .commands(command.infos)
        .subcommand_required(command.subcommand_required)
}

/// One subcommand of an enum deriving `Subcommand`.
#[derive(Debug, Clone, Copy)]
pub struct CommandEntry {
    /// The name of the subcommand.
    pub name: &'static str,
    /// The description in the `Commands` section, visible aliases included.
    pub description: &'static str,
    /// The `about` text of the subcommand help.
    pub about: &'static str,
    /// The `long_about` text of the subcommand help.
    pub long_about: &'static str,
    /// Whether the subcommand is hidden from the `Commands` section.
    pub hidden: bool,
    /// The help of the struct holding the arguments of the subcommand.
    pub command: &'static CommandHelp,
}

/// The separator between the description of a subcommand and its visible aliases.
pub const fn separator(about: &str, aliases: &str) -> &'static str {
    if about.is_empty() || aliases.is_empty() {
        ""
    } else {
        " "
    }
}

/// Number of commands in the tree rooted at `command`, itself included.
pub const fn nodes(command: &CommandHelp) -> usize {
    let mut total = 1;
    let mut index = 0;
    while index < command.commands.len() {
        total += nodes(command.commands[index].command);
        index += 1;
    }
    total
}

/// Index in the command tree of the subcommand `index` of `commands`, whose parent is at `parent`.
pub const fn node(commands: &[CommandEntry], parent: usize, index: usize) -> usize {
    let mut node = parent + 1;
    let mut before = 0;
    while before < index {
        node += nodes(commands[before].command);
        before += 1;
    }
    node
}

/// Whether a subcommand in `commands`, nested ones included, uses the short option `short`.
pub const fn commands_use_short(commands: &[CommandEntry], short: char) -> bool {
    let mut index = 0;
    while index < commands.len() {
        let command = commands[index].command;
        if contains_short(command.shorts, short)
            || (command.help_flag && short == 'h')
            || commands_use_short(command.commands, short)
        {
            return true;
        }
        index += 1;
    }
    false
}

/// Whether a subcommand in `commands`, nested ones included, uses the long option `long`.
pub const fn commands_use_long(commands: &[CommandEntry], long: &str) -> bool {
    let mut index = 0;
    while index < commands.len() {
        let command = commands[index].command;
        if contains_long(command.longs, long)
            || (command.help_flag && str_eq(long, "help"))
            || commands_use_long(command.commands, long)
        {
            return true;
        }
        index += 1;
    }
    false
}

/// Reads the next argument, converting the errors of `getargs`.
pub fn next_arg<'a, A: Input<'a>, I: Iterator<Item = A>>(
    options: &mut getargs::Options<A, I>,
) -> Result<Option<Arg<'a, A>>, Error<'a>> {
    match options.next_arg() {
        Ok(Some(argument)) => arg(argument).map(Some),
        Ok(None) => Ok(None),
        Err(getargs::Error::DoesNotRequireValue(option)) => {
            Err(Error::UnexpectedValue(opt(option)?))
        }
        Err(_) => Err(Error::InvalidArguments),
    }
}

/// The error for an argument that no field consumed, suggesting one of `longs` for a long option.
pub fn unexpected<'a, A: Input<'a>>(argument: Arg<'a, A>, longs: &[&[&'static str]]) -> Error<'a> {
    match argument {
        Arg::Positional(value) => unexpected_argument(value),
        Arg::Short(short) => Error::UnknownOption {
            option: crate::Opt::Short(short),
            suggestion: None,
        },
        Arg::Long(long) => Error::UnknownOption {
            option: crate::Opt::Long(long),
            suggestion: crate::suggest::suggest(long, longs),
        },
    }
}

/// Parses the rest of the command line as the arguments of the subcommand `T`, handling its help
/// flag and offering the arguments it does not consume to the `global` options of its parents.
pub fn command<'a, T: Args<'a>, A: Input<'a>, I: Iterator<Item = A>>(
    options: &mut getargs::Options<A, I>,
    context: Context<'a, '_>,
    globals: &mut Globals<'_, 'a, A, I>,
) -> Result<T::State, Error<'a>> {
    let mut state = T::init();
    while let Some(argument) = next_arg(options)? {
        if T::COMMAND.help_flag {
            match argument {
                Arg::Short('h') => return Err(Error::Help(context.help(false))),
                Arg::Long("help") => return Err(Error::Help(context.help(true))),
                _ => {}
            }
        }
        if T::try_arg(&mut state, argument, options, context, globals)? {
            continue;
        }
        if globals(argument, options)? {
            continue;
        }
        let reserved: &[&'static str] = if T::COMMAND.help_flag { &["help"] } else { &[] };
        return Err(unexpected(argument, &[T::LONGS, reserved]));
    }
    Ok(state)
}

/// Type-level flag telling whether a struct reads environment variables.
pub trait EnvFlag {
    /// `Self` or `Other`.
    type Or<Other: EnvFlag>: EnvFlag;
}

/// The struct reads environment variables.
pub struct UsesEnv;

/// The struct does not read environment variables.
pub struct NoEnv;

impl EnvFlag for UsesEnv {
    type Or<Other: EnvFlag> = UsesEnv;
}

impl EnvFlag for NoEnv {
    type Or<Other: EnvFlag> = Other;
}

/// Implemented when `parse` and `from_args` can read the environment variables of a struct whose
/// flattened structs and subcommands have the [`EnvFlag`] `F`.
#[diagnostic::on_unimplemented(
    message = "a flattened struct or a subcommand reads environment variables, which requires the `std` feature of `getargs-derive`",
    label = "`parse` and `from_args` read the process environment",
    note = "enable the `std` feature of `getargs-derive`, or call `parse_with_env` or `from_args_with_env` with a lookup function"
)]
pub trait EnvSupport<F> {}

impl<T: ?Sized> EnvSupport<NoEnv> for T {}

#[cfg(feature = "std")]
impl<T: ?Sized> EnvSupport<UsesEnv> for T {}

/// An environment lookup that finds no variable.
pub fn no_env<'a>(_name: &str) -> Option<&'a str> {
    None
}

/// The description of the generated help flag.
pub const fn help_flag(long: bool, has_long_help: bool) -> &'static str {
    match (long, has_long_help) {
        (_, false) => "Print help",
        (false, true) => "Print help (see more with '--help')",
        (true, true) => "Print help (see a summary with '-h')",
    }
}

/// Total number of items in `parts`.
pub const fn count<T>(parts: &[&[T]]) -> usize {
    let mut total = 0;
    let mut index = 0;
    while index < parts.len() {
        total += parts[index].len();
        index += 1;
    }
    total
}

/// Concatenates `parts` into an array of exactly [`count`] items.
pub const fn concat<T: Copy, const N: usize>(parts: &[&[T]], fill: T) -> [T; N] {
    let mut output = [fill; N];
    let mut position = 0;
    let mut part = 0;
    while part < parts.len() {
        let mut index = 0;
        while index < parts[part].len() {
            output[position] = parts[part][index];
            position += 1;
            index += 1;
        }
        part += 1;
    }
    assert!(position == N, "concatenated length mismatch");
    output
}

const fn str_eq(first: &str, second: &str) -> bool {
    let first = first.as_bytes();
    let second = second.as_bytes();
    if first.len() != second.len() {
        return false;
    }
    let mut index = 0;
    while index < first.len() {
        if first[index] != second[index] {
            return false;
        }
        index += 1;
    }
    true
}

/// The generated `--help` flag.
pub const fn help_arg(has_long_help: bool) -> ArgInfo {
    ArgInfo::new("help", crate::ArgKind::Flag)
        .short('h')
        .long("help")
        .help(help_flag(false, has_long_help))
        .long_help(help_flag(true, has_long_help))
}

/// The generated `--version` flag.
pub const fn version_arg() -> ArgInfo {
    ArgInfo::new("version", crate::ArgKind::Flag)
        .short('V')
        .long("version")
        .help("Print version")
}

/// Whether `list` contains `short`.
pub const fn contains_short(list: &[char], short: char) -> bool {
    let mut index = 0;
    while index < list.len() {
        if list[index] == short {
            return true;
        }
        index += 1;
    }
    false
}

/// Whether `list` contains `long`.
pub const fn contains_long(list: &[&str], long: &str) -> bool {
    let mut index = 0;
    while index < list.len() {
        if str_eq(list[index], long) {
            return true;
        }
        index += 1;
    }
    false
}

/// Whether `first` and `second` share a short name.
pub const fn shares_short(first: &[char], second: &[char]) -> bool {
    let mut index = 0;
    while index < first.len() {
        if contains_short(second, first[index]) {
            return true;
        }
        index += 1;
    }
    false
}

/// Whether `first` and `second` share a long name.
pub const fn shares_long(first: &[&str], second: &[&str]) -> bool {
    let mut index = 0;
    while index < first.len() {
        if contains_long(second, first[index]) {
            return true;
        }
        index += 1;
    }
    false
}

/// Whether no required positional argument follows an optional one.
pub const fn positionals_ordered(parts: &[&[bool]]) -> bool {
    let mut seen_optional = false;
    let mut part = 0;
    while part < parts.len() {
        let mut index = 0;
        while index < parts[part].len() {
            if parts[part][index] {
                seen_optional = true;
            } else if seen_optional {
                return false;
            }
            index += 1;
        }
        part += 1;
    }
    true
}

const ARGUMENTS: &str = "Arguments";
const OPTIONS: &str = "Options";
const NEXT_LINE_INDENT: usize = 10;

/// Everything needed to render a help text whose arguments are only known as constants.
#[derive(Debug, Clone, Copy)]
pub struct Help<'h> {
    /// The text before the usage line arguments, ending with `Usage: ` and the command name.
    pub prefix: &'h str,
    /// The text after the last section.
    pub suffix: &'h str,
    /// The arguments, flattened structs included, in field order.
    pub entries: &'h [HelpEntry],
    /// The generated flags appended to the `Options` section.
    pub reserved: &'h [HelpEntry],
    /// Whether to render the long help.
    pub long: bool,
    /// The width to wrap at, or `0` not to wrap.
    pub term_width: usize,
}

const fn decode(bytes: &[u8], index: usize) -> (u32, usize) {
    let first = bytes[index] as u32;
    if first < 0x80 {
        (first, 1)
    } else if first < 0xE0 {
        (((first & 0x1F) << 6) | (bytes[index + 1] as u32 & 0x3F), 2)
    } else if first < 0xF0 {
        (
            ((first & 0x0F) << 12)
                | ((bytes[index + 1] as u32 & 0x3F) << 6)
                | (bytes[index + 2] as u32 & 0x3F),
            3,
        )
    } else {
        (
            ((first & 0x07) << 18)
                | ((bytes[index + 1] as u32 & 0x3F) << 12)
                | ((bytes[index + 2] as u32 & 0x3F) << 6)
                | (bytes[index + 3] as u32 & 0x3F),
            4,
        )
    }
}

const fn is_whitespace(code: u32) -> bool {
    matches!(
        code,
        0x09..=0x0D
            | 0x20
            | 0x85
            | 0xA0
            | 0x1680
            | 0x2000..=0x200A
            | 0x2028
            | 0x2029
            | 0x202F
            | 0x205F
            | 0x3000
    )
}

const fn char_count_range(text: &str, start: usize, end: usize) -> usize {
    let bytes = text.as_bytes();
    let mut count = 0;
    let mut index = start;
    while index < end {
        if bytes[index] & 0xC0 != 0x80 {
            count += 1;
        }
        index += 1;
    }
    count
}

const fn char_count(text: &str) -> usize {
    char_count_range(text, 0, text.len())
}

const fn line_end(text: &str, start: usize) -> usize {
    let bytes = text.as_bytes();
    let mut index = start;
    while index < bytes.len() && bytes[index] != b'\n' {
        index += 1;
    }
    index
}

const fn text_width(text: &str) -> usize {
    let bytes = text.as_bytes();
    let mut width = 0;
    let mut start = 0;
    while start < bytes.len() {
        let end = line_end(text, start);
        let mut visible = end;
        if visible > start && bytes[visible - 1] == b'\r' {
            visible -= 1;
        }
        let count = char_count_range(text, start, visible);
        if count > width {
            width = count;
        }
        start = end + 1;
    }
    width
}

struct Writer<'a> {
    output: &'a mut [u8],
    position: usize,
    marks: &'a mut [usize],
    mark: usize,
}

impl Writer<'_> {
    const fn range(&mut self, text: &str, start: usize, end: usize) {
        let bytes = text.as_bytes();
        let mut index = start;
        while index < end {
            if self.position < self.output.len() {
                self.output[self.position] = bytes[index];
            }
            self.position += 1;
            index += 1;
        }
    }

    const fn str(&mut self, text: &str) {
        self.range(text, 0, text.len());
    }

    const fn spaces(&mut self, count: usize) {
        let mut index = 0;
        while index < count {
            self.str(" ");
            index += 1;
        }
    }

    const fn wrap_line(
        &mut self,
        text: &str,
        start: usize,
        end: usize,
        width: usize,
        indent: usize,
    ) {
        let bytes = text.as_bytes();
        let mut body = start;
        while body < end {
            let (code, length) = decode(bytes, body);
            if !is_whitespace(code) {
                break;
            }
            body += length;
        }
        self.range(text, start, body);
        let mut current = char_count_range(text, start, body);
        let mut line_start = true;
        let mut index = body;
        while index < end {
            let (code, length) = decode(bytes, index);
            if is_whitespace(code) {
                index += length;
                continue;
            }
            let word = index;
            while index < end {
                let (code, length) = decode(bytes, index);
                if is_whitespace(code) {
                    break;
                }
                index += length;
            }
            let length = char_count_range(text, word, index);
            if !line_start && current + 1 + length > width {
                self.str("\n");
                self.spaces(indent);
                current = 0;
            } else if !line_start {
                self.str(" ");
                current += 1;
            }
            self.range(text, word, index);
            current += length;
            line_start = false;
        }
    }

    const fn paragraph(&mut self, text: &str, width: Option<usize>, indent: usize) {
        let bytes = text.as_bytes();
        let mut start = 0;
        loop {
            let end = line_end(text, start);
            if start > 0 {
                self.str("\n");
                if end > start {
                    self.spaces(indent);
                }
            }
            match width {
                Some(width) => {
                    let width = if width == 0 { 1 } else { width };
                    if char_count_range(text, start, end) <= width {
                        self.range(text, start, end);
                    } else {
                        self.wrap_line(text, start, end, width, indent);
                    }
                }
                None => self.range(text, start, end),
            }
            if end >= bytes.len() {
                break;
            }
            start = end + 1;
        }
    }

    const fn mark(&mut self) {
        let position = self.position;
        self.mark_at(position);
    }

    const fn mark_at(&mut self, position: usize) {
        if self.mark < self.marks.len() {
            self.marks[self.mark] = position;
        }
        self.mark += 1;
    }

    #[allow(clippy::too_many_arguments)]
    const fn item(
        &mut self,
        label: &str,
        description: &str,
        wraps: bool,
        long: bool,
        term_width: usize,
        width: usize,
    ) {
        self.str("\n  ");
        if description.is_empty() {
            self.str(label);
            return;
        }
        let taken = width + 4;
        let next_line = if !wraps || long || term_width == 0 {
            long
        } else {
            term_width >= taken
                && taken * 5 > term_width * 2
                && text_width(description) > term_width - taken
        };
        let wrapped = wraps && term_width > 0;
        if next_line {
            self.str(label);
            self.str("\n");
            self.spaces(NEXT_LINE_INDENT);
            let available = term_width.saturating_sub(NEXT_LINE_INDENT);
            self.paragraph(
                description,
                if wrapped { Some(available) } else { None },
                NEXT_LINE_INDENT,
            );
        } else {
            self.str(label);
            self.spaces(width - char_count(label) + 2);
            let available = term_width.saturating_sub(taken);
            self.paragraph(
                description,
                if wrapped { Some(available) } else { None },
                taken,
            );
        }
    }

    const fn entry(&mut self, page: &Page, entry: &HelpEntry, width: usize) {
        let (description, wraps) = if page.long {
            (entry.long, entry.long_wraps)
        } else {
            (entry.short, entry.short_wraps)
        };
        self.item(
            entry.label,
            description,
            wraps,
            page.long,
            page.term_width,
            width,
        );
    }

    const fn section(&mut self, page: &Page, title: &str) {
        let count = chain_len(page.entries);
        let options = str_eq(title, OPTIONS);
        let mut width = 0;
        let mut found = false;
        let mut index = 0;
        while index < count {
            if let Some(entry) = shown(page.entries, index)
                && visible_in(entry, title)
            {
                found = true;
                let length = char_count(entry.label);
                if length > width {
                    width = length;
                }
            }
            index += 1;
        }
        if options {
            index = 0;
            while index < page.reserved.len() {
                found = true;
                let length = char_count(page.reserved[index].label);
                if length > width {
                    width = length;
                }
                index += 1;
            }
        }
        if !found {
            return;
        }
        self.str("\n\n");
        self.str(title);
        self.str(":");
        let mut written = 0;
        let mut previous: Option<(usize, usize)> = None;
        loop {
            let mut next: Option<(usize, usize)> = None;
            index = 0;
            while index < count {
                if let Some(entry) = shown(page.entries, index)
                    && visible_in(entry, title)
                {
                    let key = (order(entry, index), index);
                    let after = match previous {
                        Some(previous) => greater(key, previous),
                        None => true,
                    };
                    let better = match next {
                        Some(next) => greater(next, key),
                        None => true,
                    };
                    if after && better {
                        next = Some(key);
                    }
                }
                index += 1;
            }
            let Some(key) = next else {
                break;
            };
            if written > 0 && page.long {
                self.str("\n");
            }
            let (entry, _) = chain_get(page.entries, key.1);
            self.entry(page, entry, width);
            written += 1;
            previous = Some(key);
        }
        if options {
            index = 0;
            while index < page.reserved.len() {
                if written > 0 && page.long {
                    self.str("\n");
                }
                self.entry(page, &page.reserved[index], width);
                written += 1;
                index += 1;
            }
        }
    }

    const fn commands(&mut self, page: &Page) {
        let commands = page.commands;
        let mut width = 0;
        let mut found = false;
        let mut index = 0;
        while index < commands.len() {
            if !commands[index].hidden {
                found = true;
                let length = char_count(commands[index].name);
                if length > width {
                    width = length;
                }
            }
            index += 1;
        }
        if !found {
            return;
        }
        self.str("\n\nCommands:");
        index = 0;
        while index < commands.len() {
            if !commands[index].hidden {
                self.item(
                    commands[index].name,
                    commands[index].description,
                    true,
                    false,
                    page.term_width,
                    width,
                );
            }
            index += 1;
        }
    }

    const fn body(&mut self, page: &Page) {
        let count = chain_len(page.entries);
        let mut options = !page.reserved.is_empty();
        let mut index = 0;
        while index < count {
            if let Some(entry) = shown(page.entries, index)
                && !entry.positional
            {
                options = true;
            }
            index += 1;
        }
        if options {
            self.str(" [OPTIONS]");
        }
        index = 0;
        while index < count {
            if let Some(entry) = shown(page.entries, index)
                && entry.positional
            {
                self.str(" ");
                self.str(entry.usage);
            }
            index += 1;
        }
        if !page.commands.is_empty() {
            self.str(if page.subcommand_required {
                " <COMMAND>"
            } else {
                " [COMMAND]"
            });
        }
        self.commands(page);
        self.section(page, ARGUMENTS);
        self.section(page, OPTIONS);
        index = 0;
        while index < count {
            if let Some(entry) = shown(page.entries, index) {
                let heading = title(entry);
                if !str_eq(heading, ARGUMENTS) && !str_eq(heading, OPTIONS) {
                    let mut seen = false;
                    let mut before = 0;
                    while before < index {
                        if let Some(earlier) = shown(page.entries, before)
                            && str_eq(title(earlier), heading)
                        {
                            seen = true;
                        }
                        before += 1;
                    }
                    if !seen {
                        self.section(page, heading);
                    }
                }
            }
            index += 1;
        }
    }

    const fn path(&mut self, path: &Path) {
        if let Some(parent) = path.parent {
            self.path(parent);
            self.str(" ");
        }
        self.str(path.name);
    }

    const fn text(&mut self, text: &str, term_width: usize) {
        self.paragraph(
            text,
            if term_width == 0 {
                None
            } else {
                Some(term_width)
            },
            0,
        );
    }

    const fn page(&mut self, node: &Node, entries: &Chain, long: bool) {
        let command = node.command;
        let term_width = command.term_width;
        if !command.before_help.is_empty() {
            self.text(command.before_help, term_width);
            self.str("\n\n");
        }
        let about = if long && !node.long_about.is_empty() {
            node.long_about
        } else {
            node.about
        };
        if !about.is_empty() {
            self.text(about, term_width);
            self.str("\n\n");
        }
        self.str("Usage: ");
        self.path(node.path);
        let has_long = node.has_long();
        let reserved = [
            HelpEntry::reserved(
                "-h, --help",
                help_flag(false, has_long),
                help_flag(true, has_long),
            ),
            HelpEntry::reserved("-V, --version", "Print version", "Print version"),
        ];
        let (reserved, _) = match (command.help_flag, node.root && command.version) {
            (true, true) => reserved.split_at(2),
            (true, false) => reserved.split_at(1),
            (false, true) => reserved.split_at(1).1.split_at(1),
            (false, false) => reserved.split_at(0),
        };
        self.body(&Page {
            entries,
            reserved,
            commands: command.commands,
            subcommand_required: command.subcommand_required,
            long,
            term_width,
        });
        if !command.after_help.is_empty() {
            self.str("\n\n");
            self.text(command.after_help, term_width);
        }
    }

    const fn tree(&mut self, node: &Node, parent: Option<&Chain>) {
        let command = node.command;
        let entries = Chain {
            entries: command.entries,
            all: true,
            parent,
        };
        let start = self.position;
        self.mark();
        self.page(node, &entries, false);
        let end = self.position;
        self.mark();
        if node.has_long() {
            self.mark();
            self.page(node, &entries, true);
            self.mark();
        } else {
            self.mark_at(start);
            self.mark_at(end);
        }
        let globals = Chain {
            entries: command.entries,
            all: false,
            parent,
        };
        let mut index = 0;
        while index < command.commands.len() {
            let entry = &command.commands[index];
            let path = Path {
                name: entry.name,
                parent: Some(node.path),
            };
            self.tree(
                &Node {
                    command: entry.command,
                    about: entry.about,
                    long_about: entry.long_about,
                    path: &path,
                    root: false,
                },
                Some(&globals),
            );
            index += 1;
        }
    }
}

struct Page<'p> {
    entries: &'p Chain<'p>,
    reserved: &'p [HelpEntry],
    commands: &'p [CommandEntry],
    subcommand_required: bool,
    long: bool,
    term_width: usize,
}

struct Chain<'c> {
    entries: &'c [HelpEntry],
    all: bool,
    parent: Option<&'c Chain<'c>>,
}

struct Path<'p> {
    name: &'p str,
    parent: Option<&'p Path<'p>>,
}

struct Node<'n> {
    command: &'n CommandHelp,
    about: &'n str,
    long_about: &'n str,
    path: &'n Path<'n>,
    root: bool,
}

impl Node<'_> {
    const fn has_long(&self) -> bool {
        !self.long_about.is_empty() || self.command.has_long_help
    }
}

const fn chain_len(chain: &Chain) -> usize {
    let mut total = 0;
    let mut current = Some(chain);
    while let Some(link) = current {
        total += link.entries.len();
        current = link.parent;
    }
    total
}

const fn chain_get<'c>(chain: &Chain<'c>, index: usize) -> (&'c HelpEntry, bool) {
    let mut index = index;
    let mut entries = chain.entries;
    let mut all = chain.all;
    let mut parent = chain.parent;
    loop {
        if index < entries.len() {
            return (&entries[index], all || entries[index].global);
        }
        index -= entries.len();
        match parent {
            Some(link) => {
                entries = link.entries;
                all = link.all;
                parent = link.parent;
            }
            None => panic!("help entry index out of range"),
        }
    }
}

const fn shown<'c>(chain: &Chain<'c>, index: usize) -> Option<&'c HelpEntry> {
    let (entry, included) = chain_get(chain, index);
    if included && !entry.hidden {
        Some(entry)
    } else {
        None
    }
}

const fn greater(first: (usize, usize), second: (usize, usize)) -> bool {
    first.0 > second.0 || (first.0 == second.0 && first.1 > second.1)
}

const fn order(entry: &HelpEntry, index: usize) -> usize {
    if entry.ordered { entry.order } else { index }
}

const fn title(entry: &HelpEntry) -> &str {
    if !entry.heading.is_empty() {
        entry.heading
    } else if entry.positional {
        ARGUMENTS
    } else {
        OPTIONS
    }
}

const fn visible_in(entry: &HelpEntry, section: &str) -> bool {
    str_eq(title(entry), section)
}

const fn render(output: &mut [u8], help: &Help) -> usize {
    let mut writer = Writer {
        output,
        position: 0,
        marks: &mut [],
        mark: 0,
    };
    writer.str(help.prefix);
    writer.body(&Page {
        entries: &Chain {
            entries: help.entries,
            all: true,
            parent: None,
        },
        reserved: help.reserved,
        commands: &[],
        subcommand_required: false,
        long: help.long,
        term_width: help.term_width,
    });
    writer.str(help.suffix);
    writer.position
}

/// Length in bytes of the help text rendered by [`help`].
pub const fn help_len(help: &Help) -> usize {
    render(&mut [], help)
}

/// Renders the help text with the same layout as the help of a struct without flattened fields.
/// `N` must be [`help_len`].
pub const fn help<const N: usize>(help: &Help) -> [u8; N] {
    let mut output = [0; N];
    let length = render(&mut output, help);
    assert!(length == N, "help length mismatch");
    output
}

const fn render_tree(output: &mut [u8], marks: &mut [usize], root: &CommandHelp) -> usize {
    let mut writer = Writer {
        output,
        position: 0,
        marks,
        mark: 0,
    };
    let path = Path {
        name: root.name,
        parent: None,
    };
    writer.tree(
        &Node {
            command: root,
            about: root.about,
            long_about: root.long_about,
            path: &path,
            root: true,
        },
        None,
    );
    writer.position
}

/// Length in bytes of the help texts of every command of the tree rooted at `root`.
pub const fn tree_len(root: &CommandHelp) -> usize {
    render_tree(&mut [], &mut [], root)
}

/// Renders the short and long help of every command of the tree rooted at `root`, in pre-order.
/// `N` must be [`tree_len`].
pub const fn tree<const N: usize>(root: &CommandHelp) -> [u8; N] {
    let mut output = [0; N];
    let length = render_tree(&mut output, &mut [], root);
    assert!(length == N, "help length mismatch");
    output
}

/// The start and end of every help rendered by [`tree`]. `N` must be four times [`nodes`].
pub const fn tree_marks<const N: usize>(root: &CommandHelp) -> [usize; N] {
    let mut marks = [0; N];
    render_tree(&mut [], &mut marks, root);
    marks
}

/// Splits the output of [`tree`] into the short and long help of every command, in pre-order.
/// `N` must be twice [`nodes`].
pub const fn tree_helps<const N: usize>(
    bytes: &'static [u8],
    marks: &[usize],
) -> [&'static str; N] {
    let mut helps = [""; N];
    let mut index = 0;
    while index < N {
        let start = marks[2 * index];
        let end = marks[2 * index + 1];
        let (_, rest) = bytes.split_at(start);
        let (text, _) = rest.split_at(end - start);
        helps[index] = utf8(text);
        index += 1;
    }
    helps
}

/// Converts rendered help bytes back to a string.
pub const fn utf8(bytes: &[u8]) -> &str {
    match core::str::from_utf8(bytes) {
        Ok(text) => text,
        Err(_) => panic!("help text is not valid UTF-8"),
    }
}