palc 0.0.2

WIP: Command Line Argument Parser with several opposite design goal from Clap
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
use std::ffi::{OsStr, OsString};
use std::marker::PhantomData;
use std::num::NonZero;
use std::ops::ControlFlow;

use os_str_bytes::OsStrBytesExt;
use ref_cast::RefCast;

use crate::Result;
use crate::error::ErrorKind;
use crate::refl::{RawArgsInfo, RawSubcommandInfo};
use crate::shared::ArgAttrs;
use crate::values::ValueParser;

use super::Error;

/// The implementation detail of [`crate::Parser`].
/// Not in public API.
#[doc(hidden)]
pub trait ParserInternal: Sized {
    fn __parse_toplevel(p: &mut RawParser, program_name: &OsStr) -> Result<Self>;
}

/// Trait of argument structs, for composition.
///
/// This trait is in not public API. Only `derive(Args)` is.
#[diagnostic::on_unimplemented(
    message = "cannot flatten `{Self}` which is not a `palc::Args`",
    label = "this type is expected to have `derive(palc::Args)` but it is not"
)]
#[doc(hidden)]
pub trait Args: Sized + 'static {
    #[doc(hidden)]
    type __State: ParserState<Output = Self>;
}

/// The fallback state type for graceful failing from proc-macro.
pub struct FallbackState<T>(PhantomData<T>);

impl<T> Default for FallbackState<T> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<T: 'static> ParserState for FallbackState<T> {
    type Output = T;

    const RAW_ARGS_INFO: &'static RawArgsInfo = RawArgsInfo::EMPTY_REF;

    const TOTAL_ARG_CNT: u8 = 0;
    const TOTAL_UNNAMED_ARG_CNT: u8 = 0;

    fn finish(&mut self) -> Result<Self::Output> {
        // Never called at runtime.
        unreachable!()
    }
}
impl<T: 'static> ParserStateDyn for FallbackState<T> {}

// TODO: Invalid default strings are only caught at runtime, which is not ideal.
pub fn parse_default_str<P: ValueParser>(s: &str, _: P) -> Result<P::Output> {
    P::parse(s.as_ref())
}

pub fn assert_impl_display_for_help<T: std::fmt::Display>(x: T) -> T {
    x
}

// TODO: Check inlining behavior is expected.
pub fn unknown_subcommand<T>(name: &OsStr) -> Result<T> {
    Err(ErrorKind::UnknownSubcommand.with_input(name.into()))
}

pub fn missing_required_arg<S: ParserState, T>(idx: u8) -> Result<T> {
    Err(ErrorKind::MissingRequiredArgument.with_arg_idx::<S>(idx))
}

pub fn missing_required_subcmd<T>() -> Result<T> {
    Err(ErrorKind::MissingRequiredSubcommand.into())
}

pub fn constraint_required<S: ParserState, T>(idx: u8) -> Result<T> {
    Err(ErrorKind::ConstraintRequired.with_arg_idx::<S>(idx))
}

pub fn constraint_exclusive<S: ParserState, T>(idx: u8) -> Result<T> {
    Err(ErrorKind::ConstraintExclusive.with_arg_idx::<S>(idx))
}

pub fn constraint_conflict<S: ParserState, T>(idx: u8) -> Result<T> {
    Err(ErrorKind::ConstraintConflict.with_arg_idx::<S>(idx))
}

/// Type-erased objects that can be parsed into.
pub trait Parsable {
    /// `attrs` is the same value returned from `feed_*`.
    /// About `value`:
    /// - For named arguments accepting zero values, it should be ignored.
    /// - For named or unnamed arguments accepting one value, it is the extracted
    ///   string to be parsed, either from `--named=value`, `-ovalue` or `value`.
    ///   The callee should simply parse it.
    /// - For variable length unnamed arguments, it is the first argument
    ///   triggering the parsing. The callee should consume it and all the rest arguments.
    ///
    /// `cur_cmd_name` and `ancestors` are only used for subcommand, and should
    /// be ignored otherwise. They are not passed for named arguments.
    fn parse_from(
        &mut self,
        p: &mut RawParser,
        attrs: ArgAttrs,
        value: &OsStr,
        cur_cmd_name: &OsStr,
        ancestors: &mut dyn ParserChain,
    ) -> Result<()>;
}

/// A state for parsing a field.
pub trait FieldState: Default {
    type Value;
    type Output;
    fn place<P: ValueParser<Output = Self::Value>>(&mut self, _: P) -> &mut dyn Parsable;
    fn finish(&mut self) -> Self::Output;
    fn finish_opt(&mut self) -> Option<Self::Output>;
    fn is_set(&self) -> bool;
    // NB. This is the default output value, i.e. the default type is `Vec<T>` for multi-args.
    fn set_default(&mut self, f: impl FnOnce() -> Self::Output);
    fn set_default_parse<P: ValueParser<Output = Self::Value>>(&mut self, default: &str, p: P) {
        #[inline(never)]
        fn set_from_default_dyn(p: &mut dyn Parsable, default: &OsStr) {
            p.parse_from(
                &mut RawParser::new(&mut std::iter::empty()),
                ArgAttrs::default(),
                default.as_ref(),
                "".as_ref(),
                &mut (),
            )
            .expect("invalid default value");
        }

        if !self.is_set() {
            set_from_default_dyn(self.place(p), default.as_ref());
        }
    }
}

#[derive(Default)]
pub struct FlagPlace(Option<bool>);

impl FieldState for FlagPlace {
    type Value = bool;
    type Output = bool;
    fn place<P: ValueParser<Output = bool>>(&mut self, _: P) -> &mut dyn Parsable {
        self
    }
    fn finish(&mut self) -> bool {
        self.0.unwrap_or_default()
    }
    fn finish_opt(&mut self) -> Option<Self::Output> {
        unreachable!()
    }
    fn is_set(&self) -> bool {
        self.0.is_some()
    }
    fn set_default(&mut self, f: impl FnOnce() -> Self::Value) {
        self.0.get_or_insert_with(f);
    }
}
impl Parsable for FlagPlace {
    fn parse_from(
        &mut self,
        _: &mut RawParser,
        _: ArgAttrs,
        _: &OsStr,
        _: &OsStr,
        _: &mut dyn ParserChain,
    ) -> Result<()> {
        if self.0.is_some() {
            return Err(ErrorKind::DuplicatedNamedArgument.into());
        }
        self.0 = Some(true);
        Ok(())
    }
}

pub struct VecPlace<T>(Vec<T>);
impl<T> Default for VecPlace<T> {
    fn default() -> Self {
        Self(Vec::new())
    }
}
impl<T> FieldState for VecPlace<T> {
    type Value = T;
    type Output = Vec<T>;
    fn place<P: ValueParser<Output = Self::Value>>(&mut self, _: P) -> &mut dyn Parsable {
        <VecParser<P>>::ref_cast_mut(self)
    }
    fn finish(&mut self) -> Vec<T> {
        std::mem::take(&mut self.0)
    }
    fn finish_opt(&mut self) -> Option<Vec<T>> {
        if self.0.is_empty() { None } else { Some(self.finish()) }
    }
    fn is_set(&self) -> bool {
        !self.0.is_empty()
    }
    fn set_default(&mut self, f: impl FnOnce() -> Self::Output) {
        if self.0.is_empty() {
            self.0 = f();
        }
    }
}

#[derive(RefCast)]
#[repr(transparent)]
struct VecParser<P: ValueParser>(VecPlace<P::Output>);
impl<P: ValueParser> Parsable for VecParser<P> {
    fn parse_from(
        &mut self,
        p: &mut RawParser,
        attrs: ArgAttrs,
        value: &OsStr,
        _: &OsStr,
        _: &mut dyn ParserChain,
    ) -> Result<()> {
        let v = &mut self.0.0;

        let feed: &mut dyn FnMut(&OsStr) -> Result<()> = if let Some(delim) = attrs.get_delimiter()
        {
            &mut move |value| {
                for frag in value.split(char::from(delim.get())) {
                    v.push(P::parse(frag)?);
                }
                Ok(())
            }
        } else {
            &mut |value| {
                v.push(P::parse(value)?);
                Ok(())
            }
        };

        feed(value)?;
        if attrs.contains(ArgAttrs::GREEDY) {
            for value in &mut p.iter {
                feed(&value)?;
            }
        }
        Ok(())
    }
}

pub struct SetValuePlace<T>(Option<T>);
impl<T> Default for SetValuePlace<T> {
    fn default() -> Self {
        Self(None)
    }
}
impl<T> FieldState for SetValuePlace<T> {
    type Value = T;
    type Output = T;
    fn place<P: ValueParser<Output = Self::Value>>(&mut self, _: P) -> &mut dyn Parsable {
        <SetValueParser<P>>::ref_cast_mut(self)
    }
    fn finish(&mut self) -> T {
        self.0.take().unwrap()
    }
    fn finish_opt(&mut self) -> Option<T> {
        self.0.take()
    }
    fn is_set(&self) -> bool {
        self.0.is_some()
    }
    fn set_default(&mut self, f: impl FnOnce() -> Self::Value) {
        self.0.get_or_insert_with(f);
    }
}

#[derive(RefCast)]
#[repr(transparent)]
struct SetValueParser<P: ValueParser>(SetValuePlace<P::Output>);
impl<P: ValueParser> Parsable for SetValueParser<P> {
    fn parse_from(
        &mut self,
        _: &mut RawParser,
        _: ArgAttrs,
        value: &OsStr,
        _: &OsStr,
        _: &mut dyn ParserChain,
    ) -> Result<()> {
        if self.0.0.is_some() {
            return Err(ErrorKind::DuplicatedNamedArgument.into());
        }
        self.0.0 = Some(P::parse(value)?);
        Ok(())
    }
}

/// FIXME: This semantic is incorrect. It should accept `--foo` as `Some(None)`,
/// not `--foo=`.
pub struct SetOptionalValuePlace<T>(Option<Option<T>>);
impl<T> Default for SetOptionalValuePlace<T> {
    fn default() -> Self {
        Self(None)
    }
}
impl<T> FieldState for SetOptionalValuePlace<T> {
    type Value = T;
    type Output = Option<T>;
    fn place<P: ValueParser<Output = Self::Value>>(&mut self, _: P) -> &mut dyn Parsable {
        <SetOptionalValueParser<P>>::ref_cast_mut(self)
    }
    fn finish(&mut self) -> Option<T> {
        unreachable!()
    }
    fn finish_opt(&mut self) -> Option<Option<T>> {
        self.0.take()
    }
    fn is_set(&self) -> bool {
        self.0.is_some()
    }
    fn set_default(&mut self, f: impl FnOnce() -> Self::Output) {
        self.0.get_or_insert_with(f);
    }
}

#[derive(RefCast)]
#[repr(transparent)]
struct SetOptionalValueParser<P: ValueParser>(SetOptionalValuePlace<P::Output>);
impl<P: ValueParser> Parsable for SetOptionalValueParser<P> {
    fn parse_from(
        &mut self,
        _: &mut RawParser,
        _: ArgAttrs,
        value: &OsStr,
        _: &OsStr,
        _: &mut dyn ParserChain,
    ) -> Result<()> {
        if self.0.0.is_some() {
            return Err(ErrorKind::DuplicatedNamedArgument.into());
        }
        self.0.0 = Some(if value.is_empty() { None } else { Some(P::parse(value)?) });
        Ok(())
    }
}

/// The singly linked list for states of ancestor subcommands. Deeper states come first.
/// `ancestors` are made into trait object for lifetime erasure, or it won't compile.
pub(crate) struct ParserChainNode<'a, 'b, 'c> {
    pub cmd_name: &'a OsStr,
    pub state: &'b mut dyn ParserStateDyn,
    pub ancestors: &'c mut dyn ParserChain,
}

pub trait ParserChain {
    #[expect(private_interfaces, reason = "not used by proc-macro")]
    fn out(&mut self) -> Option<ParserChainNode<'_, '_, '_>> {
        None
    }
}

impl dyn ParserChain + '_ {
    fn feed_global_named(
        &mut self,
        enc_name: &str,
    ) -> ControlFlow<(&mut dyn Parsable, ArgAttrs, &'static RawArgsInfo)> {
        let Some(node) = self.out() else { return ControlFlow::Continue(()) };
        let info = node.state.info();
        if let ControlFlow::Break((place, attrs)) = node.state.feed_named(enc_name) {
            if attrs.contains(ArgAttrs::GLOBAL) {
                return ControlFlow::Break((place, attrs, info));
            }
        }
        node.ancestors.feed_global_named(enc_name)
    }
}

impl ParserChain for () {}

// TODO: De-virtualize this.
impl ParserChain for ParserChainNode<'_, '_, '_> {
    fn out(&mut self) -> Option<ParserChainNode<'_, '_, '_>> {
        // Reborrow fields.
        let ParserChainNode { cmd_name, state, ancestors } = self;
        Some(ParserChainNode { cmd_name, state: &mut **state, ancestors: &mut **ancestors })
    }
}

pub fn place_for_subcommand<G: GetSubcommand>(state: &mut G::State) -> FeedUnnamed<'_> {
    #[derive(RefCast)]
    #[repr(transparent)]
    struct Place<G: GetSubcommand>(G::State);

    impl<G: GetSubcommand> Parsable for Place<G> {
        fn parse_from(
            &mut self,
            p: &mut RawParser,
            _: ArgAttrs,
            value: &OsStr,
            cur_cmd_name: &OsStr,
            ancestors: &mut dyn ParserChain,
        ) -> Result<()> {
            // Recombine the state chain with the current state.
            let states =
                &mut ParserChainNode { cmd_name: cur_cmd_name, state: &mut self.0, ancestors };
            let subcmd = G::Subcommand::try_parse_with_name(p, value, states)?;
            *G::get(&mut self.0) = Some(subcmd);
            Ok(())
        }
    }

    ControlFlow::Break((Place::<G>::ref_cast_mut(state), /* unused */ ArgAttrs::default()))
}

/// `Break` on a resolved place. `Continue` on unknown names.
/// So we can `?` in generated code of `command(flatten)`.
pub type FeedNamed<'s> = ControlFlow<(&'s mut dyn Parsable, ArgAttrs)>;

pub type FeedUnnamed<'s> = FeedNamed<'s>;

pub trait ParserState: Default + ParserStateDyn {
    type Output;

    const RAW_ARGS_INFO: &'static RawArgsInfo = RawArgsInfo::EMPTY_REF;
    /// For proc-macro to reject flattening an `impl Args` with subcommands.
    const HAS_SUBCOMMAND: bool = false;

    const TOTAL_ARG_CNT: u8 = 0;
    const TOTAL_UNNAMED_ARG_CNT: u8 = 0;

    // Semantically this takes the ownership of `self`, but using `&mut self`
    // can eliminate partial drop codegen and call the default drop impl.
    // It gives a much better codegen.
    fn finish(&mut self) -> Result<Self::Output>;
}

/// The helper trait for `place_for_subcommand`.
///
/// It is possible to merge these methods into `ParserState`, but that would
/// expose `Subcommand` type at `UserParser::__State::Subcommand`, causing
/// various privacy issues if `UserParser` and its subcommand have different
/// privacy.
///
/// Here we define a separated (public) trait, but let proc-macro generate a
/// private witness type inside `feed_unnamed`, hiding the subcommand type from
/// public interface.
pub trait GetSubcommand: 'static {
    type State: ParserState;
    type Subcommand: Subcommand;
    fn get(state: &mut Self::State) -> &mut Option<Self::Subcommand>;
}

pub trait ParserStateDyn: 'static {
    /// Try to accept a named argument.
    ///
    /// If this parser accepts named argument `name`, return `Break(argument_place)`;
    /// otherwise, return `Continue(())`.
    ///
    /// `enc_name` is the encoded argument name to be matched on:
    /// - "-s" => "s"
    /// - "--long" => "long"
    /// - "--l" => "--l", to disambiguate from short arguments.
    fn feed_named(&mut self, _enc_name: &str) -> FeedNamed<'_> {
        ControlFlow::Continue(())
    }

    /// Try to accept an unnamed (positional) argument.
    ///
    /// `idx` is the index of logical arguments, counting each multi-value-argument as one.
    /// `is_last` indicates if a `--` has been encountered. It does not affect
    /// the increment of `idx`.
    fn feed_unnamed(&mut self, _arg: &OsStr, _idx: usize, _is_last: bool) -> FeedUnnamed<'_> {
        ControlFlow::Continue(())
    }

    /// Runtime reflection.
    fn info(&self) -> &'static RawArgsInfo {
        RawArgsInfo::EMPTY_REF
    }
}

/// Trait of subcommand enums.
///
/// This trait is in not public API. Only `derive(Subcommand)` is.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a `palc::Subcommand`",
    label = "this type is expected to have `derive(palc::Subcommand)` but it is not"
)]
#[doc(hidden)]
pub trait Subcommand: Sized + 'static {
    const RAW_INFO: &'static RawSubcommandInfo = RawSubcommandInfo::EMPTY_REF;

    fn feed_subcommand(_name: &OsStr) -> FeedSubcommand<Self> {
        None
    }

    fn try_parse_with_name(
        p: &mut RawParser,
        name: &OsStr,
        states: &mut dyn ParserChain,
    ) -> Result<Self> {
        let Some(f) = Self::feed_subcommand(name) else {
            return unknown_subcommand(name);
        };
        f(p, name, states)
    }
}

/// The fn signature of [`try_parse_state`], returned by [`Subcommand::feed_subcommand`].
pub type FeedSubcommand<T> =
    Option<fn(p: &mut RawParser, subcmd: &OsStr, states: &mut dyn ParserChain) -> Result<T>>;

#[cfg(test)]
fn _assert_feed_subcommand_ty<S: ParserState>() -> FeedSubcommand<S::Output> {
    Some(try_parse_state::<S>)
}

pub fn try_parse_state<S: ParserState>(
    p: &mut RawParser,
    cmd_name: &OsStr,
    ancestors: &mut dyn ParserChain,
) -> Result<S::Output> {
    let mut state = S::default();
    let node = &mut ParserChainNode { cmd_name, state: &mut state, ancestors };
    try_parse_state_dyn(p, node)?;
    state.finish()
}

/// The outlined main logic of parser.
#[inline(never)]
fn try_parse_state_dyn(p: &mut RawParser, chain: &mut ParserChainNode) -> Result<()> {
    let mut buf = OsString::new();

    let mut unnamed_idx = 0usize;

    while let Some(arg) = p.next_arg(&mut buf)? {
        match arg {
            Arg::EncodedNamed(enc_name, has_eq, value) => {
                let args_info = chain.state.info();
                let (place, attrs, args_info) = match chain.state.feed_named(enc_name) {
                    ControlFlow::Break((place, attrs)) => (place, attrs, args_info),
                    ControlFlow::Continue(()) => {
                        match chain.ancestors.feed_global_named(enc_name) {
                            ControlFlow::Break(ret) => ret,
                            ControlFlow::Continue(()) => {
                                // TODO: Configurable help?
                                #[cfg(feature = "help")]
                                if enc_name == "h" || enc_name == "help" {
                                    return Err(
                                        Error::from(ErrorKind::Help).maybe_render_help(chain)
                                    );
                                }
                                let mut dec_name = String::with_capacity(2 + enc_name.len());
                                // TODO: Dedup this code with `Error::fmt`.
                                if enc_name.chars().nth(1).is_none() {
                                    dec_name.push('-');
                                } else if !enc_name.starts_with("--") {
                                    dec_name.push_str("--");
                                }
                                dec_name.push_str(enc_name);
                                return Err(
                                    ErrorKind::UnknownNamedArgument.with_input(dec_name.into())
                                );
                            }
                        }
                    }
                };

                if attrs.contains(ArgAttrs::NO_VALUE) {
                    // Only fail on long arguments with inlined values `--long=value`.
                    if let Some(v) = value.filter(|_| enc_name.len() > 1) {
                        Err(ErrorKind::UnexpectedInlineValue.with_input(v.into()))
                    } else {
                        place.parse_from(p, attrs, "".as_ref(), "".as_ref(), &mut ())
                    }
                } else if attrs.contains(ArgAttrs::REQUIRE_EQ) && !has_eq {
                    Err(ErrorKind::MissingEq.into())
                } else if let Some(v) = value {
                    // Inlined value after `=`.
                    p.discard_short_args();
                    place.parse_from(p, attrs, v, "".as_ref(), &mut ())
                } else {
                    // Next argument as the value.
                    p.next_value(attrs).ok_or_else(|| ErrorKind::MissingValue.into()).and_then(
                        |mut v| {
                            if attrs.contains(ArgAttrs::MAKE_LOWERCASE) {
                                v.make_ascii_lowercase();
                            }
                            place.parse_from(p, attrs, &v, "".as_ref(), &mut ())
                        },
                    )
                }
                .map_err(
                    #[cold]
                    |err| {
                        let desc = args_info.get_description(attrs.get_index());
                        err.with_arg_desc(desc).maybe_render_help(chain)
                    },
                )?;
            }
            Arg::Unnamed(arg) => match chain.state.feed_unnamed(&arg, unnamed_idx, false) {
                ControlFlow::Break((place, attrs)) => {
                    unnamed_idx += 1;
                    place.parse_from(p, attrs, &arg, chain.cmd_name, chain.ancestors)?;
                }
                ControlFlow::Continue(()) => {
                    return Err(ErrorKind::ExtraUnnamedArgument.with_input(arg));
                }
            },
            Arg::DashDash => {
                drop(arg);
                drop(buf);
                while let Some(arg) = p.iter.next() {
                    match chain.state.feed_unnamed(&arg, unnamed_idx, true) {
                        ControlFlow::Break((place, attrs)) => {
                            unnamed_idx += 1;
                            place.parse_from(p, attrs, &arg, chain.cmd_name, chain.ancestors)?;
                        }
                        ControlFlow::Continue(()) => {
                            return Err(ErrorKind::ExtraUnnamedArgument.with_input(arg));
                        }
                    }
                }
                return Ok(());
            }
        }
    }
    Ok(())
}

pub struct RawParser<'i> {
    iter: &'i mut dyn Iterator<Item = OsString>,
    /// If we are inside a short arguments bundle, the index of next short arg.
    next_short_idx: Option<NonZero<usize>>,
}

#[derive(Debug)]
enum Arg<'a> {
    /// "--"
    DashDash,
    /// Encoded arg name, equal sign, and an inlined value (excluding `=`).
    ///
    /// - "--long" => ("long", None)
    /// - "--long=value" => ("long", Some("value"))
    /// - "-s" => ("s", None)
    /// - "-smore", "-s=more" => ("s", Some("more"))
    EncodedNamed(&'a str, bool, Option<&'a OsStr>),
    Unnamed(OsString),
}

impl<'i> RawParser<'i> {
    pub(crate) fn new(iter: &'i mut dyn Iterator<Item = OsString>) -> Self {
        Self { iter, next_short_idx: None }
    }

    /// Iterate the next logical argument, possibly splitting short argument bundle.
    fn next_arg<'b>(&mut self, buf: &'b mut OsString) -> Result<Option<Arg<'b>>> {
        #[cold]
        fn fail_on_next_short_arg(rest: &OsStr) -> Error {
            let bytes = rest.as_encoded_bytes();

            // UTF-8 length of a char must be 1..=4, len==1 case is checked outside.
            for len in 2..=bytes.len().min(4) {
                if let Ok(s) = std::str::from_utf8(&bytes[..len]) {
                    let mut dec_input = String::with_capacity(4);
                    dec_input.push('-');
                    dec_input.push_str(s);
                    return ErrorKind::UnknownNamedArgument.with_input(dec_input.into());
                }
            }
            ErrorKind::InvalidUtf8.with_input(rest.into())
        }

        if let Some(pos) = self.next_short_idx.filter(|pos| pos.get() < buf.len()) {
            let argb = buf.as_encoded_bytes();
            let idx = pos.get();

            // By struct invariant, argb[..idx] must be UTF-8.
            let next_byte = std::str::from_utf8(&argb[idx..idx + 1]);
            // Assuming all valid short args are ASCII, if the next byte is not ASCII, it must fail.
            let short_arg = next_byte.map_err(|_| fail_on_next_short_arg(buf.index(idx..)))?;

            self.next_short_idx = pos.checked_add(1);
            let (has_eq, value) = match argb.get(idx + 1) {
                Some(&b'=') => (true, Some(buf.index(idx + 2..))),
                Some(_) => (false, Some(buf.index(idx + 1..))),
                None => {
                    // Reached the end of bundle.
                    self.discard_short_args();
                    (false, None)
                }
            };
            return Ok(Some(Arg::EncodedNamed(short_arg, has_eq, value)));
        }
        self.next_short_idx = None;

        // Otherwise, fetch the next input argument.
        *buf = match self.iter.next() {
            Some(raw) => raw,
            None => return Ok(None),
        };

        if buf.starts_with("--") {
            if buf.len() == 2 {
                return Ok(Some(Arg::DashDash));
            }
            // Using `strip_prefix` in if-condition requires polonius to make lifetime check.
            let rest = buf.index(2..);
            let (name, has_eq, value) = match rest.split_once('=') {
                Some((name, value)) => (name, true, Some(value)),
                None => (rest, false, None),
            };
            // Include proceeding "--" only for single-char long arguments.
            let enc_name = if name.len() != 1 { name } else { buf.index(..3) };
            let enc_name = enc_name
                .to_str()
                .ok_or_else(|| ErrorKind::InvalidUtf8.with_input(enc_name.into()))?;
            Ok(Some(Arg::EncodedNamed(enc_name, has_eq, value)))
        } else if buf.starts_with("-") && buf.len() != 1 {
            self.next_short_idx = Some(NonZero::new(1).unwrap());
            self.next_arg(buf)
        } else {
            Ok(Some(Arg::Unnamed(std::mem::take(buf))))
        }
    }

    /// Discard the rest of short argument bundle, poll a new raw argument on next `next_arg`.
    fn discard_short_args(&mut self) {
        self.next_short_idx = None;
    }

    fn next_value(&mut self, attrs: ArgAttrs) -> Option<OsString> {
        assert!(self.next_short_idx.is_none());
        self.iter.next().filter(|raw| {
            let raw = raw.as_encoded_bytes();
            if raw == b"-" || !raw.starts_with(b"-") {
                return true;
            }
            if attrs.contains(ArgAttrs::ACCEPT_HYPHEN_ANY) {
                true
            } else if attrs.contains(ArgAttrs::ACCEPT_HYPHEN_NUM) {
                raw[1..].iter().all(|b| b.is_ascii_digit())
            } else {
                false
            }
        })
    }
}