1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
use crate::command::{Command, Completion};
use crate::command_set::CommandSet;
use crate::error::ShiError;
use crate::shell::Shell;
use crate::tokenizer::{DefaultTokenizer, Tokenization, Tokenizer};

/// A parser that parses input lines into `Command` invocations.
pub struct Parser {
    tokenizer: DefaultTokenizer,
}

#[derive(Debug, PartialEq)]
/// CommandType represents part of a parse result. A parse attempt for a command will result in a
/// decision on whether a given input line represents a `Builtin` command, a `Custom` command, or
/// `Unknown`, in the case of an unsuccessful or incomplete parse.
pub enum CommandType {
    Builtin,
    Custom,
    Unknown,
}

#[derive(Debug, PartialEq)]
/// Outcome is the final result of a parse attempt. It includes various useful bits of information
/// from the parse:
///
/// * `cmd_path` - The components of the command invocation. In particular, it shows the chain of
/// ancestry in terms of `Parent` commands and the eventual `Leaf` command.
/// * `remaining` - The remaining components of the string. In the case of a successful parse, this
/// represents the arguments passed to the command. In the case of unsuccessful or incomplete
/// parses, this represents the part of the input string that was not able to be parsed.
/// * `cmd_type` - The type of the command. See `CommandType`.
/// * `possibilities` - Includes the potential candidates that the parser is expecting to see
/// following the input line.
/// * `complete` - A flag denoting whether we had a successful and complete parse.
pub struct Outcome<'a> {
    pub cmd_path: Vec<&'a str>,
    pub remaining: Vec<&'a str>,
    pub cmd_type: CommandType,
    pub possibilities: Vec<String>,
    pub leaf_completion: Option<Completion>,
    pub complete: bool,
}

impl<'a> Outcome<'a> {
    pub fn error(&self) -> Option<ShiError> {
        if !self.complete {
            Some(ShiError::ParseError {
                msg: self.error_msg(),
                cmd_path: self.cmd_path.iter().map(|s| s.to_string()).collect(),
                remaining: self.remaining.iter().map(|s| s.to_string()).collect(),
                possibilities: self.possibilities.clone(),
            })
        } else {
            None
        }
    }

    /// Prints an error message for the `Outcome`. Of course, if the `Outcome` was complete, the
    /// error message is empty.
    pub fn error_msg(&self) -> String {
        // TODO: We should split apart this function.

        // If we parsed successfully, we obviously shouldn't produce an error message.
        if self.complete {
            return String::from("");
        }

        // This will be our String buffer.
        let mut msg = String::new();

        if self.cmd_path.is_empty() && self.remaining.is_empty() {
            // In this case, we must have found an empty string, which is obviously not parseable
            // as a command.
            msg += "Empty string could not be parsed as a command.";
        } else if self.cmd_path.is_empty() {
            // If the `cmd_path` is empty, this implies we immediately failed the parse, and it was
            // not at least partially complete. This then implies that the first element of the
            // remaining components must be the thing we failed to parse as a recognized command.
            if let Some(first_remaining_word) = self.remaining.get(0) {
                msg.push_str(&format!(
                    "'{}' is not a recognized command.",
                    first_remaining_word
                ));
            } else {
                // This should not be possible. If the remaining tokens were empty, then the prior
                // if case should have caught it.
                unreachable!("remaining unparsed tokens cannot be empty at this point")
            }
        } else {
            msg += "Failed to parse fully:\n";
            msg += "\n";

            let valid_prefix = self.cmd_path.join(" ");
            let invalid_suffix = self.remaining.join(" ");
            msg += "\t    (spaces trimmed)\n";
            if self.remaining.is_empty() {
                msg += &format!("\t => '{}  '\n", valid_prefix);
                msg += &format!("\t     {}^\n", " ".repeat(valid_prefix.len() + 1));
            } else {
                msg += &format!("\t => '{} {}'\n", valid_prefix, invalid_suffix);
                msg += &format!("\t     {}^\n", " ".repeat(valid_prefix.len() + 1));
            }

            msg += "expected a valid subcommand\n";
            msg += "instead, got: ";
            if let Some(first_remaining_word) = self.remaining.get(0) {
                msg += &format!("'{}';\n", first_remaining_word);
            } else {
                msg += "nothing;\n"
            }

            msg += "\n";
            msg.push_str(&format!(
                "Run '{} help' for more info on the command.",
                valid_prefix
            ));
        }

        if !self.possibilities.is_empty() {
            msg += "\n\n";
            msg.push_str(&format!(
                "\t => expected one of {}.\n",
                self.possibilities
                    .iter()
                    .map(|s| format!("'{}'", s))
                    .collect::<Vec<String>>()
                    .join(" or ")
            ))
        }

        msg += "\n";
        msg += "Run 'helptree' for more info on the entire command tree.\n";

        msg
    }
}

impl Parser {
    /// Constructs a new Parser.
    pub fn new() -> Parser {
        Parser {
            tokenizer: DefaultTokenizer::new(vec!['\'', '"']),
        }
    }

    /// Parses a given Vector of tokens into a parse `Outcome`.
    ///
    /// # Arguments
    /// `tokens` - The tokens produced from an input line.
    /// `cmd_type` - The type of command contained in `set`. See `CommandType`.
    /// `set` - The available commands to parse into.
    ///
    /// # Returns
    /// `Outcome` - The parse outcome, given the arguments.
    fn parse_tokens_with_set<'a, T>(
        &self,
        tokenization: &Tokenization<'a>,
        cmd_type: CommandType,
        set: &CommandSet<T>,
    ) -> Outcome<'a> {
        let mut cmd_path: Vec<&str> = Vec::new();
        let mut current_set = set;
        for (i, token) in tokenization.tokens.iter().enumerate() {
            // Try looking up the token in our set.
            let looked_up_cmd = match current_set.get(token) {
                Some(cmd) => {
                    cmd_path.push(token);
                    cmd
                }
                None => {
                    return Outcome {
                        cmd_path,
                        // NOTE Since i < len, .get(i..) will never panic.
                        remaining: tokenization.tokens.get(i..).unwrap().to_vec(),
                        cmd_type: if i == 0 {
                            // If this is the first lookup, then obviously we have no idea what the
                            // type is.
                            CommandType::Unknown
                        } else {
                            cmd_type
                        },
                        possibilities: current_set.names(),
                        leaf_completion: None,
                        complete: false,
                    };
                }
            };

            // At this point, we have successfully found the token in the set.
            // Now, if this command has children, we want to go deeper into the set.
            // If it is a leaf command, and has we're actually done and can return the current
            // cmd_path and remaining tokens and complete.
            match &**looked_up_cmd {
                Command::Leaf(cmd) => {
                    // This is a leaf command, so we are actually almost done.
                    // Leaf commands themselves, can, given their arguments, attempt a local
                    // autocompletion. Let's give that a shot and then finish.
                    return Outcome {
                        cmd_path,
                        // NOTE Since i < len, .get(i+1..) will never panic.
                        remaining: tokenization.tokens.get(i + 1..).unwrap().to_vec(),
                        cmd_type,
                        possibilities: Vec::new(),
                        leaf_completion: Some(cmd.autocomplete(
                            tokenization.tokens.get(i + 1..).unwrap().to_vec(),
                            tokenization.trailing_space,
                        )),
                        complete: true,
                    };
                }
                Command::Parent(cmd) => {
                    current_set = cmd.sub_commands();
                }
            }
        }

        // We will basically only arrive here if the number of tokens is zero.
        Outcome {
            cmd_path,
            remaining: Vec::new(), // If we get here, we are out of tokens anyways.
            cmd_type: if tokenization.tokens.is_empty() {
                CommandType::Unknown
            } else {
                cmd_type
            },
            possibilities: current_set.names(),
            leaf_completion: None,
            complete: false,
        }
    }

    /// Parses a given Vector of tokens into a parse `Outcome`.
    ///
    /// # Arguments
    /// `tokens` - The tokens produced from an input line.
    /// `cmds` - The available custom commands to parse into.
    /// `builtins` - The available builtins to parse into.
    ///
    /// # Returns
    /// `Outcome` - The parse outcome, given the arguments.
    fn parse_tokens<'a, S>(
        &self,
        tokenization: &Tokenization<'a>,
        cmds: &CommandSet<S>,
        builtins: &CommandSet<Shell<S>>,
    ) -> Outcome<'a> {
        let cmd_outcome = self.parse_tokens_with_set(tokenization, CommandType::Custom, cmds);
        if cmd_outcome.complete {
            return cmd_outcome;
        }

        let builtin_outcome =
            self.parse_tokens_with_set(tokenization, CommandType::Builtin, builtins);
        if builtin_outcome.complete {
            return builtin_outcome;
        }

        cmd_outcome
    }

    /// Parses the given information into a parse `Outcome`.
    ///
    /// # Arguments
    /// `line` - The input line.
    /// `cmds` - The available custom commands to parse into.
    /// `builtins` - The available builtins to parse into.
    ///
    /// # Returns
    /// `Outcome` - The parse outcome, given the arguments.
    pub fn parse<'a, S>(
        &self,
        line: &'a str,
        cmds: &CommandSet<S>,
        builtins: &CommandSet<Shell<S>>,
    ) -> Outcome<'a> {
        let tokenization = self.tokenizer.tokenize(line);
        self.parse_tokens(&tokenization, cmds, builtins)
    }
}

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

    use crate::command::BaseCommand;
    use crate::Result;

    use pretty_assertions::assert_eq;

    use std::marker::PhantomData;

    // TODO: We should not need to stutter and call it 'ParseTestCommand'. Just call it
    // 'TestCommand'. It's obviously for parser tests.
    #[derive(Debug)]
    struct ParseTestCommand<'a, S> {
        name: &'a str,
        autocompletions: Vec<&'a str>,
        phantom: PhantomData<S>,
    }

    impl<'a, S> ParseTestCommand<'a, S> {
        fn new(name: &str) -> ParseTestCommand<S> {
            ParseTestCommand {
                name,
                autocompletions: Vec::new(),
                phantom: PhantomData,
            }
        }

        fn new_with_completions(
            name: &'a str,
            completions: Vec<&'a str>,
        ) -> ParseTestCommand<'a, S> {
            ParseTestCommand {
                name,
                autocompletions: completions,
                phantom: PhantomData,
            }
        }
    }

    impl<'a, S> BaseCommand for ParseTestCommand<'a, S> {
        type State = S;

        fn name(&self) -> &str {
            self.name
        }

        #[cfg(not(tarpaulin_include))]
        fn validate_args(&self, _: &[String]) -> Result<()> {
            Ok(())
        }

        fn autocomplete(&self, args: Vec<&str>, _: bool) -> Completion {
            // If we don't have any autocompletions set, then just short-circuit out.
            if self.autocompletions.is_empty() {
                return Completion::Nothing;
            }

            match args.last() {
                Some(last) => {
                    if self.autocompletions.iter().filter(|s| s == &last).count() > 0 {
                        // If the last argument is in our autocompletions, then we're good, nothing
                        // more to complete.
                        Completion::Nothing
                    } else {
                        let prefix_matches: Vec<String> = self
                            .autocompletions
                            .iter()
                            .filter(|s| s.starts_with(last))
                            .map(|s| s.to_string())
                            .collect();

                        if prefix_matches.is_empty() {
                            // If nothing matched, then we have no completions.
                            return Completion::Nothing;
                        }
                        // If not, then perhaps it is a prefix of an autocompletion. Let's give
                        // back some partial arg completions if so!
                        Completion::PartialArgCompletion(prefix_matches)
                    }
                }
                None => Completion::Possibilities(
                    self.autocompletions.iter().map(|s| s.to_string()).collect(),
                ),
            }
        }

        #[cfg(not(tarpaulin_include))]
        fn execute(&self, _: &mut S, _: &[String]) -> Result<String> {
            Ok(String::from(""))
        }
    }

    pub fn make_parser_cmds<'a>() -> (CommandSet<'a, ()>, CommandSet<'a, Shell<'a, ()>>) {
        (
            CommandSet::new_from_vec(vec![
                Command::new_parent(
                    "foo-c",
                    vec![
                        Command::new_leaf(ParseTestCommand::new("bar-c")),
                        Command::new_leaf(ParseTestCommand::new("baz-c")),
                        Command::new_parent(
                            "qux-c",
                            vec![
                                Command::new_leaf(ParseTestCommand::new("quux-c")),
                                Command::new_leaf(ParseTestCommand::new("corge-c")),
                            ],
                        ),
                    ],
                ),
                Command::new_leaf(ParseTestCommand::new("grault-c")),
                Command::new_leaf(ParseTestCommand::new("conflict-tie")),
                Command::new_leaf(ParseTestCommand::new(
                    "conflict-builtin-longer-match-but-still-loses",
                )),
                Command::new_parent(
                    "conflict-custom-wins",
                    vec![Command::new_leaf(ParseTestCommand::new("child"))],
                ),
            ]),
            CommandSet::new_from_vec(vec![
                Command::new_parent(
                    "foo-b",
                    vec![Command::new_leaf(ParseTestCommand::new_with_completions(
                        "bar-b",
                        vec!["ho", "he", "bum"],
                    ))],
                ),
                Command::new_leaf(ParseTestCommand::new("conflict-tie")),
                Command::new_leaf(ParseTestCommand::new("conflict-custom-wins")),
                Command::new_parent(
                    "conflict-builtin-longer-match-but-still-loses",
                    vec![Command::new_leaf(ParseTestCommand::new("child"))],
                ),
            ]),
        )
    }

    #[test]
    fn nesting() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-c bar-c he", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-c", "bar-c"],
                remaining: vec!["he"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn no_nesting_no_args() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-c bar-c", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-c", "bar-c"],
                remaining: vec![],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn end_with_no_args_but_is_parent() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-c qux-c", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-c", "qux-c"],
                remaining: vec![],
                cmd_type: CommandType::Custom,
                possibilities: vec![String::from("quux-c"), String::from("corge-c")],
                leaf_completion: None,
                complete: false,
            }
        );
    }

    #[test]
    fn builtin_nesting() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-b bar-b he", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-b", "bar-b"],
                remaining: vec!["he"],
                cmd_type: CommandType::Builtin,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn empty() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec![],
                remaining: vec![],
                cmd_type: CommandType::Unknown,
                possibilities: vec![
                    String::from("foo-c"),
                    String::from("grault-c"),
                    String::from("conflict-tie"),
                    String::from("conflict-builtin-longer-match-but-still-loses"),
                    String::from("conflict-custom-wins"),
                ],
                leaf_completion: None,
                complete: false,
            }
        );
    }

    #[test]
    fn invalid_subcmd() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-c he", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-c"],
                remaining: vec!["he"],
                cmd_type: CommandType::Custom,
                possibilities: vec![
                    String::from("bar-c"),
                    String::from("baz-c"),
                    String::from("qux-c"),
                ],
                leaf_completion: None,
                complete: false,
            }
        );
    }

    #[test]
    fn no_nesting() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("grault-c la la", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["grault-c"],
                remaining: vec!["la", "la"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn no_args_no_nesting() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("grault-c", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["grault-c"],
                remaining: vec![],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn cmd_has_args_that_match_other_cmds() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("grault-c foo-c bar-c", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["grault-c"],
                // Although these match other command names, since they come after grault, we
                // expect them to be treated as basic arguments.
                remaining: vec!["foo-c", "bar-c"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn nonexistent_cmd() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("notacmd", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec![],
                remaining: vec!["notacmd"],
                cmd_type: CommandType::Unknown,
                possibilities: vec![
                    String::from("foo-c"),
                    String::from("grault-c"),
                    String::from("conflict-tie"),
                    String::from("conflict-builtin-longer-match-but-still-loses"),
                    String::from("conflict-custom-wins"),
                ],
                leaf_completion: None,
                complete: false,
            }
        );
    }

    #[test]
    fn args_with_nonexistent_cmd() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("notacmd la la", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec![],
                remaining: vec!["notacmd", "la", "la"],
                cmd_type: CommandType::Unknown,
                possibilities: vec![
                    String::from("foo-c"),
                    String::from("grault-c"),
                    String::from("conflict-tie"),
                    String::from("conflict-builtin-longer-match-but-still-loses"),
                    String::from("conflict-custom-wins"),
                ],
                leaf_completion: None,
                complete: false,
            }
        );
    }

    #[test]
    fn three_levels_deep() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-c qux-c quux-c la la", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-c", "qux-c", "quux-c"],
                remaining: vec!["la", "la"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn perfect_tie_custom_wins_tie_breaker() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("conflict-tie ha ha", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["conflict-tie"],
                remaining: vec!["ha", "ha"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn conflict_but_builtin_has_longer_match() {
        // We are testing that custom commands have a higher precedence. Although this command
        // exists identically in the builtin set, the custom variant is chosen.
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse(
                "conflict-builtin-longer-match-but-still-loses child ha",
                &cmds.0,
                &cmds.1
            ),
            Outcome {
                cmd_path: vec!["conflict-builtin-longer-match-but-still-loses"],
                remaining: vec!["child", "ha"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn conflict_but_custom_has_longer_match() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("conflict-custom-wins child ha", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["conflict-custom-wins", "child"],
                remaining: vec!["ha"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn cmd_level_partial_autocompletion_multiple_choices() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-b bar-b h", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-b", "bar-b"],
                remaining: vec!["h"],
                cmd_type: CommandType::Builtin,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::PartialArgCompletion(vec![
                    String::from("ho"),
                    String::from("he")
                ])),
                complete: true,
            }
        );
    }

    #[test]
    fn cmd_level_partial_autocompletion_single_choice() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-b bar-b b", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-b", "bar-b"],
                remaining: vec!["b"],
                cmd_type: CommandType::Builtin,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::PartialArgCompletion(vec![String::from("bum"),])),
                complete: true,
            }
        );
    }

    #[test]
    fn cmd_level_completion_all_options() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-b bar-b", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-b", "bar-b"],
                remaining: vec![],
                cmd_type: CommandType::Builtin,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Possibilities(vec![
                    String::from("ho"),
                    String::from("he"),
                    String::from("bum"),
                ])),
                complete: true,
            }
        );
    }

    #[test]
    fn cmd_level_completion_no_matches() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-b bar-b z", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-b", "bar-b"],
                remaining: vec!["z"],
                cmd_type: CommandType::Builtin,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    #[test]
    fn cmd_level_completion_already_complete() {
        let cmds = make_parser_cmds();

        assert_eq!(
            Parser::new().parse("foo-b bar-b bum", &cmds.0, &cmds.1),
            Outcome {
                cmd_path: vec!["foo-b", "bar-b"],
                remaining: vec!["bum"],
                cmd_type: CommandType::Builtin,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            }
        );
    }

    mod outcome {
        use super::{CommandType, Completion, Outcome};

        use pretty_assertions::assert_eq;

        #[test]
        fn outcome_error_msg() {
            let outcome = Outcome {
                cmd_path: vec!["foo", "bar"],
                remaining: vec!["la", "la"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: None,
                complete: false,
            };

            assert_eq!(
                outcome.error_msg(),
                vec![
                    "Failed to parse fully:\n",
                    "\n",
                    "\t    (spaces trimmed)\n",
                    "\t => 'foo bar la la'\n",
                    "\t             ^\n",
                    "expected a valid subcommand\n",
                    "instead, got: 'la';\n",
                    "\n",
                    "Run 'foo bar help' for more info on the command.\n",
                    "Run 'helptree' for more info on the entire command tree.\n",
                ]
                .join(""),
            );
        }

        #[test]
        fn empty_remaining_in_outcome() {
            let outcome = Outcome {
                cmd_path: vec!["foo", "bar"],
                remaining: vec![],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: None,
                complete: false,
            };

            assert_eq!(
                outcome.error_msg(),
                vec![
                    "Failed to parse fully:\n",
                    "\n",
                    "\t    (spaces trimmed)\n",
                    "\t => 'foo bar  '\n",
                    "\t             ^\n",
                    "expected a valid subcommand\n",
                    "instead, got: nothing;\n",
                    "\n",
                    "Run 'foo bar help' for more info on the command.\n",
                    "Run 'helptree' for more info on the entire command tree.\n",
                ]
                .join(""),
            );
        }

        #[test]
        fn empty() {
            let outcome = Outcome {
                cmd_path: vec![],
                remaining: vec![],
                cmd_type: CommandType::Custom,
                possibilities: vec![
                    String::from("conflict-tie"),
                    String::from("conflict-builtin-longer-match-but-still-loses"),
                    String::from("conflict-custom-wins"),
                    String::from("foo-c"),
                    String::from("grault-c"),
                ],
                leaf_completion: None,
                complete: false,
            };

            assert_eq!(
                outcome.error_msg(),
                vec![
                    "Empty string could not be parsed as a command.\n",
                    "\n",
                    "\t => expected one of 'conflict-tie' or 'conflict-builtin-longer-match-but-still-loses' or 'conflict-custom-wins' or 'foo-c' or 'grault-c'.",
                    "\n",
                    "\n",
                    "Run 'helptree' for more info on the entire command tree.\n",
                ]
                .join(""),
            );
        }

        #[test]
        fn unrecognized_first_cmd() {
            let outcome = Outcome {
                cmd_path: vec![],
                remaining: vec!["notfound", "la"],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: None,
                complete: false,
            };

            assert_eq!(
                outcome.error_msg(),
                vec![
                    "'notfound' is not a recognized command.\n",
                    "Run 'helptree' for more info on the entire command tree.\n",
                ]
                .join(""),
            );
        }

        #[test]
        fn error_msg_is_blank_for_complete_parse() {
            let outcome = Outcome {
                cmd_path: vec![],
                remaining: vec![],
                cmd_type: CommandType::Custom,
                possibilities: Vec::new(),
                leaf_completion: Some(Completion::Nothing),
                complete: true,
            };

            assert_eq!(outcome.error_msg(), String::from(""));
        }
    }
}