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
//! Port of `_set_command` from `Completion/Base/Utility/_set_command`.
//!
//! Full upstream body (31 lines verbatim):
//! ```text
//! sh: 1  #autoload
//! sh: 6  local command
//! sh: 8  command="$words[1]"
//! sh:10  [[ -z "$command" ]] && return
//! sh:12  if (( $+builtins[$command] + $+functions[$command] )); then
//! sh:13    _comp_command1="$command"
//! sh:14    _comp_command="$_comp_command1"
//! sh:15  elif [[ "$command[1]" = '=' ]]; then
//! sh:16    eval _comp_command2\=$command
//! sh:17    _comp_command1="$command[2,-1]"
//! sh:18    _comp_command="$_comp_command2"
//! sh:19  elif [[ "$command" = ..#/* ]]; then
//! sh:20    _comp_command1="${PWD}/$command"
//! sh:21    _comp_command2="${command:t}"
//! sh:22    _comp_command="$_comp_command2"
//! sh:23  elif [[ "$command" = */* ]]; then
//! sh:24    _comp_command1="$command"
//! sh:25    _comp_command2="${command:t}"
//! sh:26    _comp_command="$_comp_command2"
//! sh:27  else
//! sh:28    _comp_command1="$command"
//! sh:29    _comp_command2="$commands[$command]"
//! sh:30    _comp_command="$_comp_command1"
//! sh:31  fi
//! ```
//!
//! Reads `$words[1]`, classifies the command (builtin/function vs
//! `=cmd` vs absolute path vs basename), and publishes the three
//! `_comp_command{,1,2}` params for downstream consumers.

use crate::ported::params::{getaparam, getsparam, setsparam};

/// Reach `_set_command` as a BARE COMMAND WORD, the way every upstream caller
/// writes it — `_set_command` (Completion/Zsh/Context/_redirect sh:5) — 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).
///
/// [`_set_command_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 _set_command() -> i32 {
    crate::compsys::ported::shared::call_compfn("_set_command", &[], || _set_command_impl())
}

/// `_set_command` — classify `$words[1]` and publish
/// `_comp_command`, `_comp_command1`, `_comp_command2`. Returns 0,
/// including when `$words[1]` is empty.
pub fn _set_command_impl() -> i32 {
    let _fn_scope = crate::compsys::ported::shared::FnScope::enter("_set_command");
    let words = getaparam("words").unwrap_or_default();
    // sh:8
    let command = words.first().cloned().unwrap_or_default();
    // sh:10 `[[ -z "$command" ]] && return` — a bare `return` hands back the
    // status of the `[[ ]]` that just succeeded, so an empty command word
    // returns 0 without touching `_comp_command{,1,2}`.
    if command.is_empty() {
        return 0;
    }

    // sh:12 `(( $+builtins[$command] + $+functions[$command] ))`
    //
    // sh:12 reads BOTH `$builtins[$command]` and `$functions[$command]`
    // as subscripts (`$+a + $+b` evaluates both operands), so in zsh each
    // goes through `fetchvalue` → `getparamnode` (Src/params.c:588-595) →
    // `loadparamnode` (c:563-585), clearing that `zsh/parameter`
    // PM_AUTOLOAD stub exactly as the `$commands[...]` reads below do.
    // Consulting the live tables directly skips the fetch, so the load has
    // to be requested here — otherwise a later `${(k)parameters[(R)^a*]}`
    // scan still types both "undefined" (Src/Modules/parameter.c:49-50)
    // and `_parameters -g '^a*'` offers `builtins`/`functions` where zsh,
    // typing them "association-…", does not.
    crate::vm_helper::mark_module_param_used("builtins");
    crate::vm_helper::mark_module_param_used("functions");
    let is_function = crate::ported::utils::getshfunc(&command).is_some();
    let is_builtin = is_known_builtin(&command);
    if is_function || is_builtin {
        // sh:13-14
        let _ = setsparam("_comp_command1", &command);
        let _ = setsparam("_comp_command", &command);
        return 0;
    }

    // sh:12  `=cmd` — `eval _comp_command2\=$command` runs equals-expansion,
    // which is the same `$PATH` command lookup `$commands[...]` performs
    // (`Src/Modules/parameter.c:213 getpmcommand`).
    if command.starts_with('=') {
        let bare = &command[1..];
        // c:Src/Modules/parameter.c:213 `getpmcommand` — the getfn
        // behind the `commands` special hash (`PARTAB` row
        // parameter.rs:4391). `commands` is NOT paramtab-hashed
        // storage, so the previous `getaparam("commands")` returned
        // None and every bare-name lookup here yielded "".
        // See the sh:29 note below for why the fetch's `loadparamnode`
        // side effect has to be requested explicitly.
        crate::vm_helper::mark_module_param_used("commands");
        let resolved: String =
            crate::ported::modules::parameter::getpmcommand(std::ptr::null_mut(), bare)
                .and_then(|pm| pm.u_str.clone())
                .unwrap_or_default();
        let _ = setsparam("_comp_command2", &resolved);
        let _ = setsparam("_comp_command1", bare);
        let _ = setsparam("_comp_command", &resolved);
        return 0;
    }

    // sh:19 — `[[ "$command" = ..#/* ]]`: a `.`, any further dots, then `/`
    // (`./x`, `../x`, `.../x`).
    if command.starts_with('.') && command.trim_start_matches('.').starts_with('/') {
        let pwd = getsparam("PWD").unwrap_or_default();
        let _ = setsparam("_comp_command1", &format!("{}/{}", pwd, command));
        let tail = basename(&command);
        let _ = setsparam("_comp_command2", &tail);
        let _ = setsparam("_comp_command", &tail);
        return 0;
    }

    // sh:23 — `*/*` containing slash
    if command.contains('/') {
        let _ = setsparam("_comp_command1", &command);
        let tail = basename(&command);
        let _ = setsparam("_comp_command2", &tail);
        let _ = setsparam("_comp_command", &tail);
        return 0;
    }

    // sh:27-30 — bare name, lookup in $commands
    // c:Src/Modules/parameter.c:213 `getpmcommand` — same `commands`
    // special-hash getfn as the `=cmd` branch above. This is the value
    // `_redirect` (Completion/Zsh/Context/_redirect:13-14) puts FIRST in
    // `strs`, so an empty `_comp_command2` cost the full-path dispatch
    // key: zsh builds `-redirect-,<,/bin/cat`, zshrs built
    // `-redirect-,<,cat`.
    //
    // sh:29 writes `$commands[$command]`, so in zsh the subscript goes
    // through `fetchvalue` → `getparamnode` (Src/params.c:588-595) →
    // `loadparamnode` (c:563-585), which CLEARS the `zsh/parameter`
    // PM_AUTOLOAD stub and installs the real special node. That side
    // effect is observable: `local -A +h commands` preserves the special
    // only once the stub has been loaded, so `_command_names`'s
    // `local -A +h commands` behaves differently before and after this
    // line has run. `_normal` calls `_set_command` only when
    // `CURRENT != 1`, which is exactly why zsh's command-position
    // completion sees a plain local assoc and argument-position
    // completion sees the live command table. Calling the getfn
    // directly skips the fetch, so the load has to be requested here.
    crate::vm_helper::mark_module_param_used("commands");
    let cmd2: String =
        crate::ported::modules::parameter::getpmcommand(std::ptr::null_mut(), &command)
            .and_then(|pm| pm.u_str.clone())
            .unwrap_or_default();
    let _ = setsparam("_comp_command1", &command);
    let _ = setsparam("_comp_command2", &cmd2);
    let _ = setsparam("_comp_command", &command);
    0
}

/// sh:12's `$+builtins[$command]` test — consult the LIVE builtin table.
/// The previous port used a hardcoded ~34-name allowlist that misclassified
/// every builtin outside it (`print`, `typeset`, `zle`, `setopt`, `zstyle`,
/// `compadd`, `zmodload`, `whence`, `getopts`, …) as non-builtins, so
/// `_set_command` failed to recognise them as the command word. Bug #657.
///
/// The replacement then over-corrected: `createbuiltintable()` is a static
/// superset of `$builtins` (`src/ported/builtin.rs:147-180`), so sh:12 was
/// also true for module builtins the shell reports as unset — `chmod`,
/// `stat`, `zpty`, `zselect` — which sent an EXTERNAL command down sh:13's
/// branch and left `_comp_command2` (the `$commands[$command]` full path)
/// empty. `getpmbuiltin` is the accessor `$+builtins` itself uses; see
/// `shared::plus_builtins`.
fn is_known_builtin(name: &str) -> bool {
    crate::compsys::ported::shared::plus_builtins(name)
}

/// `${command:t}` — basename.
fn basename(s: &str) -> String {
    s.rsplit('/').next().unwrap_or("").to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ported::params::setaparam;

    #[test]
    fn empty_words_returns_zero_and_publishes_nothing() {
        // sh:10 `[[ -z "$command" ]] && return` returns the `[[ ]]` status.
        let _g = crate::test_util::global_state_lock();
        setaparam("words", Vec::new());
        let _ = setsparam("_comp_command", "outer");
        assert_eq!(_set_command_impl(), 0);
        assert_eq!(getsparam("_comp_command").as_deref(), Some("outer"));
    }

    #[test]
    fn slash_path_uses_basename() {
        // sh:23-26
        let _g = crate::test_util::global_state_lock();
        setaparam("words", vec!["/usr/bin/ls".to_string()]);
        let _ = _set_command_impl();
        assert_eq!(getsparam("_comp_command1").as_deref(), Some("/usr/bin/ls"));
        assert_eq!(getsparam("_comp_command2").as_deref(), Some("ls"));
        assert_eq!(getsparam("_comp_command").as_deref(), Some("ls"));
    }

    #[test]
    fn known_builtin_takes_builtin_branch() {
        // sh:12-14
        let _g = crate::test_util::global_state_lock();
        setaparam("words", vec!["cd".to_string()]);
        let _ = _set_command_impl();
        assert_eq!(getsparam("_comp_command1").as_deref(), Some("cd"));
        assert_eq!(getsparam("_comp_command").as_deref(), Some("cd"));
    }

    // ========================================================
    // is_known_builtin — recognition matrix
    // ========================================================

    #[test]
    fn known_builtins_include_navigation_and_io() {
        for name in ["cd", "echo", "pwd", "printf", "read"] {
            assert!(
                is_known_builtin(name),
                "expected {} to register as builtin",
                name
            );
        }
    }

    #[test]
    fn known_builtins_include_set_and_unset_family() {
        for name in ["set", "unset", "export", "alias", "unalias"] {
            assert!(is_known_builtin(name), "{} missing from builtin set", name);
        }
    }

    #[test]
    fn known_builtins_include_control_flow() {
        for name in ["return", "break", "continue", "trap"] {
            assert!(is_known_builtin(name), "{} missing from builtin set", name);
        }
    }

    #[test]
    fn known_builtins_include_test_aliases() {
        // Both `test` and the bracketed form `[` are listed.
        assert!(is_known_builtin("test"));
        assert!(is_known_builtin("["));
    }

    #[test]
    fn known_builtins_includes_source_and_dot_alias() {
        // `source` and `.` are both registered as builtin per sh:9.
        assert!(is_known_builtin("source"));
        assert!(is_known_builtin("."));
    }

    #[test]
    fn unknown_command_is_not_a_builtin() {
        assert!(!is_known_builtin("ls"));
        assert!(!is_known_builtin("grep"));
        assert!(!is_known_builtin(""));
        assert!(!is_known_builtin("foo-bar-baz"));
    }

    #[test]
    fn builtin_name_is_case_sensitive() {
        // POSIX builtin lookup is case-sensitive — uppercase aliases
        // are NOT auto-recognized.
        assert!(!is_known_builtin("CD"));
        assert!(!is_known_builtin("Echo"));
    }

    // ========================================================
    // basename — `${command:t}` analog
    // ========================================================

    #[test]
    fn basename_strips_leading_directory_components() {
        assert_eq!(basename("/usr/bin/ls"), "ls");
        assert_eq!(basename("foo/bar/baz"), "baz");
    }

    #[test]
    fn basename_passes_through_when_no_slash() {
        assert_eq!(basename("plain"), "plain");
    }

    #[test]
    fn basename_empty_input_returns_empty() {
        assert_eq!(basename(""), "");
    }

    #[test]
    fn basename_trailing_slash_yields_empty_string() {
        // rsplit('/').next() on `"foo/"` returns the empty tail.
        assert_eq!(basename("foo/"), "");
    }

    #[test]
    fn basename_handles_root_only() {
        assert_eq!(basename("/"), "");
    }

    // ========================================================
    // _set_command — control-flow branches
    // ========================================================

    #[test]
    fn relative_dotdot_path_uses_pwd_prefix_and_basename() {
        // sh:16-19  command begins with `../`
        let _g = crate::test_util::global_state_lock();
        let _ = crate::ported::params::setsparam("PWD", "/here");
        setaparam("words", vec!["../tools/runme".to_string()]);
        let _ = _set_command_impl();
        assert_eq!(
            getsparam("_comp_command1").as_deref(),
            Some("/here/../tools/runme")
        );
        assert_eq!(getsparam("_comp_command2").as_deref(), Some("runme"));
        assert_eq!(getsparam("_comp_command").as_deref(), Some("runme"));
    }

    /// sh:19 `[[ "$command" = ..#/* ]]` — `..#` is a dot followed by ANY number
    /// of further dots, so `./x` takes the PWD-prefixed branch too, not the
    /// plain `*/*` one of sh:23.
    #[test]
    fn single_dot_relative_path_uses_pwd_prefix() {
        let _g = crate::test_util::global_state_lock();
        let _ = crate::ported::params::setsparam("PWD", "/here");
        setaparam("words", vec!["./runme".to_string()]);
        let _ = _set_command_impl();
        assert_eq!(getsparam("_comp_command1").as_deref(), Some("/here/./runme"));
        assert_eq!(getsparam("_comp_command2").as_deref(), Some("runme"));
        assert_eq!(getsparam("_comp_command").as_deref(), Some("runme"));
    }

    /// sh:12 must answer `(( $+builtins[$command] ))` the way the SHELL's
    /// `$builtins` answers it, not the way the static builtin table does.
    /// `chmod` is a `zsh/files` builtin (c:Src/Modules/files.c:806-824) and
    /// that module is not loaded by default, so both shells report
    /// `$+builtins[chmod]` as 0 and `_set_command` has to fall through to
    /// sh:27-30, publishing `_comp_command2` from `$commands[chmod]`.
    ///
    /// The regression this pins is not cosmetic. sh:13-14 never writes
    /// `_comp_command2` AND never performs the `$commands[...]` fetch, and
    /// that fetch is `getpmcommand`, which is what fills `cmdnamtab` from
    /// `$PATH` under HASH_LIST_ALL (c:Src/Modules/parameter.c:218-222).
    /// `_normal` calls `_set_command` on every ARGUMENT completion, so with
    /// `chmod` taking the builtin branch the command table stayed empty; a
    /// following COMMAND-position completion (`chmod <TAB>`, BACKSPACE,
    /// `<TAB>`) then matched nothing, `makecomplist` returned its error
    /// value, and `do_completion`'s error arm set `clearlist`
    /// (c:Src/Zle/compcore.c:343-348) — wiping a listing zsh still shows.
    /// Measured on the live fpath before the fix, `--jobs 1`: `chmod `,
    /// `mv ` and `ln ` lost the listing zsh keeps, `env ` lost the match zsh
    /// inserts; `cp `, which has no module builtin of that name, was
    /// byte-identical throughout.
    #[test]
    fn module_builtin_name_falls_through_to_the_commands_branch() {
        let _g = crate::test_util::global_state_lock();

        // A one-entry PATH directory holding an executable named `chmod`,
        // so the expected value is exact instead of whatever the host's
        // /bin happens to hold.
        let dir = std::env::temp_dir().join(format!(
            "zshrs_set_command_{}_{}",
            std::process::id(),
            "chmodbranch"
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("scratch PATH dir");
        let exe = dir.join("chmod");
        std::fs::write(&exe, b"#!/bin/sh\nexit 0\n").expect("scratch chmod");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755))
                .expect("chmod +x the scratch chmod");
        }
        let dir_s = dir.to_string_lossy().to_string();

        // Seed cmdnamtab from that directory only, so `$commands[chmod]`
        // resolves without depending on HASH_LIST_ALL or on the ambient
        // $PATH of the test process.
        crate::ported::hashtable::emptycmdnamtable();
        crate::ported::hashtable::fillcmdnamtable(&[dir_s.clone()]);

        assert!(
            !is_known_builtin("chmod"),
            "premise: zsh/files is unloaded, so `$+builtins[chmod]` is 0 \
             (c:Src/Modules/parameter.c:784-792)"
        );

        setaparam("words", vec!["chmod".to_string(), "arg".to_string()]);
        let _ = setsparam("_comp_command1", "");
        let _ = setsparam("_comp_command2", "");
        let _ = setsparam("_comp_command", "");
        let rc = _set_command_impl();

        let c1 = getsparam("_comp_command1").unwrap_or_default();
        let c2 = getsparam("_comp_command2").unwrap_or_default();
        let c = getsparam("_comp_command").unwrap_or_default();

        crate::ported::hashtable::emptycmdnamtable();
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(rc, 0);
        assert_eq!(c1, "chmod", "sh:28");
        assert_eq!(
            c2,
            format!("{}/chmod", dir_s),
            "sh:29 — `_comp_command2` is `$commands[chmod]`; empty here means \
             sh:12 wrongly claimed `chmod` is a builtin"
        );
        assert_eq!(c, "chmod", "sh:30");
    }
}