zshrs 0.13.41

The first JIT-compiled Unix shell — bytecode VM, Cranelift JIT, worker pool, AOP intercept, Rkyv caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Port of `_complete` from `Completion/Base/Completer/_complete`.
//!
//! Full upstream body (145 lines, abridged — line numbers are the
//! vendored `Base/Completer/_complete` next to this file, byte-identical
//! to the installed `/opt/homebrew/share/zsh/functions/_complete`):
//! ```text
//! sh:  1  #autoload
//! sh:  7  local comp name oldcontext ret=1 service
//! sh:  8  typeset -T curcontext="$curcontext" ccarray
//! sh: 10  oldcontext="$curcontext"
//! sh: 14  if [[ -n "$compcontext" ]]; then  # custom context dispatch
//! sh: 16    type-of-compcontext (array | assoc | tag:descr:action | scalar)
//! sh: 85    ccarray[3]="$compcontext"
//! sh: 87    comp="$_comps[$compcontext]"
//! sh: 91    return
//! sh: 92  fi
//! sh: 96  comp="$_comps[-first-]"
//! sh: 97  if [[ -n "$comp" ]]; then
//! sh: 99    ccarray[3]=-first-
//! sh:100    … run -first-, exit if _compskip == all …
//! sh:110  [[ -n $compstate[vared] ]] && compstate[context]=vared
//! sh:115  if [[ "$compstate[context]" = command ]]; then
//! sh:116    curcontext="$oldcontext"
//! sh:117    _normal -s && ret=0
//! sh:118  else
//! sh:122    local cname="-${compstate[context]:s/_/-/}-"
//! sh:124    ccarray[3]="$cname"
//! sh:126    comp="$_comps[$cname]"
//! sh:131    if [[ -z "$comp" ]]; then
//! sh:136      comp="$_comps[-default-]"
//! sh:138    fi
//! sh:139    [[ -n "$comp" ]] && eval "$comp" && ret=0
//! sh:140  fi
//! sh:142  _compskip=
//! sh:144  return ret
//! ```
//!
//! Top-level completer dispatching to context-specific `$_comps`
//! entries. Heavy `compcontext`-based dispatch left as a thin
//! delegation since most live invocations skip that branch.

use crate::compsys::ported::_message::_message;
use crate::compsys::ported::_next_label::_next_label;
use crate::compsys::ported::_tags::_tags;
use crate::compsys::ported::_normal::_normal;
use crate::ported::exec::dispatch_function_call;
use crate::ported::params::{getaparam, getsparam, setaparam, setsparam};
use crate::ported::zsh_h::{options, MAX_OPS};

/// `compadd`'s option block — the builtin is normally reached through
/// `execbuiltin`, which builds this; a direct call has to supply it.
fn make_ops() -> options {
    options {
        ind: [0u8; MAX_OPS],
        args: Vec::new(),
        argscount: 0,
        argsalloc: 0,
    }
}

/// Helper: flat assoc lookup.
fn assoc_get(name: &str, key: &str) -> Option<String> {
    // `_comps`/`_services` are PM_HASHED associative arrays, NOT flat arrays,
    // so `getaparam` returns nothing for them — read the hashed storage
    // directly (same fix as `_dispatch::assoc_get`). With the old getaparam
    // path, `$_comps[-parameter-]` came back empty during completion even
    // though the shell saw it set, so every non-command context (parameter,
    // brace_parameter, value, condition, …) fell through to nothing —
    // `$var<TAB>`, `${...}<TAB>`, `((expr<TAB>` all produced no matches.
    crate::ported::params::paramtab_hashed_storage()
        .lock()
        .ok()?
        .get(name)?
        .get(key)
        .cloned()
}

/// `ccarray[n]=value` under sh:8's `typeset -T curcontext="$curcontext"
/// ccarray` — the array half of the tie, written back through the scalar.
///
/// A `-T` tie with no explicit separator uses `:`, so `ccarray` is just
/// `$curcontext` split on colons and `ccarray[3]` (1-based, hence
/// `n - 1` here) is the COMMAND field of
/// `<function>:<completer>:<command>:<argument>`. Assigning past the end
/// of a zsh array pads the gap with empty elements, then the tie rejoins
/// with `:` — so `curcontext=foo` + `ccarray[3]=bar` yields `foo::bar`,
/// which is what the pad loop below reproduces. An empty `curcontext`
/// splits to one empty field and pads to `::value`, matching zsh.
///
/// The write goes back into the PARAMETER, not a Rust local: every
/// `$_comps` entry dispatched below (and everything it calls —
/// `_tags`/`_description`/`lookupstyle`) reads `$curcontext` to build
/// the style context, which is the whole point of the field.
fn set_ccarray_field(n: usize, value: &str) {
    debug_assert!(n >= 1, "ccarray is 1-based");
    let cur = getsparam("curcontext").unwrap_or_default();
    let mut parts: Vec<&str> = cur.split(':').collect();
    while parts.len() < n {
        parts.push("");
    }
    parts[n - 1] = value;
    let _ = setsparam("curcontext", &parts.join(":"));
}

/// Reach `_complete` as a BARE COMMAND WORD, the way every upstream caller
/// writes it — `if _complete; then` (Completion/Base/Completer/_approximate
/// sh:84) — so the normal function lookup runs.
///
/// This is the DEFAULT entry point for the port, and the one a sibling port
/// should call. It goes through
/// [`crate::compsys::ported::shared::call_compfn`], which supplies both of
/// the things a bare Rust call to the body would skip: `$fpath` / shfunc
/// arbitration (the user's own copy of the function wins instead of being
/// inert) and the `doshfunc` frame (a `FUNCSTACK` entry, and the callee's
/// `declare_locals` landing in its OWN param scope rather than the caller's).
///
/// [`_complete_impl`] is the raw body, reserved for the two callers that must not
/// re-enter dispatch: this wrapper's own fallback (it runs only when neither
/// a shell function nor a registered port claims the name — i.e. unit tests
/// with no executor installed), and the `compsys::router` arm, which has to
/// target the body or dispatch would re-enter this wrapper forever.
pub fn _complete() -> i32 {
    crate::compsys::ported::shared::call_compfn("_complete", &[], || _complete_impl())
}

/// `_complete` — primary `completer` entry: dispatches to per-context
/// `$_comps` entries based on `$compstate[context]`.
pub fn _complete_impl() -> i32 {
    let _fn_scope = crate::compsys::ported::shared::FnScope::enter("_complete");
    // sh:7 `local comp name oldcontext ret=1 service`.
    //
    // `comp`/`name`/`oldcontext`/`ret` are Rust locals here, but `service`
    // is a real shell parameter: the port writes it with `setsparam` below
    // and every `$_comps` entry reads it. Without the declaration that write
    // landed at level 0, so `service` survived the completion AND read back
    // as `scalar` instead of `scalar-local` — `_parameters` filters on
    // `[(R)…~*local*]`, so `${<TAB>` / `$fpath[<TAB>` offered `service` as a
    // parameter name and zsh does not. The other four are declared for the
    // same reason `_main_complete` declares its whole `local` line: a
    // `$parameters`/`typeset -p` read during completion must see what zsh
    // sees. `_complete` is reached through `dispatch_function_call`, so
    // `doshfunc`'s `endparamscope` performs the unwind.
    {
        use crate::compsys::ported::shared::declare_locals;
        declare_locals(&["comp", "name", "oldcontext", "ret", "service"], 0);
    }
    // sh:8 `typeset -T curcontext="$curcontext" ccarray` — a `typeset`
    // inside a function, so `curcontext` is LOCAL to `_complete` and
    // seeded from the enclosing scope's value (the completer-patched one
    // `_main_complete` built at `_main_complete.rs:736`). Every
    // `ccarray[3]=` below therefore has to be visible to the `$_comps`
    // entry it dispatches and unwound on return, exactly like
    // `_main_complete:31`'s own `curcontext="$curcontext"`
    // (`_main_complete.rs:432`).
    //
    // `LocalScope` rather than a bare `declare_locals_keeping_value`:
    // the value restore then holds on EVERY exit path (the four early
    // `return`s in the `compcontext` branch included) without depending
    // on `doshfunc`'s `endparamscope` firing, so a `-subscript-` written
    // here can never leak into the next completer in the chain.
    let mut _cc_scope = crate::compsys::ported::shared::LocalScope::declare(&[], 0);
    _cc_scope.also_keeping_value(&["curcontext"]);
    // …and then the TIE itself, which the port used to skip: it emulated
    // `ccarray[3]=` by rewriting `$curcontext`'s third `:`-field directly
    // (`set_ccarray_field` above) and never created the array half at all.
    // The emulation gets the VALUE right, but `ccarray` is a shell
    // parameter and `$parameters` reports every one of them. Measured
    // inside a live `-brace-parameter-` completion, `${(k)parameters}`
    // filtered to `*local*`, zshrs vs /opt/homebrew/bin/zsh 5.9.2:
    //
    //   only in zsh:  ccarray = array-local-tied
    //                 cname = scalar-local
    //                 curcontext = scalar-local-tied
    //   only in zshrs: curcontext = scalar-local
    //
    // and that is directly on screen: completing a parameter name renders
    // each candidate's VALUE as its description, so `print ${(j.:.)pa<TAB>`
    // listed `parameters -- scalar-local integer-local …` in zsh against
    // `parameters -- scalar-local …` in zshrs — a one-row screen
    // divergence caused purely by the missing declarations.
    //
    // `bin_typeset` rather than `declare_locals`, because only the real
    // builtin builds the tie: `${(t)curcontext}` has to read
    // `scalar-local-tied`, not `scalar-local`, and writing either half has
    // to update the other. The `LocalScope` above still owns the unwind —
    // it saved both names' previous `paramtab` entries and restores them on
    // every exit path, so this does not start depending on `endparamscope`.
    _cc_scope.also(&["ccarray"], 0);
    {
        use crate::ported::builtin::{bin_typeset, BIN_TYPESET};
        let mut ops = options {
            ind: [0u8; MAX_OPS],
            args: Vec::new(),
            argscount: 0,
            argsalloc: 0,
        };
        // sh:8 `typeset -T curcontext="$curcontext" ccarray`.
        ops.ind[b'T' as usize] = 1;
        let seed = getsparam("curcontext").unwrap_or_default();
        let args = [format!("curcontext={}", seed), "ccarray".to_string()];
        let _ = bin_typeset("typeset", &args, &ops, BIN_TYPESET);
    }

    let mut ret: i32 = 1;
    // sh:10 `oldcontext="$curcontext"`.
    let oldcontext = getsparam("curcontext").unwrap_or_default();

    // sh:14  compcontext custom dispatch
    let compcontext = getsparam("compcontext").unwrap_or_default();
    tracing::debug!(
        target: "compsys_args",
        %compcontext,
        compskip = %getsparam("_compskip").unwrap_or_default(),
        context = %crate::ported::params::getsparam("compstate[context]").unwrap_or_default(),
        "_complete ENTER"
    );
    if !compcontext.is_empty() {
        // sh:32  tag:descr:action form
        if compcontext.matches(':').count() >= 2 {
            let mut parts = compcontext.splitn(3, ':');
            let tag = parts
                .next()
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .unwrap_or_else(|| "values".to_string());
            let descr = parts
                .next()
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .unwrap_or_else(|| "value".to_string());
            let action = parts.next().unwrap_or("").to_string();
            if action.trim().is_empty() {
                return _message(&["-e".to_string(), tag, descr]);
            }
            // sh:40-44 `\(\(*\)\))` — `eval ws=( "${action[3,-3]}" )` then
            // `_describe -t "$tag" "$descr" ws`. Was missing entirely.
            if action.starts_with("((") && action.ends_with("))") && action.len() >= 4 {
                let body = &action[2..action.len() - 2];
                setaparam("ws", crate::compsys::ported::eval_action_words(body));
                crate::compsys::ported::shared::set_sh_lineno(44);
                return dispatch_function_call(
                    "_describe",
                    &["-t".to_string(), tag, descr, "ws".to_string()],
                )
                .unwrap_or(1);
            }
            // sh:46-49 `\(*\))` — `_wanted "$tag" expl "$descr" compadd -a - ws`.
            // Was missing entirely.
            if action.starts_with('(') && action.ends_with(')') && action.len() >= 2 {
                let body = &action[1..action.len() - 1];
                setaparam("ws", crate::compsys::ported::eval_action_words(body));
                crate::compsys::ported::shared::set_sh_lineno(49);
                return dispatch_function_call(
                    "_wanted",
                    &[
                        tag,
                        "expl".to_string(),
                        descr,
                        "compadd".to_string(),
                        "-a".to_string(),
                        "-".to_string(),
                        "ws".to_string(),
                    ],
                )
                .unwrap_or(1);
            }
            // sh:51-58 `\{*\})` — `_tags "$tag"`, then per label
            // `eval "$action[2,-2]" && ret=0`. Was missing entirely.
            if action.starts_with('{') && action.ends_with('}') && action.len() >= 2 {
                let body = action[1..action.len() - 1].to_string();
                let mut ret = 1;
                let _ = _tags(&[tag.clone()]);
                while _tags(&[]) == 0 {
                    while _next_label(&[tag.clone(), "expl".to_string(), descr.clone()]) == 0 {
                        if crate::ported::exec::execute_script(&body).is_ok() {
                            ret = 0; // sh:55 `&& ret=0`
                        }
                    }
                    if ret == 0 {
                        break; // sh:57 `(( ret )) || break`
                    }
                }
                return ret;
            }
            // sh:60-80 — the two command-line arms. They differ ONLY in
            // whether `$expl[@]` is spliced in after the command word:
            //   sh:66  `\ *)`  leading space -> `"$ws[@]"`, verbatim
            //   sh:77  `*)`     otherwise     -> `"$ws[1]" "$expl[@]" "${(@)ws[2,-1]}"`
            // The port collapsed both into one bare dispatch, so the default
            // arm never passed the description flags `_next_label` builds and
            // the match was added with no group or description. Both arms also
            // run inside the `_tags`/`_next_label` loop, which was absent too.
            let splice_expl = !action.starts_with(' '); // sh:61 vs sh:73
            let parts: Vec<String> = crate::compsys::ported::eval_action_words(&action);
            if let Some((cmd, rest)) = parts.split_first() {
                let mut ret = 1;
                let _ = _tags(&[tag.clone()]);
                while _tags(&[]) == 0 {
                    while _next_label(&[tag.clone(), "expl".to_string(), descr.clone()]) == 0 {
                        let mut argv: Vec<String> = Vec::new();
                        if splice_expl {
                            argv.extend(getaparam("expl").unwrap_or_default()); // sh:77
                        }
                        argv.extend(rest.iter().cloned());
                        // A bare `dispatch_function_call` resolves SHELL
                        // FUNCTIONS and native ports only, so a builtin, a
                        // `$PATH` executable and a NONEXISTENT name all came
                        // back `None` and collapsed to "non-zero" with NO
                        // diagnostic, where zsh prints `command not found`.
                        // `dispatch_action_command` publishes the sh line,
                        // routes `compadd` to the builtin, then falls back to
                        // the builtin table and `findcmd` before reporting.
                        //
                        // Reachable WITHOUT any completer: a `compcontext` of
                        // the form `tag:descr: compadd foo` is a documented
                        // user-facing spelling, so a plain zstyle reaches here.
                        let rc = crate::compsys::ported::shared::dispatch_action_command(
                            cmd,
                            &argv,
                            if splice_expl { 77 } else { 66 },
                        );
                        if rc == 0 {
                            ret = 0;
                        }
                    }
                    if ret == 0 {
                        break; // sh:69 / sh:80 `(( ret )) || break`
                    }
                }
                return ret;
            }
            // sh:66 / sh:77 run inside the `_tags` loop above, which returns
            // from within its `if let`. An action that evaluates to NO words
            // has nothing to run, so it simply fails.
            return 1;
        }
        // sh:85  `ccarray[3]="$compcontext"` — a user-supplied context
        //   name becomes the command field before its `$_comps` entry runs.
        set_ccarray_field(3, &compcontext);
        // sh:87  scalar compcontext — look up $_comps[$compcontext]
        let comp = assoc_get("_comps", &compcontext).unwrap_or_default();
        if !comp.is_empty() {
            return dispatch_function_call(&comp, &[]).unwrap_or(1);
        }
        return 1;
    }

    // sh:96-105  -first- entry
    let first_comp = assoc_get("_comps", "-first-").unwrap_or_default();
    if !first_comp.is_empty() {
        // sh:98  `service="${_services[-first-]:--first-}"`.
        let service = assoc_get("_services", "-first-").unwrap_or_else(|| "-first-".to_string());
        let _ = setsparam("service", &service);
        // sh:99  `ccarray[3]=-first-`.
        set_ccarray_field(3, "-first-");
        if dispatch_function_call(&first_comp, &[]).unwrap_or(1) == 0 {
            ret = 0;
        }
        if getsparam("_compskip").as_deref() == Some("all") {
            let _ = setsparam("_compskip", "");
            return ret;
        }
    }

    // sh:110  vared override
    let vared = crate::ported::params::getsparam("compstate[vared]").unwrap_or_default();
    if !vared.is_empty() {
        let _ = crate::ported::params::setsparam("compstate[context]", "vared");
    }

    // sh:114 `ret=1` — whatever the -first- hook returned is discarded here;
    // only the context dispatch below decides `_complete`'s status.
    ret = 1;
    // sh:115-140
    let context = crate::ported::params::getsparam("compstate[context]").unwrap_or_default();
    if context == "command" {
        // sh:116 `curcontext="$oldcontext"` — undo any `ccarray[3]`
        //   written by the `-first-` branch before handing off to
        //   `_normal`, which builds its own command field.
        let _ = setsparam("curcontext", &oldcontext);
        // STALE NOTE CORRECTED (2026-09-20): the text here used to say this is
        // a "direct Rust call, not a shell-function dispatch", so `_normal`
        // "contributes no `$funcstack` entry". It is not a direct call any
        // more — `_normal` (`Base/Core/_normal.rs:66-67`) is the dispatching
        // wrapper over `call_compfn("_normal", …)`, so this goes through
        // `dispatch_function_call` → `doshfunc` and DOES push a `FUNCSTACK`
        // frame. Measured live on this binary, reading `$funcstack` from
        // inside a completion action:
        //
        //   zshrs  … _probecmd (eval) _dispatch _normal _complete _main_complete
        //
        // The `has_fpath_override` gate the old note said was bypassed runs on
        // that same path, so a user's own `_normal` on `$fpath` wins here too.
        // `docs/COMPLETION_DISPATCH.md:193-202` still prints the pre-change
        // table (zshrs `funcstack` without `_normal`, "six-frame deficit") and
        // needs re-measuring; the `zsh_eval_context` half of that table was NOT
        // re-measured here, so only this comment is corrected.
        // sh:117 — `_normal -s && ret=0`. Publish the calling line before
        // entering `_normal`, so the frame it pushes records `_complete:117`
        // instead of the `0` `FnScope::enter` leaves behind.
        crate::compsys::ported::shared::set_sh_lineno(117);
        if _normal(&["-s".to_string()]) == 0 {
            ret = 0;
        }
    } else {
        // sh:122 — `local cname="-${compstate[context]:s/_/-/}-"`. The
        //   `:s` modifier substitutes the FIRST match only (`:gs` would
        //   be global), and no `compstate[context]` value carries more
        //   than one underscore (`brace_parameter`, `array_value`), so
        //   the two spellings agree on every live value.
        let cname = format!("-{}-", context.replacen('_', "-", 1));
        // sh:122's `local` half. `cname` is a Rust binding above, so the
        // shell never saw the declaration and `$parameters` was missing the
        // key — same reason sh:7's five names are declared at the top of
        // this function.
        crate::compsys::ported::shared::declare_locals(&["cname"], 0);
        let _ = setsparam("cname", &cname);
        // sh:124 `ccarray[3]="$cname"` — THE fix: without this the
        //   command field of `curcontext` stays empty for every
        //   non-`command` context, so `:completion:*:*:-subscript-:*`,
        //   `-parameter-`, `-brace-parameter-`, `-math-`, `-condition-`,
        //   `-value-`, `-redirect-`, `-default-` styles are unreachable.
        //   Measured: `echo $path[<TAB>` reported context
        //   `:completion::megacomplete:::` instead of
        //   `:completion::megacomplete:-subscript-::`, so
        //   `zstyle ':completion:*:*:-subscript-:*' tag-order indexes
        //   parameters` never matched and `_subscript`'s two tags
        //   collapsed into a single pass.
        //
        //   (`-command-` was unaffected because `_normal` writes its own
        //   command field — sh:115's branch above restores `oldcontext`
        //   and hands off.)
        set_ccarray_field(3, &cname);
        let mut comp = assoc_get("_comps", &cname).unwrap_or_default();
        let service = assoc_get("_services", &cname).unwrap_or_else(|| cname.clone());
        let _ = setsparam("service", &service);
        // sh:131  `if [[ -z "$comp" ]]` — fall back to `-default-`.
        if comp.is_empty() {
            let cs = getsparam("_compskip").unwrap_or_default();
            if cs.contains("default") {
                let _ = setsparam("_compskip", "");
                return 1;
            }
            comp = assoc_get("_comps", "-default-").unwrap_or_default();
            let default_service =
                assoc_get("_services", "-default-").unwrap_or_else(|| "-default-".to_string());
            let _ = setsparam("service", &default_service);
        }
        if !comp.is_empty() {
            // sh:139 `[[ -n "$comp" ]] && eval "$comp" && ret=0`. Publish the
            // calling line before entering the completer, the same thing the
            // `command` branch does for sh:117: without it `FnScope::enter`'s
            // 0 stands, and every completer reached through this branch saw
            // `_complete:0` in `$functrace` where zsh reports `_complete:139`.
            // Measured inside a `-brace-parameter-` completion:
            //   zsh   (eval):1 _complete:139 _main_complete:218 …
            //   zshrs           _complete:0   _main_complete:218 …
            // (the missing `(eval)` frame is the separate, documented
            // dispatch divergence — docs/COMPLETION_DISPATCH.md, Divergence C
            // — and is not what this line addresses.)
            crate::compsys::ported::shared::set_sh_lineno(139);
            if dispatch_function_call(&comp, &[]).unwrap_or(1) == 0 {
                ret = 0;
            }
        }
    }
    let _ = setsparam("_compskip", "");
    ret
}

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

    #[test]
    fn returns_one_without_executor() {
        let _g = crate::test_util::global_state_lock();
        let _ = setsparam("compcontext", "");
        let _ = crate::ported::params::setsparam("compstate[context]", "command");
        crate::ported::params::setaparam("_comps", Vec::new());
        let _r = _complete_impl();
    }

    /// sh:124 `ccarray[3]="$cname"` on the shape `_main_complete` hands
    /// `_complete`: `:<completer>::` → `:<completer>:-subscript-:`, which
    /// is what makes `:completion:*:*:-subscript-:*` styles match.
    #[test]
    fn ccarray_field_three_is_the_command_field() {
        let _g = crate::test_util::global_state_lock();
        let _ = setsparam("curcontext", ":megacomplete::");
        set_ccarray_field(3, "-subscript-");
        assert_eq!(
            getsparam("curcontext").as_deref(),
            Some(":megacomplete:-subscript-:")
        );
    }

    /// zsh pads a tied array assignment past its end with empty elements
    /// before rejoining on `:` — `curcontext=foo` + `ccarray[3]=bar` is
    /// `foo::bar`, and an empty scalar becomes `::bar`.
    #[test]
    fn ccarray_field_pads_short_context() {
        let _g = crate::test_util::global_state_lock();
        let _ = setsparam("curcontext", "foo");
        set_ccarray_field(3, "bar");
        assert_eq!(getsparam("curcontext").as_deref(), Some("foo::bar"));

        let _ = setsparam("curcontext", "");
        set_ccarray_field(3, "bar");
        assert_eq!(getsparam("curcontext").as_deref(), Some("::bar"));
    }

    /// Fields past the third survive untouched — the argument field
    /// `_main_complete`/`_normal` may already have filled in must not be
    /// truncated by the command-field write.
    #[test]
    fn ccarray_field_preserves_trailing_fields() {
        let _g = crate::test_util::global_state_lock();
        let _ = setsparam("curcontext", ":complete:oldcmd:argfield");
        set_ccarray_field(3, "-parameter-");
        assert_eq!(
            getsparam("curcontext").as_deref(),
            Some(":complete:-parameter-:argfield")
        );
    }
}