Skip to main content

bpaf/
error.rs

1use std::ops::Range;
2
3use crate::{
4    args::{Arg, State},
5    buffer::{Block, Color, Doc, Style, Token},
6    item::{Item, ShortLong},
7    meta_help::Metavar,
8    meta_youmean::{Suggestion, Variant},
9    Meta,
10};
11
12/// Unsuccessful command line parsing outcome, internal representation
13#[derive(Debug)]
14pub struct Error(pub(crate) Message);
15
16impl Error {
17    pub(crate) fn combine_with(self, other: Self) -> Self {
18        Error(self.0.combine_with(other.0))
19    }
20}
21
22#[derive(Debug)]
23pub(crate) enum Message {
24    // those can be caught ---------------------------------------------------------------
25    /// Tried to consume an env variable with no fallback, variable was not set
26    NoEnv(&'static str),
27
28    /// User specified an error message on some
29    ParseSome(&'static str),
30
31    /// User asked for parser to fail explicitly
32    ParseFail(&'static str),
33
34    /// pure_with failed to parse a value
35    PureFailed(String),
36
37    /// Expected one of those values
38    ///
39    /// Used internally to generate better error messages
40    Missing(Vec<MissingItem>),
41
42    // those cannot be caught-------------------------------------------------------------
43    /// Parsing failed and this is the final output
44    ParseFailure(ParseFailure),
45
46    /// Tried to consume a strict positional argument, value was present but was not strictly
47    /// positional
48    StrictPos(usize, Metavar),
49
50    /// Tried to consume a non-strict positional argument, but the value was strict
51    NonStrictPos(usize, Metavar),
52
53    /// Parser provided by user failed to parse a value
54    ParseFailed(Option<usize>, String),
55
56    /// Parser provided by user failed to parse a value taken from an environment variable
57    EnvParseFailed(&'static str, String),
58
59    /// Parser provided by user failed to validate a value
60    GuardFailed(Option<usize>, &'static str),
61
62    /// Argument requres a value but something else was passed,
63    /// required: --foo <BAR>
64    /// given: --foo --bar
65    ///        --foo -- bar
66    ///        --foo
67    NoArgument(usize, Metavar),
68
69    /// Parser is expected to consume all the things from the command line
70    /// this item will contain an index of the unconsumed value
71    Unconsumed(/* TODO - unused? */ usize),
72
73    /// argument is ambigoups - parser can accept it as both a set of flags and a short flag with no =
74    Ambiguity(usize, String),
75
76    /// Suggested fixes for typos or missing input
77    Suggestion(usize, Suggestion),
78
79    /// Two arguments are mutually exclusive
80    /// --release --dev
81    Conflict(/* winner */ usize, usize),
82
83    /// Expected one or more items in the scope, got someting else if any
84    Expected(Vec<Item>, Option<usize>),
85
86    /// Parameter is accepted but only once
87    OnlyOnce(/* winner */ usize, usize),
88}
89
90impl Message {
91    pub(crate) fn can_catch(&self) -> bool {
92        match self {
93            Message::NoEnv(_)
94            | Message::ParseSome(_)
95            | Message::ParseFail(_)
96            | Message::Missing(_)
97            | Message::PureFailed(_)
98            | Message::NonStrictPos(_, _) => true,
99            Message::StrictPos(_, _)
100            | Message::ParseFailed(_, _)
101            | Message::EnvParseFailed(_, _)
102            | Message::GuardFailed(_, _)
103            | Message::Unconsumed(_)
104            | Message::Ambiguity(_, _)
105            | Message::Suggestion(_, _)
106            | Message::Conflict(_, _)
107            | Message::ParseFailure(_)
108            | Message::Expected(_, _)
109            | Message::OnlyOnce(_, _)
110            | Message::NoArgument(_, _) => false,
111        }
112    }
113
114    /// A list of errors that `catch` can't catch
115    pub(crate) fn wrong_input(&self) -> bool {
116        matches!(
117            self,
118            Message::StrictPos(_, _)
119                | Message::NonStrictPos(_, _)
120                | Message::NoArgument(_, _)
121                | Message::Unconsumed(_)
122                | Message::Ambiguity(_, _)
123        )
124    }
125}
126
127/// Missing item in a context
128#[derive(Debug, Clone)]
129pub struct MissingItem {
130    /// Item that is missing
131    pub(crate) item: Item,
132    /// Position it is missing from - exact for positionals, earliest possible for flags
133    pub(crate) position: usize,
134    /// Range where search was performed, important for combinators that narrow the search scope
135    /// such as adjacent
136    pub(crate) scope: Range<usize>,
137}
138
139impl Message {
140    #[must_use]
141    pub(crate) fn combine_with(self, other: Self) -> Self {
142        #[allow(clippy::match_same_arms)]
143        match (self, other) {
144            // help output takes priority
145            (a @ Message::ParseFailure(_), _) => a,
146            (_, b @ Message::ParseFailure(_)) => b,
147
148            // combine missing elements
149            (Message::Missing(mut a), Message::Missing(mut b)) => {
150                a.append(&mut b);
151                Message::Missing(a)
152            }
153
154            // otherwise earliest wins
155            (a, b) => {
156                if a.can_catch() {
157                    b
158                } else {
159                    a
160                }
161            }
162        }
163    }
164}
165
166/// Unsuccessful command line parsing outcome, use it for unit tests
167///
168/// When [`OptionParser::run_inner`](crate::OptionParser::run_inner) produces `Err(ParseFailure)`
169/// it means that the parser couldn't produce the value it supposed to produce and the program
170/// should terminate.
171///
172/// If you are handling variants manually - `Stdout` contains formatted output and you can use any
173/// logging framework to produce the output, `Completion` should be printed to stdout unchanged -
174/// shell completion mechanism relies on that. In both cases application should exit with error
175/// code of 0. `Stderr` variant indicates a genuinly parsing error which should be printed to
176/// stderr or a logging framework of your choice as an error and the app should exit with error
177/// code of 1. [`ParseFailure::exit_code`] is a helper method that performs printing and produces
178/// the exit code to use.
179///
180/// For purposes of for unit testing for user parsers, you can consume it with
181/// [`ParseFailure::unwrap_stdout`] and [`ParseFailure::unwrap_stdout`] - both of which produce a
182/// an unformatted `String` that parser might produce if failure type is correct or panics
183/// otherwise.
184#[derive(Clone, Debug)]
185pub enum ParseFailure {
186    /// Print this to stdout and exit with success code
187    Stdout(Doc, bool),
188    /// This also goes to stdout with exit code of 0,
189    /// this cannot be Doc because completion needs more control about rendering
190    Completion(String),
191    /// Print this to stderr and exit with failure code
192    Stderr(Doc),
193}
194
195impl ParseFailure {
196    /// Returns the contained `stderr` values - for unit tests
197    ///
198    /// # Panics
199    ///
200    /// Panics if failure contains `stdout`
201    #[allow(clippy::must_use_candidate)]
202    #[track_caller]
203    pub fn unwrap_stderr(self) -> String {
204        match self {
205            Self::Stderr(err) => err.monochrome(true),
206            Self::Completion(..) | Self::Stdout(..) => panic!("not an stderr: {:?}", self),
207        }
208    }
209
210    /// Returns the contained `stdout` values - for unit tests
211    ///
212    /// # Panics
213    ///
214    /// Panics if failure contains `stderr`
215    #[allow(clippy::must_use_candidate)]
216    #[track_caller]
217    pub fn unwrap_stdout(self) -> String {
218        match self {
219            Self::Stdout(err, full) => err.monochrome(full),
220            Self::Completion(s) => s,
221            Self::Stderr(..) => panic!("not an stdout: {:?}", self),
222        }
223    }
224
225    /// Returns the exit code for the failure
226    #[allow(clippy::must_use_candidate)]
227    pub fn exit_code(self) -> i32 {
228        match self {
229            Self::Stdout(..) | Self::Completion(..) => 0,
230            Self::Stderr(..) => 1,
231        }
232    }
233
234    #[doc(hidden)]
235    #[deprecated = "Please use ParseFailure::print_message, with two s"]
236    pub fn print_mesage(&self, max_width: usize) {
237        self.print_message(max_width)
238    }
239
240    /// Prints a message to `stdout` or `stderr` appropriate to the failure.
241    pub fn print_message(&self, max_width: usize) {
242        let color = Color::default();
243        match self {
244            ParseFailure::Stdout(msg, full) => {
245                println!("{}", msg.render_console(*full, color, max_width));
246            }
247            ParseFailure::Completion(s) => {
248                print!("{}", s);
249            }
250            ParseFailure::Stderr(msg) => {
251                #[allow(unused_mut)]
252                let mut error;
253                #[cfg(not(feature = "color"))]
254                {
255                    error = "Error: ";
256                }
257
258                #[cfg(feature = "color")]
259                {
260                    error = String::new();
261                    color.push_str(Style::Invalid, &mut error, "Error: ");
262                }
263
264                eprintln!("{}{}", error, msg.render_console(true, color, max_width));
265            }
266        }
267    }
268}
269
270fn check_conflicts(args: &State) -> Option<Message> {
271    let (loser, winner) = args.conflict()?;
272    Some(Message::Conflict(winner, loser))
273}
274
275fn textual_part(args: &State, ix: Option<usize>) -> Option<std::borrow::Cow<'_, str>> {
276    match args.items.get(ix?)? {
277        Arg::Short(_, _, _) | Arg::Long(_, _, _) => None,
278        Arg::ArgWord(s) | Arg::Word(s) | Arg::PosWord(s) => Some(s.to_string_lossy()),
279    }
280}
281
282fn only_once(args: &State, cur: usize) -> Option<usize> {
283    if cur == 0 {
284        return None;
285    }
286    let mut iter = args.items[..cur].iter().rev();
287    let offset = match args.items.get(cur)? {
288        Arg::Short(s, _, _) => iter.position(|a| a.match_short(*s)),
289        Arg::Long(l, _, _) => iter.position(|a| a.match_long(l)),
290        Arg::ArgWord(_) | Arg::Word(_) | Arg::PosWord(_) => None,
291    };
292    Some(cur - offset? - 1)
293}
294
295impl Message {
296    #[allow(clippy::too_many_lines)] // it's a huge match with lots of simple cases
297    pub(crate) fn render(mut self, args: &State, meta: &Meta) -> ParseFailure {
298        // try to come up with a better error message for a few cases
299        match self {
300            Message::Unconsumed(ix) => {
301                if let Some(conflict) = check_conflicts(args) {
302                    self = conflict;
303                } else if let Some(prev_ix) = only_once(args, ix) {
304                    self = Message::OnlyOnce(prev_ix, ix);
305                } else if let Some((ix, suggestion)) = crate::meta_youmean::suggest(args, meta) {
306                    self = Message::Suggestion(ix, suggestion);
307                }
308            }
309            Message::Missing(xs) => {
310                self = summarize_missing(&xs, meta, args);
311            }
312            _ => {}
313        }
314
315        let mut doc = Doc::default();
316        match self {
317            // already rendered
318            Message::ParseFailure(f) => return f,
319
320            // this case is handled above
321            Message::Missing(_) => {
322                // this one is unreachable
323            }
324
325            // Error: --foo is not expected in this context
326            Message::Unconsumed(ix) => {
327                let item = &args.items[ix];
328                doc.token(Token::BlockStart(Block::TermRef));
329                doc.write(item, Style::Invalid);
330                doc.token(Token::BlockEnd(Block::TermRef));
331                doc.text(" is not expected in this context");
332            }
333
334            // Error: environment variable FOO is not set
335            Message::NoEnv(name) => {
336                doc.text("environment variable ");
337                doc.token(Token::BlockStart(Block::TermRef));
338                doc.invalid(name);
339                doc.token(Token::BlockEnd(Block::TermRef));
340                doc.text(" is not set");
341            }
342
343            // Error: FOO expected to be  in the right side of --
344            Message::StrictPos(_ix, metavar) => {
345                doc.text("expected ");
346                doc.token(Token::BlockStart(Block::TermRef));
347                doc.metavar(metavar);
348                doc.token(Token::BlockEnd(Block::TermRef));
349                doc.text(" to be on the right side of ");
350                doc.token(Token::BlockStart(Block::TermRef));
351                doc.literal("--");
352                doc.token(Token::BlockEnd(Block::TermRef));
353            }
354
355            // Error: FOO expected to be on the left side of --
356            Message::NonStrictPos(_ix, metavar) => {
357                doc.text("expected ");
358                doc.token(Token::BlockStart(Block::TermRef));
359                doc.metavar(metavar);
360                doc.token(Token::BlockEnd(Block::TermRef));
361                doc.text(" to be on the left side of ");
362                doc.token(Token::BlockStart(Block::TermRef));
363                doc.literal("--");
364                doc.token(Token::BlockEnd(Block::TermRef));
365            }
366
367            // Error: <message from some or fail>
368            Message::ParseSome(s) | Message::ParseFail(s) => {
369                doc.text(s);
370            }
371
372            // Error: couldn't parse FIELD: <FromStr message>
373            Message::ParseFailed(mix, s) => {
374                doc.text("couldn't parse");
375                if let Some(field) = textual_part(args, mix) {
376                    doc.text(" ");
377                    doc.token(Token::BlockStart(Block::TermRef));
378                    if field.is_empty() {
379                        let mut s = String::new();
380                        if let Some(ix) = mix {
381                            if ix > 0 {
382                                if let Some(arg) = args.items.get(ix - 1) {
383                                    use std::fmt::Write as _;
384                                    match arg {
385                                        Arg::Short(n, true, _) => _ = write!(&mut s, "-{n}="),
386                                        Arg::Short(n, false, _) => _ = write!(&mut s, "-{n} "),
387                                        Arg::Long(l, false, _) => _ = write!(&mut s, "--{l} "),
388                                        Arg::Long(l, true, _) => _ = write!(&mut s, "--{l}="),
389                                        _ => {}
390                                    }
391                                }
392                            }
393                        }
394                        s.push_str(r#""""#);
395                        doc.invalid(&s);
396                    } else {
397                        doc.invalid(&field);
398                    }
399                    doc.token(Token::BlockEnd(Block::TermRef));
400                }
401                doc.text(": ");
402                doc.text(&s);
403            }
404
405            // Error: couldn't parse the value of environment variable FOO: <FromStr message>
406            Message::EnvParseFailed(name, s) => {
407                doc.text("couldn't parse the value of environment variable ");
408                doc.token(Token::BlockStart(Block::TermRef));
409                doc.invalid(name);
410                doc.token(Token::BlockEnd(Block::TermRef));
411                doc.text(": ");
412                doc.text(&s);
413            }
414
415            // Error: ( FIELD:  | check failed: ) <message from guard>
416            Message::GuardFailed(mix, s) => {
417                if let Some(field) = textual_part(args, mix) {
418                    doc.token(Token::BlockStart(Block::TermRef));
419                    doc.invalid(&field);
420                    doc.token(Token::BlockEnd(Block::TermRef));
421                    doc.text(": ");
422                } else {
423                    doc.text("check failed: ");
424                }
425                doc.text(s);
426            }
427
428            // Error: --foo requires an argument FOO, got a flag --bar, try --foo=-bar to use it as an argument
429            // Error: --foo requires an argument FOO
430            Message::NoArgument(x, mv) => match args.get(x + 1) {
431                Some(Arg::Short(_, _, os) | Arg::Long(_, _, os)) => {
432                    let arg = &args.items[x];
433                    let os = &os.to_string_lossy();
434
435                    doc.token(Token::BlockStart(Block::TermRef));
436                    doc.write(arg, Style::Literal);
437                    doc.token(Token::BlockEnd(Block::TermRef));
438                    doc.text(" requires an argument ");
439                    doc.token(Token::BlockStart(Block::TermRef));
440                    doc.metavar(mv);
441                    doc.token(Token::BlockEnd(Block::TermRef));
442                    doc.text(", got a flag ");
443                    doc.token(Token::BlockStart(Block::TermRef));
444                    doc.write(os, Style::Invalid);
445                    doc.token(Token::BlockEnd(Block::TermRef));
446                    doc.text(", try ");
447                    doc.token(Token::BlockStart(Block::TermRef));
448                    doc.write(arg, Style::Literal);
449                    doc.literal("=");
450                    doc.write(os, Style::Literal);
451                    doc.token(Token::BlockEnd(Block::TermRef));
452                    doc.text(" to use it as an argument");
453                }
454                // "Some" part of this branch is actually unreachable
455                Some(Arg::ArgWord(_) | Arg::Word(_) | Arg::PosWord(_)) | None => {
456                    let arg = &args.items[x];
457                    doc.token(Token::BlockStart(Block::TermRef));
458                    doc.write(arg, Style::Literal);
459                    doc.token(Token::BlockEnd(Block::TermRef));
460                    doc.text(" requires an argument ");
461                    doc.token(Token::BlockStart(Block::TermRef));
462                    doc.metavar(mv);
463                    doc.token(Token::BlockEnd(Block::TermRef));
464                }
465            },
466            // Error: <message from pure_with>
467            Message::PureFailed(s) => {
468                doc.text(&s);
469            }
470            // Error: app supports -f as both an option and an option-argument, try to split -foo
471            // into invididual options (-f -o ..) or use -f=oo syntax to disambiguate
472            Message::Ambiguity(ix, name) => {
473                let mut chars = name.chars();
474                let first = chars.next().unwrap();
475                let rest = chars.as_str();
476                let second = chars.next().unwrap();
477                let s = args.items[ix].os_str().to_str().unwrap();
478
479                if let Some(name) = args.path.first() {
480                    doc.literal(name);
481                    doc.text(" supports ");
482                } else {
483                    doc.text("app supports ");
484                }
485
486                doc.token(Token::BlockStart(Block::TermRef));
487                doc.literal("-");
488                doc.write_char(first, Style::Literal);
489                doc.token(Token::BlockEnd(Block::TermRef));
490                doc.text(" as both an option and an option-argument, try to split ");
491                doc.token(Token::BlockStart(Block::TermRef));
492                doc.write(s, Style::Literal);
493                doc.token(Token::BlockEnd(Block::TermRef));
494                doc.text(" into individual options (");
495                doc.literal("-");
496                doc.write_char(first, Style::Literal);
497                doc.literal(" -");
498                doc.write_char(second, Style::Literal);
499                doc.literal(" ..");
500                doc.text(") or use ");
501                doc.token(Token::BlockStart(Block::TermRef));
502                doc.literal("-");
503                doc.write_char(first, Style::Literal);
504                doc.literal("=");
505                doc.literal(rest);
506                doc.token(Token::BlockEnd(Block::TermRef));
507                doc.text(" syntax to disambiguate");
508            }
509            // Error: No such (flag|argument|command), did you mean  ...
510            Message::Suggestion(ix, suggestion) => {
511                let actual = &args.items[ix].to_string();
512                match suggestion {
513                    Suggestion::Variant(v) => {
514                        let ty = match &args.items[ix] {
515                            _ if actual.starts_with('-') => "flag",
516                            Arg::Short(_, _, _) | Arg::Long(_, _, _) => "flag",
517                            Arg::ArgWord(_) => "argument value",
518                            Arg::Word(_) | Arg::PosWord(_) => "command or positional",
519                        };
520
521                        doc.text("no such ");
522                        doc.text(ty);
523                        doc.text(": ");
524                        doc.token(Token::BlockStart(Block::TermRef));
525                        doc.invalid(actual);
526                        doc.token(Token::BlockEnd(Block::TermRef));
527                        doc.text(", did you mean ");
528                        doc.token(Token::BlockStart(Block::TermRef));
529
530                        match v {
531                            Variant::CommandLong(name) => doc.literal(name),
532                            Variant::Flag(ShortLong::Long(l) | ShortLong::Both(_, l)) => {
533                                doc.literal("--");
534                                doc.literal(l);
535                            }
536                            Variant::Flag(ShortLong::Short(s)) => {
537                                doc.literal("-");
538                                doc.write_char(s, Style::Literal);
539                            }
540                        };
541
542                        doc.token(Token::BlockEnd(Block::TermRef));
543                        doc.text("?");
544                    }
545                    Suggestion::MissingDash(name) => {
546                        doc.text("no such flag: ");
547                        doc.token(Token::BlockStart(Block::TermRef));
548                        doc.literal("-");
549                        doc.literal(name);
550                        doc.token(Token::BlockEnd(Block::TermRef));
551                        doc.text(" (with one dash), did you mean ");
552                        doc.token(Token::BlockStart(Block::TermRef));
553                        doc.literal("--");
554                        doc.literal(name);
555                        doc.token(Token::BlockEnd(Block::TermRef));
556                        doc.text("?");
557                    }
558                    Suggestion::ExtraDash(name) => {
559                        doc.text("no such flag: ");
560                        doc.token(Token::BlockStart(Block::TermRef));
561                        doc.literal("--");
562                        doc.write_char(name, Style::Literal);
563                        doc.token(Token::BlockEnd(Block::TermRef));
564                        doc.text(" (with two dashes), did you mean ");
565                        doc.token(Token::BlockStart(Block::TermRef));
566                        doc.literal("-");
567                        doc.write_char(name, Style::Literal);
568                        doc.token(Token::BlockEnd(Block::TermRef));
569                        doc.text("?");
570                    }
571                    Suggestion::Nested(x, v) => {
572                        let ty = match v {
573                            Variant::CommandLong(_) => "subcommand",
574                            Variant::Flag(_) => "flag",
575                        };
576                        doc.text(ty);
577                        doc.text(" ");
578                        doc.token(Token::BlockStart(Block::TermRef));
579                        doc.literal(actual);
580                        doc.token(Token::BlockEnd(Block::TermRef));
581                        doc.text(
582                            " is not valid in this context, did you mean to pass it to command ",
583                        );
584                        doc.token(Token::BlockStart(Block::TermRef));
585                        doc.literal(&x);
586                        doc.token(Token::BlockEnd(Block::TermRef));
587                        doc.text("?");
588                    }
589                }
590            }
591            // Error: Expected (no arguments|--foo), got ..., pass --help
592            Message::Expected(exp, actual) => {
593                doc.text("expected ");
594                match exp.len() {
595                    0 => {
596                        doc.text("no arguments");
597                    }
598                    1 => {
599                        doc.token(Token::BlockStart(Block::TermRef));
600                        doc.write_item(&exp[0]);
601                        doc.token(Token::BlockEnd(Block::TermRef));
602                    }
603                    2 => {
604                        doc.token(Token::BlockStart(Block::TermRef));
605                        doc.write_item(&exp[0]);
606                        doc.token(Token::BlockEnd(Block::TermRef));
607                        doc.text(" or ");
608                        doc.token(Token::BlockStart(Block::TermRef));
609                        doc.write_item(&exp[1]);
610                        doc.token(Token::BlockEnd(Block::TermRef));
611                    }
612                    _ => {
613                        doc.token(Token::BlockStart(Block::TermRef));
614                        doc.write_item(&exp[0]);
615                        doc.token(Token::BlockEnd(Block::TermRef));
616                        doc.text(", ");
617                        doc.token(Token::BlockStart(Block::TermRef));
618                        doc.write_item(&exp[1]);
619                        doc.token(Token::BlockEnd(Block::TermRef));
620                        doc.text(", or more");
621                    }
622                }
623                match actual {
624                    Some(actual) => {
625                        doc.text(", got ");
626                        doc.token(Token::BlockStart(Block::TermRef));
627                        doc.write(&args.items[actual], Style::Invalid);
628                        doc.token(Token::BlockEnd(Block::TermRef));
629                        doc.text(". Pass ");
630                    }
631                    None => {
632                        doc.text(", pass ");
633                    }
634                }
635                doc.token(Token::BlockStart(Block::TermRef));
636                doc.literal("--help");
637                doc.token(Token::BlockEnd(Block::TermRef));
638                doc.text(" for usage information");
639            }
640
641            // Error: --intel cannot be used at the same time as --att
642            Message::Conflict(winner, loser) => {
643                doc.token(Token::BlockStart(Block::TermRef));
644                doc.write(&args.items[loser], Style::Literal);
645                doc.token(Token::BlockEnd(Block::TermRef));
646                doc.text(" cannot be used at the same time as ");
647                doc.token(Token::BlockStart(Block::TermRef));
648                doc.write(&args.items[winner], Style::Literal);
649                doc.token(Token::BlockEnd(Block::TermRef));
650            }
651
652            // Error: argument FOO cannot be used multiple times in this context
653            Message::OnlyOnce(_winner, loser) => {
654                doc.text("argument ");
655                doc.token(Token::BlockStart(Block::TermRef));
656                doc.write(&args.items[loser], Style::Literal);
657                doc.token(Token::BlockEnd(Block::TermRef));
658                doc.text(" cannot be used multiple times in this context");
659            }
660        };
661
662        ParseFailure::Stderr(doc)
663    }
664}
665
666/// go over all the missing items, pick the left most scope
667pub(crate) fn summarize_missing(items: &[MissingItem], inner: &Meta, args: &State) -> Message {
668    // missing items can belong to different scopes, pick the best scope to work with
669    let best_item = match items
670        .iter()
671        .max_by_key(|item| (item.position, item.scope.start))
672    {
673        Some(x) => x,
674        None => return Message::ParseSome("parser requires an extra flag, argument or parameter, but its name is hidden by the author"),
675    };
676
677    let mut best_scope = best_item.scope.clone();
678
679    let mut saw_command = false;
680    let expected = items
681        .iter()
682        .filter_map(|i| {
683            let cmd = matches!(i.item, Item::Command { .. });
684            if i.scope == best_scope && !(saw_command && cmd) {
685                saw_command |= cmd;
686                Some(i.item.clone())
687            } else {
688                None
689            }
690        })
691        .collect::<Vec<_>>();
692
693    best_scope.start = best_scope.start.max(best_item.position);
694    let mut args = args.clone();
695    args.set_scope(best_scope);
696    if let Some((ix, _arg)) = args.items_iter().next() {
697        if let Some((ix, sugg)) = crate::meta_youmean::suggest(&args, inner) {
698            Message::Suggestion(ix, sugg)
699        } else {
700            Message::Expected(expected, Some(ix))
701        }
702    } else {
703        Message::Expected(expected, None)
704    }
705}
706
707/*
708#[inline(never)]
709/// the idea is to post some context for the error
710fn snip(buffer: &mut Buffer, args: &State, items: &[usize]) {
711    for ix in args.scope() {
712        buffer.write(ix, Style::Text);
713    }
714}
715*/