Repository: clap-rs/clap (Rust)

Issue:
clap_generate panics for ZSH with nested subcommands
### Make sure you completed the following tasks

- [x] Searched the [discussions](https://github.com/clap-rs/clap/discussions)
- [x] Searched the closed issues

This appears to be similar to #2009, but I think the root cause of this issue is different.

### Code
This is a modification of the `bash_completion.rs` example in the `clap_generate` workspace.

```rust
use clap::App;
use clap_generate::{generate, generators::Zsh};
use std::io;

fn main() {
    let mut app = App::new("myapp")
        .subcommand(App::new("test").subcommand(App::new("config")))
        .subcommand(App::new("hello"));

    generate::<Zsh, _>(&mut app, "myapp", &mut io::stdout());
}
```

### Steps to reproduce the issue

1. `cd clap_generate`
2. Create a file called `examples/zsh_completion.rs` with the above code.
3. `cargo run --example zsh_completion`

### Version

* **Rust**: `rustc 1.45.2 (d3fb005a3 2020-07-31)`
* **Clap**: 6a56a82629d1a990efb37dae9c75a76e943f22a0 (master)

### Actual Behavior Summary

The program fails with a panic.

### Expected Behavior Summary

I do not expect generation to panic for a valid App.

### Debug output

<details>
<summary> Debug Output </summary>
<pre>
<code>
[            clap::build::app]  App::_build
[            clap::build::app]  App::_derive_display_order:myapp
[            clap::build::app]  App::_derive_display_order:test
[            clap::build::app]  App::_derive_display_order:config
[            clap::build::app]  App::_derive_display_order:hello
[            clap::build::app]  App::_create_help_and_version
[            clap::build::app]  App::_create_help_and_version: Building --help
[            clap::build::app]  App::_create_help_and_version: Building --version
[            clap::build::app]  App::_create_help_and_version: Building help
[clap::build::app::debug_asserts]       App::_debug_asserts
[            clap::build::arg]  Arg::_debug_asserts:help
[            clap::build::arg]  Arg::_debug_asserts:version
[            clap::build::app]  App::_build_bin_names
[            clap::build::app]  App::_build_bin_names:iter: bin_name set...
[            clap::build::app]  No
[            clap::build::app]  App::_build_bin_names:iter: Setting bin_name of myapp to myapp test
[            clap::build::app]  App::_build_bin_names:iter: Calling build_bin_names from...test
[            clap::build::app]  App::_build_bin_names
[            clap::build::app]  App::_build_bin_names:iter: bin_name set...
[            clap::build::app]  No
[            clap::build::app]  App::_build_bin_names:iter: Setting bin_name of test to myapp test config
[            clap::build::app]  App::_build_bin_names:iter: Calling build_bin_names from...config
[            clap::build::app]  App::_build_bin_names
[            clap::build::app]  App::_build_bin_names:iter: bin_name set...
[            clap::build::app]  No
[            clap::build::app]  App::_build_bin_names:iter: Setting bin_name of myapp to myapp hello
[            clap::build::app]  App::_build_bin_names:iter: Calling build_bin_names from...hello
[            clap::build::app]  App::_build_bin_names
[            clap::build::app]  App::_build_bin_names:iter: bin_name set...
[            clap::build::app]  No
[            clap::build::app]  App::_build_bin_names:iter: Setting bin_name of myapp to myapp help
[            clap::build::app]  App::_build_bin_names:iter: Calling build_bin_names from...help
[            clap::build::app]  App::_build_bin_names
[clap_generate::generators::shells::zsh]        get_args_of
[clap_generate::generators::shells::zsh]        write_opts_of
[clap_generate::generators::shells::zsh]        write_flags_of;
[   clap_generate::generators]  flags: name=myapp
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=help
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-h[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--help[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=version
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-V[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--version[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_positionals_of;
[clap_generate::generators::shells::zsh]        get_subcommands_of: Has subcommands...true
[   clap_generate::generators]  subcommands: name=myapp
[   clap_generate::generators]  subcommands: Has subcommands...true
[   clap_generate::generators]  subcommands:iter: name=test, bin_name=myapp test
[   clap_generate::generators]  subcommands:iter: name=hello, bin_name=myapp hello
[   clap_generate::generators]  subcommands:iter: name=help, bin_name=myapp help
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp test
[clap_generate::generators::shells::zsh]        get_args_of
[clap_generate::generators::shells::zsh]        write_opts_of
[clap_generate::generators::shells::zsh]        write_flags_of;
[   clap_generate::generators]  flags: name=test
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=help
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-h[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--help[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=version
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-V[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--version[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_positionals_of;
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp test
[clap_generate::generators::shells::zsh]        get_subcommands_of: Has subcommands...true
[   clap_generate::generators]  subcommands: name=test
[   clap_generate::generators]  subcommands: Has subcommands...true
[   clap_generate::generators]  subcommands:iter: name=config, bin_name=myapp test config
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp test config
[clap_generate::generators::shells::zsh]        get_args_of
[clap_generate::generators::shells::zsh]        write_opts_of
[clap_generate::generators::shells::zsh]        write_flags_of;
[   clap_generate::generators]  flags: name=config
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=help
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-h[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--help[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=version
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-V[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--version[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_positionals_of;
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp test config
[clap_generate::generators::shells::zsh]        get_subcommands_of: Has subcommands...false
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp hello
[clap_generate::generators::shells::zsh]        get_args_of
[clap_generate::generators::shells::zsh]        write_opts_of
[clap_generate::generators::shells::zsh]        write_flags_of;
[   clap_generate::generators]  flags: name=hello
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=help
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-h[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--help[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=version
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-V[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--version[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_positionals_of;
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp hello
[clap_generate::generators::shells::zsh]        get_subcommands_of: Has subcommands...false
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp help
[clap_generate::generators::shells::zsh]        get_args_of
[clap_generate::generators::shells::zsh]        write_opts_of
[clap_generate::generators::shells::zsh]        write_flags_of;
[   clap_generate::generators]  flags: name=help
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=help
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-h[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--help[Prints help information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: f=version
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'-V[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_flags_of:iter: Wrote...'--version[Prints version information]' \
[clap_generate::generators::shells::zsh]        write_positionals_of;
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp help
[clap_generate::generators::shells::zsh]        get_subcommands_of: Has subcommands...false
[clap_generate::generators::shells::zsh]        subcommand_details
[clap_generate::generators::shells::zsh]        subcommands_of
[clap_generate::generators::shells::zsh]        subcommands_of:iter: subcommand=test
[clap_generate::generators::shells::zsh]        add_sc
[clap_generate::generators::shells::zsh]        subcommands_of:iter: subcommand=hello
[clap_generate::generators::shells::zsh]        add_sc
[clap_generate::generators::shells::zsh]        subcommands_of:iter: subcommand=help
[clap_generate::generators::shells::zsh]        add_sc
[   clap_generate::generators]  subcommands: name=myapp
[   clap_generate::generators]  subcommands: Has subcommands...true
[   clap_generate::generators]  subcommands:iter: name=test, bin_name=myapp test
[   clap_generate::generators]  subcommands:iter: name=hello, bin_name=myapp hello
[   clap_generate::generators]  subcommands:iter: name=help, bin_name=myapp help
[   clap_generate::generators]  subcommands: name=test
[   clap_generate::generators]  subcommands: Has subcommands...true
[   clap_generate::generators]  subcommands:iter: name=config, bin_name=myapp test config
[   clap_generate::generators]  subcommands: name=config
[   clap_generate::generators]  subcommands: Has subcommands...false
[   clap_generate::generators]  subcommands: name=hello
[   clap_generate::generators]  subcommands: Has subcommands...false
[   clap_generate::generators]  subcommands: name=help
[   clap_generate::generators]  subcommands: Has subcommands...false
[clap_generate::generators::shells::zsh]        subcommand_details:iter: bin_name=myapp test config
[clap_generate::generators::shells::zsh]        parser_of: sc=myapp test config
thread 'main' panicked at 'Fatal internal error. Please consider filing a bug report at https://github.com/clap-rs/clap/issues', clap_generate/src/generators/shells/zsh.rs:263:5
stack backtrace:
   0: backtrace::backtrace::libunwind::trace
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/libunwind.rs:86
   1: backtrace::backtrace::trace_unsynchronized
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/mod.rs:66
   2: std::sys_common::backtrace::_print_fmt
             at src/libstd/sys_common/backtrace.rs:78
   3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt
             at src/libstd/sys_common/backtrace.rs:59
   4: core::fmt::write
             at src/libcore/fmt/mod.rs:1076
   5: std::io::Write::write_fmt
             at src/libstd/io/mod.rs:1537
   6: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:62
   7: std::sys_common::backtrace::print
             at src/libstd/sys_common/backtrace.rs:49
   8: std::panicking::default_hook::{{closure}}
             at src/libstd/panicking.rs:198
   9: std::panicking::default_hook
             at src/libstd/panicking.rs:218
  10: std::panicking::rust_panic_with_hook
             at src/libstd/panicking.rs:486
  11: rust_begin_unwind
             at src/libstd/panicking.rs:388
  12: core::panicking::panic_fmt
             at src/libcore/panicking.rs:101
  13: core::option::expect_failed
             at src/libcore/option.rs:1264
  14: core::option::Option<T>::expect
             at /home/alex/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libcore/option.rs:349
  15: clap_generate::generators::shells::zsh::parser_of
             at clap_generate/src/generators/shells/zsh.rs:263
  16: clap_generate::generators::shells::zsh::subcommand_details
             at clap_generate/src/generators/shells/zsh.rs:122
  17: <clap_generate::generators::shells::zsh::Zsh as clap_generate::generators::Generator>::generate
             at clap_generate/src/generators/shells/zsh.rs:48
  18: clap_generate::generate
             at ./src/lib.rs:189
  19: bash_completion::main
             at clap_generate/examples/bash_completion.rs:10
  20: std::rt::lang_start::{{closure}}
             at /home/alex/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libstd/rt.rs:67
  21: std::rt::lang_start_internal::{{closure}}
             at src/libstd/rt.rs:52
  22: std::panicking::try::do_call
             at src/libstd/panicking.rs:297
  23: std::panicking::try
             at src/libstd/panicking.rs:274
  24: std::panic::catch_unwind
             at src/libstd/panic.rs:394
  25: std::rt::lang_start_internal
             at src/libstd/rt.rs:51
  26: std::rt::lang_start
             at /home/alex/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libstd/rt.rs:67
  27: main
  28: __libc_start_main
  29: _start
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
</code>
</pre>
</details>



Discussion:

Patch:
diff --git a/clap_generate/src/generators/shells/zsh.rs b/clap_generate/src/generators/shells/zsh.rs
index e32303d6714..54ff712ce82 100644
--- a/clap_generate/src/generators/shells/zsh.rs
+++ b/clap_generate/src/generators/shells/zsh.rs
@@ -119,7 +119,8 @@ _{bin_name_underscore}_commands() {{
 }}",
             bin_name_underscore = bin_name.replace(" ", "__"),
             bin_name = bin_name,
-            subcommands_and_args = subcommands_of(parser_of(p, bin_name))
+            subcommands_and_args =
+                subcommands_of(parser_of(p, bin_name).expect(INTERNAL_ERROR_MSG))
         ));
     }
 
@@ -217,14 +218,20 @@ fn get_subcommands_of(p: &App) -> String {
     let mut subcmds = vec![];
 
     for &(ref name, ref bin_name) in &sc_names {
+        debug!(
+            "get_subcommands_of:iter: p={}, name={}, bin_name={}",
+            p.get_name(),
+            name,
+            bin_name,
+        );
         let mut v = vec![format!("({})", name)];
-        let subcommand_args = get_args_of(parser_of(p, &*bin_name));
+        let subcommand_args = get_args_of(parser_of(p, &*bin_name).expect(INTERNAL_ERROR_MSG));
 
         if !subcommand_args.is_empty() {
             v.push(subcommand_args);
         }
 
-        let subcommands = get_subcommands_of(parser_of(p, &*bin_name));
+        let subcommands = get_subcommands_of(parser_of(p, &*bin_name).expect(INTERNAL_ERROR_MSG));
 
         if !subcommands.is_empty() {
             v.push(subcommands);
@@ -252,15 +259,24 @@ esac",
     )
 }
 
-fn parser_of<'help, 'app>(p: &'app App<'help>, mut sc: &str) -> &'app App<'help> {
-    debug!("parser_of: sc={}", sc);
+// Get the App for a given subcommand tree.
+//
+// Given the bin_name "a b c" and the App for "a" this returns the "c" App.
+// Given the bin_name "a b c" and the App for "b" this returns the "c" App.
+fn parser_of<'help, 'app>(p: &'app App<'help>, bin_name: &str) -> Option<&'app App<'help>> {
+    debug!("parser_of: p={}, bin_name={}", p.get_name(), bin_name);
+
+    if bin_name == p.get_bin_name().unwrap_or(&String::new()) {
+        return Some(p);
+    }
 
-    if sc == p.get_bin_name().unwrap_or(&String::new()) {
-        return p;
+    for sc in p.get_subcommands() {
+        if let Some(ret) = parser_of(sc, bin_name) {
+            return Some(ret);
+        }
     }
 
-    sc = sc.split(' ').last().unwrap();
-    p.find_subcommand(sc).expect(INTERNAL_ERROR_MSG)
+    None
 }
 
 // Writes out the args section, which ends up being the flags, opts and positionals, and a jump to
diff --git a/src/build/app/mod.rs b/src/build/app/mod.rs
index 0216a0e80ac..03ee06ff17d 100644
--- a/src/build/app/mod.rs
+++ b/src/build/app/mod.rs
@@ -263,6 +263,8 @@ impl<'help> App<'help> {
     }
 
     /// Find subcommand such that its name or one of aliases equals `name`.
+    ///
+    /// This does not recurse through subcommands of subcommands.
     #[inline]
     pub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>>
     where


Test patch:
diff --git a/clap_generate/tests/completions.rs b/clap_generate/tests/completions.rs
index 1aa76b31d42..c26ecd1a03f 100644
--- a/clap_generate/tests/completions.rs
+++ b/clap_generate/tests/completions.rs
@@ -712,6 +712,108 @@ _my_app_commands() {
 
 _my_app "$@""#;
 
+static ZSH_NESTED_SUBCOMMANDS: &str = r#"#compdef my_app
+
+autoload -U is-at-least
+
+_my_app() {
+    typeset -A opt_args
+    typeset -a _arguments_options
+    local ret=1
+
+    if is-at-least 5.2; then
+        _arguments_options=(-s -S -C)
+    else
+        _arguments_options=(-s -C)
+    fi
+
+    local context curcontext="$curcontext" state line
+    _arguments "${_arguments_options[@]}" \
+'-h[Prints help information]' \
+'--help[Prints help information]' \
+'-V[Prints version information]' \
+'--version[Prints version information]' \
+":: :_my_app_commands" \
+"*::: :->first" \
+&& ret=0
+    case $state in
+    (first)
+        words=($line[1] "${words[@]}")
+        (( CURRENT += 1 ))
+        curcontext="${curcontext%:*:*}:my_app-command-$line[1]:"
+        case $line[1] in
+            (second)
+_arguments "${_arguments_options[@]}" \
+'-h[Prints help information]' \
+'--help[Prints help information]' \
+'-V[Prints version information]' \
+'--version[Prints version information]' \
+":: :_my_app__second_commands" \
+"*::: :->second" \
+&& ret=0
+case $state in
+    (second)
+        words=($line[1] "${words[@]}")
+        (( CURRENT += 1 ))
+        curcontext="${curcontext%:*:*}:my_app-second-command-$line[1]:"
+        case $line[1] in
+            (third)
+_arguments "${_arguments_options[@]}" \
+'-h[Prints help information]' \
+'--help[Prints help information]' \
+'-V[Prints version information]' \
+'--version[Prints version information]' \
+&& ret=0
+;;
+        esac
+    ;;
+esac
+;;
+(help)
+_arguments "${_arguments_options[@]}" \
+'-h[Prints help information]' \
+'--help[Prints help information]' \
+'-V[Prints version information]' \
+'--version[Prints version information]' \
+&& ret=0
+;;
+        esac
+    ;;
+esac
+}
+
+(( $+functions[_my_app_commands] )) ||
+_my_app_commands() {
+    local commands; commands=(
+        "second:" \
+"help:Prints this message or the help of the given subcommand(s)" \
+    )
+    _describe -t commands 'my_app commands' commands "$@"
+}
+(( $+functions[_my_app__help_commands] )) ||
+_my_app__help_commands() {
+    local commands; commands=(
+        
+    )
+    _describe -t commands 'my_app help commands' commands "$@"
+}
+(( $+functions[_my_app__second_commands] )) ||
+_my_app__second_commands() {
+    local commands; commands=(
+        "third:" \
+    )
+    _describe -t commands 'my_app second commands' commands "$@"
+}
+(( $+functions[_my_app__second__third_commands] )) ||
+_my_app__second__third_commands() {
+    local commands; commands=(
+        
+    )
+    _describe -t commands 'my_app second third commands' commands "$@"
+}
+
+_my_app "$@""#;
+
 fn build_app() -> App<'static> {
     build_app_with_name("myapp")
 }
@@ -777,6 +879,10 @@ fn build_app_special_help() -> App<'static> {
         )
 }
 
+fn build_app_nested_subcommands() -> App<'static> {
+    App::new("first").subcommand(App::new("second").subcommand(App::new("third")))
+}
+
 pub fn common<G: Generator>(app: &mut App, name: &str, fixture: &str) {
     let mut buf = vec![];
     generate::<G, _>(app, name, &mut buf);
@@ -856,3 +962,9 @@ fn zsh_with_special_help() {
     let mut app = build_app_special_help();
     common::<Zsh>(&mut app, "my_app", ZSH_SPECIAL_HELP);
 }
+
+#[test]
+fn zsh_with_nested_subcommands() {
+    let mut app = build_app_nested_subcommands();
+    common::<Zsh>(&mut app, "my_app", ZSH_NESTED_SUBCOMMANDS);
+}