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#[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 NoEnv(&'static str),
27
28 ParseSome(&'static str),
30
31 ParseFail(&'static str),
33
34 PureFailed(String),
36
37 Missing(Vec<MissingItem>),
41
42 ParseFailure(ParseFailure),
45
46 StrictPos(usize, Metavar),
49
50 NonStrictPos(usize, Metavar),
52
53 ParseFailed(Option<usize>, String),
55
56 EnvParseFailed(&'static str, String),
58
59 GuardFailed(Option<usize>, &'static str),
61
62 NoArgument(usize, Metavar),
68
69 Unconsumed(usize),
72
73 Ambiguity(usize, String),
75
76 Suggestion(usize, Suggestion),
78
79 Conflict(usize, usize),
82
83 Expected(Vec<Item>, Option<usize>),
85
86 OnlyOnce(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 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#[derive(Debug, Clone)]
129pub struct MissingItem {
130 pub(crate) item: Item,
132 pub(crate) position: usize,
134 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 (a @ Message::ParseFailure(_), _) => a,
146 (_, b @ Message::ParseFailure(_)) => b,
147
148 (Message::Missing(mut a), Message::Missing(mut b)) => {
150 a.append(&mut b);
151 Message::Missing(a)
152 }
153
154 (a, b) => {
156 if a.can_catch() {
157 b
158 } else {
159 a
160 }
161 }
162 }
163 }
164}
165
166#[derive(Clone, Debug)]
185pub enum ParseFailure {
186 Stdout(Doc, bool),
188 Completion(String),
191 Stderr(Doc),
193}
194
195impl ParseFailure {
196 #[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 #[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 #[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 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)] pub(crate) fn render(mut self, args: &State, meta: &Meta) -> ParseFailure {
298 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 Message::ParseFailure(f) => return f,
319
320 Message::Missing(_) => {
322 }
324
325 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 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 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 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 Message::ParseSome(s) | Message::ParseFail(s) => {
369 doc.text(s);
370 }
371
372 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 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 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 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(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 Message::PureFailed(s) => {
468 doc.text(&s);
469 }
470 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 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 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 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 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
666pub(crate) fn summarize_missing(items: &[MissingItem], inner: &Meta, args: &State) -> Message {
668 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