lexarg-parser 0.0.2

Minimal, API stable CLI parser
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
//! Minimal, API stable CLI parser
//!
//! Inspired by [lexopt](https://crates.io/crates/lexopt), `lexarg` simplifies the formula down
//! further so it can be used for CLI plugin systems.
//!
//! ## Example
//!
//! ```no_run
#![doc = include_str!("../examples/hello-parser.rs")]
//! ```

#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![allow(clippy::result_unit_err)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(clippy::print_stderr)]
#![warn(clippy::print_stdout)]

mod ext;

use std::ffi::OsStr;

use ext::OsStrExt as _;

/// A parser for command line arguments.
#[derive(Debug, Clone)]
pub struct Parser<'a> {
    raw: &'a dyn RawArgs,
    current: usize,
    state: Option<State<'a>>,
    was_attached: bool,
}

impl<'a> Parser<'a> {
    /// Create a parser from an iterator. This is useful for testing among other things.
    ///
    /// The first item from the iterator **must** be the binary name, as from [`std::env::args_os`].
    ///
    /// The iterator is consumed immediately.
    ///
    /// # Example
    /// ```
    /// let args = ["myapp", "-n", "10", "./foo.bar"];
    /// let mut parser = lexarg_parser::Parser::new(&&args[1..]);
    /// ```
    pub fn new(raw: &'a dyn RawArgs) -> Self {
        Parser {
            raw,
            current: 0,
            state: None,
            was_attached: false,
        }
    }

    /// Get the next option or positional [`Arg`].
    ///
    /// Returns `None` if the command line has been exhausted.
    ///
    /// Returns [`Arg::Unexpected`] on failure
    ///
    /// Notes:
    /// - `=` is always accepted as a [`Arg::Short("=")`].  If that isn't the case in your
    ///   application, you may want to special case the error for that.
    pub fn next_arg(&mut self) -> Option<Arg<'a>> {
        // Always reset
        self.was_attached = false;

        match self.state {
            Some(State::PendingValue(attached)) => {
                // Last time we got `--long=value`, and `value` hasn't been used.
                self.state = None;
                self.current += 1;
                Some(Arg::Unexpected(attached))
            }
            Some(State::PendingShorts(valid, invalid, index)) => {
                // We're somewhere inside a `-abc` chain. Because we're in `.next_arg()`, not `.next_flag_value()`, we
                // can assume that the next character is another option.
                if let Some(next_index) = ceil_char_boundary(valid, index) {
                    if next_index < valid.len() {
                        self.state = Some(State::PendingShorts(valid, invalid, next_index));
                    } else if !invalid.is_empty() {
                        self.state = Some(State::PendingValue(invalid));
                    } else {
                        // No more flags
                        self.state = None;
                        self.current += 1;
                    }
                    let flag = &valid[index..next_index];
                    Some(Arg::Short(flag))
                } else {
                    debug_assert_ne!(invalid, "");
                    if index == 0 {
                        panic!("there should have been a `-`")
                    } else if index == 1 {
                        // Like long flags, include `-`
                        let arg = self
                            .raw
                            .get(self.current)
                            .expect("`current` is valid if state is `Shorts`");
                        self.state = None;
                        self.current += 1;
                        Some(Arg::Unexpected(arg))
                    } else {
                        self.state = None;
                        self.current += 1;
                        Some(Arg::Unexpected(invalid))
                    }
                }
            }
            Some(State::Escaped) => {
                self.state = Some(State::Escaped);
                self.next_raw_().map(Arg::Value)
            }
            None => {
                let arg = self.raw.get(self.current)?;
                if arg == "--" {
                    self.state = Some(State::Escaped);
                    self.current += 1;
                    Some(Arg::Escape(arg.to_str().expect("`--` is valid UTF-8")))
                } else if arg == "-" {
                    self.state = None;
                    self.current += 1;
                    Some(Arg::Value(arg))
                } else if let Some(long) = arg.strip_prefix("--") {
                    let (name, value) = long
                        .split_once("=")
                        .map(|(n, v)| (n, Some(v)))
                        .unwrap_or((long, None));
                    if name.is_empty() {
                        self.state = None;
                        self.current += 1;
                        Some(Arg::Unexpected(arg))
                    } else if let Ok(name) = name.try_str() {
                        if let Some(value) = value {
                            self.state = Some(State::PendingValue(value));
                        } else {
                            self.state = None;
                            self.current += 1;
                        }
                        Some(Arg::Long(name))
                    } else {
                        self.state = None;
                        self.current += 1;
                        Some(Arg::Unexpected(arg))
                    }
                } else if arg.starts_with("-") {
                    let (valid, invalid) = split_nonutf8_once(arg);
                    let invalid = invalid.unwrap_or_default();
                    self.state = Some(State::PendingShorts(valid, invalid, 1));
                    self.next_arg()
                } else {
                    self.state = None;
                    self.current += 1;
                    Some(Arg::Value(arg))
                }
            }
        }
    }

    /// Get a flag's value
    ///
    /// This function should normally be called right after seeing a flag that expects a value;
    /// positional arguments should be collected with [`Parser::next_arg()`].
    ///
    /// A value is collected even if it looks like an option (i.e., starts with `-`).
    ///
    /// `None` is returned if there is not another applicable flag value, including:
    /// - No more arguments are present
    /// - `--` was encountered, meaning all remaining arguments are positional
    /// - Being called again when the first value was attached (`--flag=value`, `-Fvalue`, `-F=value`)
    pub fn next_flag_value(&mut self) -> Option<&'a OsStr> {
        if self.was_attached {
            debug_assert!(!self.has_pending());
            None
        } else if let Some(value) = self.next_attached_value() {
            Some(value)
        } else {
            self.next_detached_value()
        }
    }

    /// Get a flag's attached value (`--flag=value`, `-Fvalue`, `-F=value`)
    ///
    /// This is a more specialized variant of [`Parser::next_flag_value`] for when only attached
    /// values are allowed, e.g. `--color[=<when>]`.
    pub fn next_attached_value(&mut self) -> Option<&'a OsStr> {
        match self.state? {
            State::PendingValue(attached) => {
                self.state = None;
                self.current += 1;
                self.was_attached = true;
                Some(attached)
            }
            State::PendingShorts(_, _, index) => {
                let arg = self
                    .raw
                    .get(self.current)
                    .expect("`current` is valid if state is `Shorts`");
                self.state = None;
                self.current += 1;
                if index == arg.len() {
                    None
                } else {
                    // SAFETY: everything preceding `index` were a short flags, making them valid UTF-8
                    let remainder = unsafe { ext::split_at(arg, index) }.1;
                    let remainder = remainder.strip_prefix("=").unwrap_or(remainder);
                    self.was_attached = true;
                    Some(remainder)
                }
            }
            State::Escaped => None,
        }
    }

    fn next_detached_value(&mut self) -> Option<&'a OsStr> {
        if self.state == Some(State::Escaped) {
            // Escaped values are positional-only
            return None;
        }

        if self.peek_raw_()? == "--" {
            None
        } else {
            self.next_raw_()
        }
    }

    /// Get the next argument, independent of what it looks like
    ///
    /// Returns `Err(())` if an [attached value][Parser::next_attached_value] is present
    pub fn next_raw(&mut self) -> Result<Option<&'a OsStr>, ()> {
        if self.has_pending() {
            Err(())
        } else {
            self.was_attached = false;
            Ok(self.next_raw_())
        }
    }

    /// Collect all remaining arguments, independent of what they look like
    ///
    /// Returns `Err(())` if an [attached value][Parser::next_attached_value] is present
    pub fn remaining_raw(&mut self) -> Result<impl Iterator<Item = &'a OsStr> + '_, ()> {
        if self.has_pending() {
            Err(())
        } else {
            self.was_attached = false;
            Ok(std::iter::from_fn(|| self.next_raw_()))
        }
    }

    /// Get the next argument, independent of what it looks like
    ///
    /// Returns `Err(())` if an [attached value][Parser::next_attached_value] is present
    pub fn peek_raw(&self) -> Result<Option<&'a OsStr>, ()> {
        if self.has_pending() {
            Err(())
        } else {
            Ok(self.peek_raw_())
        }
    }

    fn peek_raw_(&self) -> Option<&'a OsStr> {
        self.raw.get(self.current)
    }

    fn next_raw_(&mut self) -> Option<&'a OsStr> {
        debug_assert!(!self.has_pending());
        debug_assert!(!self.was_attached);

        let next = self.raw.get(self.current)?;
        self.current += 1;
        Some(next)
    }

    fn has_pending(&self) -> bool {
        self.state.as_ref().map(State::has_pending).unwrap_or(false)
    }
}

/// Accessor for unparsed arguments
pub trait RawArgs: std::fmt::Debug + private::Sealed {
    /// Returns a reference to an element or subslice depending on the type of index.
    ///
    /// - If given a position, returns a reference to the element at that position or None if out
    ///   of bounds.
    /// - If given a range, returns the subslice corresponding to that range, or None if out
    ///   of bounds.
    fn get(&self, index: usize) -> Option<&OsStr>;

    /// Returns the number of elements in the slice.
    fn len(&self) -> usize;

    /// Returns `true` if the slice has a length of 0.
    fn is_empty(&self) -> bool;
}

impl<const C: usize, S> RawArgs for [S; C]
where
    S: AsRef<OsStr> + std::fmt::Debug,
{
    #[inline]
    fn get(&self, index: usize) -> Option<&OsStr> {
        self.as_slice().get(index).map(|s| s.as_ref())
    }

    #[inline]
    fn len(&self) -> usize {
        C
    }

    #[inline]
    fn is_empty(&self) -> bool {
        C != 0
    }
}

impl<S> RawArgs for &'_ [S]
where
    S: AsRef<OsStr> + std::fmt::Debug,
{
    #[inline]
    fn get(&self, index: usize) -> Option<&OsStr> {
        (*self).get(index).map(|s| s.as_ref())
    }

    #[inline]
    fn len(&self) -> usize {
        (*self).len()
    }

    #[inline]
    fn is_empty(&self) -> bool {
        (*self).is_empty()
    }
}

impl<S> RawArgs for Vec<S>
where
    S: AsRef<OsStr> + std::fmt::Debug,
{
    #[inline]
    fn get(&self, index: usize) -> Option<&OsStr> {
        self.as_slice().get(index).map(|s| s.as_ref())
    }

    #[inline]
    fn len(&self) -> usize {
        self.len()
    }

    #[inline]
    fn is_empty(&self) -> bool {
        self.is_empty()
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum State<'a> {
    /// We have a value left over from `--option=value`
    PendingValue(&'a OsStr),
    /// We're in the middle of `-abc`
    ///
    /// On Windows and other non-UTF8-OsString platforms this Vec should
    /// only ever contain valid UTF-8 (and could instead be a String).
    PendingShorts(&'a str, &'a OsStr, usize),
    /// We saw `--` and know no more options are coming.
    Escaped,
}

impl State<'_> {
    fn has_pending(&self) -> bool {
        match self {
            Self::PendingValue(_) | Self::PendingShorts(_, _, _) => true,
            Self::Escaped => false,
        }
    }
}

/// A command line argument found by [`Parser`], either an option or a positional argument
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Arg<'a> {
    /// A short option, e.g. `Short("q")` for `-q`
    Short(&'a str),
    /// A long option, e.g. `Long("verbose")` for `--verbose`
    ///
    /// The dashes are not included
    Long(&'a str),
    /// A positional argument, e.g. `/dev/null`
    Value(&'a OsStr),
    /// Marks the following values have been escaped with `--`
    Escape(&'a str),
    /// User passed something in that doesn't work
    Unexpected(&'a OsStr),
}

fn split_nonutf8_once(b: &OsStr) -> (&str, Option<&OsStr>) {
    match b.try_str() {
        Ok(s) => (s, None),
        Err(err) => {
            // SAFETY: `char_indices` ensures `index` is at a valid UTF-8 boundary
            let (valid, after_valid) = unsafe { ext::split_at(b, err.valid_up_to()) };
            let valid = valid.try_str().unwrap();
            (valid, Some(after_valid))
        }
    }
}

fn ceil_char_boundary(s: &str, curr_boundary: usize) -> Option<usize> {
    (curr_boundary + 1..=s.len()).find(|i| s.is_char_boundary(*i))
}

mod private {
    use super::OsStr;

    #[allow(unnameable_types)]
    pub trait Sealed {}
    impl<const C: usize, S> Sealed for [S; C] where S: AsRef<OsStr> + std::fmt::Debug {}
    impl<S> Sealed for &'_ [S] where S: AsRef<OsStr> + std::fmt::Debug {}
    impl<S> Sealed for Vec<S> where S: AsRef<OsStr> + std::fmt::Debug {}
}

#[cfg(test)]
mod tests {
    use super::Arg::*;
    use super::*;

    #[test]
    fn test_basic() {
        let mut p = Parser::new(&["-n", "10", "foo", "-", "--", "baz", "-qux"]);
        assert_eq!(p.next_arg().unwrap(), Short("n"));
        assert_eq!(p.next_flag_value().unwrap(), "10");
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("foo")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-")));
        assert_eq!(p.next_arg().unwrap(), Escape("--"));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("baz")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-qux")));
        assert_eq!(p.next_arg(), None);
        assert_eq!(p.next_arg(), None);
        assert_eq!(p.next_arg(), None);
    }

    #[test]
    fn test_combined() {
        let mut p = Parser::new(&["-abc", "-fvalue", "-xfvalue"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg().unwrap(), Short("b"));
        assert_eq!(p.next_arg().unwrap(), Short("c"));
        assert_eq!(p.next_arg().unwrap(), Short("f"));
        assert_eq!(p.next_flag_value().unwrap(), "value");
        assert_eq!(p.next_arg().unwrap(), Short("x"));
        assert_eq!(p.next_arg().unwrap(), Short("f"));
        assert_eq!(p.next_flag_value().unwrap(), "value");
        assert_eq!(p.next_arg(), None);
    }

    #[test]
    fn test_long() {
        let mut p = Parser::new(&["--foo", "--bar=qux", "--foobar=qux=baz"]);
        assert_eq!(p.next_arg().unwrap(), Long("foo"));
        assert_eq!(p.next_arg().unwrap(), Long("bar"));
        assert_eq!(p.next_flag_value().unwrap(), "qux");
        assert_eq!(p.next_flag_value(), None);
        assert_eq!(p.next_arg().unwrap(), Long("foobar"));
        assert_eq!(p.next_arg().unwrap(), Unexpected(OsStr::new("qux=baz")));
        assert_eq!(p.next_arg(), None);
    }

    #[test]
    fn test_dash_args() {
        // "--" should indicate the end of the options
        let mut p = Parser::new(&["-x", "--", "-y"]);
        assert_eq!(p.next_arg().unwrap(), Short("x"));
        assert_eq!(p.next_arg().unwrap(), Escape("--"));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-y")));
        assert_eq!(p.next_arg(), None);

        // ...even if it's an argument of an option
        let mut p = Parser::new(&["-x", "--", "-y"]);
        assert_eq!(p.next_arg().unwrap(), Short("x"));
        assert_eq!(p.next_flag_value(), None);
        assert_eq!(p.next_arg().unwrap(), Escape("--"));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-y")));
        assert_eq!(p.next_arg(), None);

        // "-" is a valid value that should not be treated as an option
        let mut p = Parser::new(&["-x", "-", "-y"]);
        assert_eq!(p.next_arg().unwrap(), Short("x"));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-")));
        assert_eq!(p.next_arg().unwrap(), Short("y"));
        assert_eq!(p.next_arg(), None);

        // '-' is a silly and hard to use short option, but other parsers treat
        // it like an option in this position
        let mut p = Parser::new(&["-x-y"]);
        assert_eq!(p.next_arg().unwrap(), Short("x"));
        assert_eq!(p.next_arg().unwrap(), Short("-"));
        assert_eq!(p.next_arg().unwrap(), Short("y"));
        assert_eq!(p.next_arg(), None);
    }

    #[test]
    fn test_missing_value() {
        let mut p = Parser::new(&["-o"]);
        assert_eq!(p.next_arg().unwrap(), Short("o"));
        assert_eq!(p.next_flag_value(), None);

        let mut q = Parser::new(&["--out"]);
        assert_eq!(q.next_arg().unwrap(), Long("out"));
        assert_eq!(q.next_flag_value(), None);

        let args: [&OsStr; 0] = [];
        let mut r = Parser::new(&args);
        assert_eq!(r.next_flag_value(), None);
    }

    #[test]
    fn test_weird_args() {
        let mut p = Parser::new(&[
            "--=", "--=3", "-", "-x", "--", "-", "-x", "--", "", "-", "-x",
        ]);
        assert_eq!(p.next_arg().unwrap(), Unexpected(OsStr::new("--=")));
        assert_eq!(p.next_arg().unwrap(), Unexpected(OsStr::new("--=3")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-")));
        assert_eq!(p.next_arg().unwrap(), Short("x"));
        assert_eq!(p.next_arg().unwrap(), Escape("--"));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-x")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("--")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-")));
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("-x")));
        assert_eq!(p.next_arg(), None);

        let bad = bad_string("--=@");
        let args = [&bad];
        let mut q = Parser::new(&args);
        assert_eq!(q.next_arg().unwrap(), Unexpected(OsStr::new(&bad)));

        let mut r = Parser::new(&[""]);
        assert_eq!(r.next_arg().unwrap(), Value(OsStr::new("")));
    }

    #[test]
    fn test_unicode() {
        let mut p = Parser::new(&["-aµ", "--µ=10", "µ", "--foo=µ"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg().unwrap(), Short("µ"));
        assert_eq!(p.next_arg().unwrap(), Long("µ"));
        assert_eq!(p.next_flag_value().unwrap(), "10");
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("µ")));
        assert_eq!(p.next_arg().unwrap(), Long("foo"));
        assert_eq!(p.next_flag_value().unwrap(), "µ");
    }

    #[cfg(any(unix, target_os = "wasi", windows))]
    #[test]
    fn test_mixed_invalid() {
        let args = [bad_string("--foo=@@@")];
        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Long("foo"));
        assert_eq!(p.next_flag_value().unwrap(), bad_string("@@@"));

        let args = [bad_string("-💣@@@")];
        let mut q = Parser::new(&args);
        assert_eq!(q.next_arg().unwrap(), Short("💣"));
        assert_eq!(q.next_flag_value().unwrap(), bad_string("@@@"));

        let args = [bad_string("-f@@@")];
        let mut r = Parser::new(&args);
        assert_eq!(r.next_arg().unwrap(), Short("f"));
        assert_eq!(r.next_arg().unwrap(), Unexpected(&bad_string("@@@")));
        assert_eq!(r.next_arg(), None);

        let args = [bad_string("--foo=bar=@@@")];
        let mut s = Parser::new(&args);
        assert_eq!(s.next_arg().unwrap(), Long("foo"));
        assert_eq!(s.next_flag_value().unwrap(), bad_string("bar=@@@"));
    }

    #[cfg(any(unix, target_os = "wasi", windows))]
    #[test]
    fn test_separate_invalid() {
        let args = [bad_string("--foo"), bad_string("@@@")];
        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Long("foo"));
        assert_eq!(p.next_flag_value().unwrap(), bad_string("@@@"));
    }

    #[cfg(any(unix, target_os = "wasi", windows))]
    #[test]
    fn test_invalid_long_option() {
        let args = [bad_string("--@=10")];
        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Unexpected(&args[0]));
        assert_eq!(p.next_arg(), None);

        let args = [bad_string("--@")];
        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Unexpected(&args[0]));
        assert_eq!(p.next_arg(), None);
    }

    #[cfg(any(unix, target_os = "wasi", windows))]
    #[test]
    fn test_invalid_short_option() {
        let args = [bad_string("-@")];
        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Unexpected(&args[0]));
        assert_eq!(p.next_arg(), None);
    }

    #[test]
    fn short_opt_equals_sign() {
        let mut p = Parser::new(&["-a=b"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_flag_value().unwrap(), OsStr::new("b"));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-a=b", "c"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_flag_value().unwrap(), OsStr::new("b"));
        assert_eq!(p.next_flag_value(), None);
        assert_eq!(p.next_arg().unwrap(), Value(OsStr::new("c")));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-a=b"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg().unwrap(), Short("="));
        assert_eq!(p.next_arg().unwrap(), Short("b"));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-a="]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_flag_value().unwrap(), OsStr::new(""));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-a=="]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_flag_value().unwrap(), OsStr::new("="));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-abc=de"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_flag_value().unwrap(), OsStr::new("bc=de"));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-abc==de"]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg().unwrap(), Short("b"));
        assert_eq!(p.next_arg().unwrap(), Short("c"));
        assert_eq!(p.next_flag_value().unwrap(), OsStr::new("=de"));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-a="]);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg().unwrap(), Short("="));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-="]);
        assert_eq!(p.next_arg().unwrap(), Short("="));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&["-=a"]);
        assert_eq!(p.next_arg().unwrap(), Short("="));
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg(), None);
    }

    #[cfg(any(unix, target_os = "wasi", windows))]
    #[test]
    fn short_opt_equals_sign_invalid() {
        let bad = bad_string("@");
        let args = [bad_string("-a=@")];
        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_flag_value().unwrap(), bad_string("@"));
        assert_eq!(p.next_arg(), None);

        let mut p = Parser::new(&args);
        assert_eq!(p.next_arg().unwrap(), Short("a"));
        assert_eq!(p.next_arg().unwrap(), Short("="));
        assert_eq!(p.next_arg().unwrap(), Unexpected(&bad));
        assert_eq!(p.next_arg(), None);
    }

    #[test]
    fn remaining_raw() {
        let mut p = Parser::new(&["-a", "b", "c", "d"]);
        assert_eq!(
            p.remaining_raw().unwrap().collect::<Vec<_>>(),
            &["-a", "b", "c", "d"]
        );
        // Consumed all
        assert!(p.next_arg().is_none());
        assert!(p.remaining_raw().is_ok());
        assert_eq!(p.remaining_raw().unwrap().collect::<Vec<_>>().len(), 0);

        let mut p = Parser::new(&["-ab", "c", "d"]);
        p.next_arg().unwrap();
        // Attached value
        assert!(p.remaining_raw().is_err());
        p.next_attached_value().unwrap();
        assert_eq!(p.remaining_raw().unwrap().collect::<Vec<_>>(), &["c", "d"]);
        // Consumed all
        assert!(p.next_arg().is_none());
        assert_eq!(p.remaining_raw().unwrap().collect::<Vec<_>>().len(), 0);
    }

    /// Transform @ characters into invalid unicode.
    fn bad_string(text: &str) -> std::ffi::OsString {
        #[cfg(any(unix, target_os = "wasi"))]
        {
            #[cfg(unix)]
            use std::os::unix::ffi::OsStringExt;
            #[cfg(target_os = "wasi")]
            use std::os::wasi::ffi::OsStringExt;
            let mut text = text.as_bytes().to_vec();
            for ch in &mut text {
                if *ch == b'@' {
                    *ch = b'\xFF';
                }
            }
            std::ffi::OsString::from_vec(text)
        }
        #[cfg(windows)]
        {
            use std::os::windows::ffi::OsStringExt;
            let mut out = Vec::new();
            for ch in text.chars() {
                if ch == '@' {
                    out.push(0xD800);
                } else {
                    let mut buf = [0; 2];
                    out.extend(&*ch.encode_utf16(&mut buf));
                }
            }
            std::ffi::OsString::from_wide(&out)
        }
        #[cfg(not(any(unix, target_os = "wasi", windows)))]
        {
            if text.contains('@') {
                unimplemented!("Don't know how to create invalid OsStrings on this platform");
            }
            text.into()
        }
    }

    /// Basic exhaustive testing of short combinations of "interesting"
    /// arguments. They should not panic, not hang, and pass some checks.
    ///
    /// The advantage compared to full fuzzing is that it runs on all platforms
    /// and together with the other tests. cargo-fuzz doesn't work on Windows
    /// and requires a special incantation.
    ///
    /// A disadvantage is that it's still limited by arguments I could think of
    /// and only does very short sequences. Another is that it's bad at
    /// reporting failure, though the println!() helps.
    ///
    /// This test takes a while to run.
    #[test]
    fn basic_fuzz() {
        #[cfg(any(windows, unix, target_os = "wasi"))]
        const VOCABULARY: &[&str] = &[
            "", "-", "--", "---", "a", "-a", "-aa", "@", "-@", "-a@", "-@a", "--a", "--@", "--a=a",
            "--a=", "--a=@", "--@=a", "--=", "--=@", "--=a", "-@@", "-a=a", "-a=", "-=", "-a-",
        ];
        #[cfg(not(any(windows, unix, target_os = "wasi")))]
        const VOCABULARY: &[&str] = &[
            "", "-", "--", "---", "a", "-a", "-aa", "--a", "--a=a", "--a=", "--=", "--=a", "-a=a",
            "-a=", "-=", "-a-",
        ];
        let args: [&OsStr; 0] = [];
        exhaust(Parser::new(&args), vec![]);
        let vocabulary: Vec<std::ffi::OsString> =
            VOCABULARY.iter().map(|&s| bad_string(s)).collect();
        let mut permutations = vec![vec![]];
        for _ in 0..3 {
            let mut new = Vec::new();
            for old in permutations {
                for word in &vocabulary {
                    let mut extended = old.clone();
                    extended.push(word);
                    new.push(extended);
                }
            }
            permutations = new;
            for permutation in &permutations {
                println!("Starting {permutation:?}");
                let p = Parser::new(permutation);
                exhaust(p, vec![]);
            }
        }
    }

    /// Run many sequences of methods on a Parser.
    fn exhaust(parser: Parser<'_>, path: Vec<String>) {
        if path.len() > 100 {
            panic!("Stuck in loop: {path:?}");
        }

        if parser.has_pending() {
            {
                let mut parser = parser.clone();
                let next = parser.next_arg();
                assert!(
                    matches!(next, Some(Unexpected(_)) | Some(Short(_))),
                    "{next:?} via {path:?}",
                );
                let mut path = path.clone();
                path.push(format!("pending-next-{next:?}"));
                exhaust(parser, path);
            }

            {
                let mut parser = parser.clone();
                let next = parser.next_flag_value();
                assert!(next.is_some(), "{next:?} via {path:?}",);
                let mut path = path;
                path.push(format!("pending-value-{next:?}"));
                exhaust(parser, path);
            }
        } else {
            {
                let mut parser = parser.clone();
                let next = parser.next_arg();
                match &next {
                    None => {
                        assert!(
                            matches!(parser.state, None | Some(State::Escaped)),
                            "{next:?} via {path:?}",
                        );
                        assert_eq!(parser.current, parser.raw.len(), "{next:?} via {path:?}",);
                    }
                    _ => {
                        let mut path = path.clone();
                        path.push(format!("next-{next:?}"));
                        exhaust(parser, path);
                    }
                }
            }

            {
                let mut parser = parser.clone();
                let next = parser.next_flag_value();
                match &next {
                    None => {
                        assert!(
                            matches!(parser.state, None | Some(State::Escaped)),
                            "{next:?} via {path:?}",
                        );
                        if parser.state.is_none()
                            && !parser.was_attached
                            && parser.peek_raw_() != Some(OsStr::new("--"))
                        {
                            assert_eq!(parser.current, parser.raw.len(), "{next:?} via {path:?}",);
                        }
                    }
                    Some(_) => {
                        assert!(
                            matches!(parser.state, None | Some(State::Escaped)),
                            "{next:?} via {path:?}",
                        );
                        let mut path = path;
                        path.push(format!("value-{next:?}"));
                        exhaust(parser, path);
                    }
                }
            }
        }
    }
}

#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;