Skip to main content

shell/
zsh.rs

1//! The Zsh shell implementation.
2//!
3//! Zsh is a peer of Bash, not a flavor of it: it owns its builtin table
4//! (`where`, `whence`, `which`, `print`, and zsh-flavored `echo`, `alias`,
5//! `export`, `type`), its dialect (messages and prompt), and its grammar.
6//! The grammar today is the shared sh-family grammar ([`brush_parser`]),
7//! which is the honest state of affairs for a first zsh: zsh syntax was
8//! never formally specified and no maintained zsh grammar crate exists, so
9//! zsh-specific constructs (glob qualifiers, extended globbing,
10//! `=command` expansion, prompt escapes) are future work owned by this
11//! implementation on top of the shared [`ShellCore`](crate::core::ShellCore).
12//!
13//! What already differs from Bash, verified against a real zsh:
14//! - `echo` interprets backslash escapes by default (BSD behavior);
15//! - `alias` lists as `name='expansion'` without a prefix;
16//! - `export` lists as `export NAME=value`;
17//! - `type` says `name is an alias for ...`;
18//! - the `where`/`whence`/`which`/`print` builtins;
19//! - the prompt (`user@host:~/path% ` with the home directory abbreviated
20//!   to `~`).
21
22use engine::{Input, Output, Terminal, VirtualPath};
23use os::{Credentials, ExitStatus, UnixOs};
24
25use crate::core::{ShellCore, ShellDialect};
26
27/// The Zsh-flavored shell.
28pub struct Zsh<'os> {
29    /// The shared execution core in the Zsh dialect.
30    core: ShellCore<'os>,
31}
32
33impl<'os> Zsh<'os> {
34    /// Creates a Zsh shell for a session.
35    pub fn new(os: &'os UnixOs, credentials: Credentials) -> Result<Self, os::OsError> {
36        let mut core = ShellCore::new(os, credentials, zsh_dialect())?;
37        // Scripts run through this shell, not a separate interpreter.
38        core.install_shell_bindings();
39        // Startup files define the session's aliases and functions.
40        core.source_startup_files();
41        Ok(Self { core })
42    }
43}
44
45/// The behavior of `/bin/zsh`: the Zsh dialect as a program
46/// (`#!/bin/zsh` is interpreted by Zsh). Scripts and `zsh -c` invocations
47/// run through the same implementation as interactive commands.
48pub struct ZshInterpreter;
49
50impl os::runtime::Command for ZshInterpreter {
51    fn name(&self) -> &'static str {
52        "zsh"
53    }
54
55    fn execute(
56        &self,
57        context: &mut os::runtime::CommandContext<'_, '_, '_, '_>,
58    ) -> Result<os::runtime::ExitStatus, os::OsError> {
59        crate::core::run_interpreter_invocation(
60            context.os,
61            context.credentials.clone(),
62            zsh_dialect(),
63            context.cwd,
64            context.argv,
65            &mut *context.stdin,
66            &mut *context.stdout,
67            &mut *context.stderr,
68        )
69    }
70}
71
72/// The Zsh dialect: identity, messages, and the builtin table.
73fn zsh_dialect() -> ShellDialect {
74    ShellDialect {
75        name: "zsh",
76        command_not_found: |name| format!("zsh: command not found: {name}\n"),
77        run_builtin: zsh_run_builtin,
78        system_rc: "/etc/zshrc",
79        user_rc: ".zshrc",
80        echo_escapes_default: true,
81        export_prefix: "export ",
82        alias_prefix: "",
83    }
84}
85
86/// Whether a name is a Zsh builtin.
87fn zsh_is_builtin(name: &str) -> bool {
88    matches!(
89        name,
90        "cd" | "pwd"
91            | "export"
92            | "history"
93            | "alias"
94            | "unalias"
95            | "jobs"
96            | "fg"
97            | "bg"
98            | "wait"
99            | "hash"
100            | "echo"
101            | "print"
102            | "clear"
103            | ":"
104            | "dirs"
105            | "pushd"
106            | "popd"
107            | "unset"
108            | "source"
109            | "."
110            | "whence"
111            | "which"
112            | "where"
113            | "type"
114            | "exit"
115    )
116}
117
118/// Dispatches a Zsh builtin (function → builtin → external).
119fn zsh_run_builtin(
120    core: &mut ShellCore,
121    name: &str,
122    argv: &[String],
123    stdin: &mut dyn Input,
124    stdout: &mut dyn Output,
125    stderr: &mut dyn Output,
126) -> Option<ExitStatus> {
127    let status = match name {
128        // Shared mechanisms, verified identical in Bash and Zsh.
129        "cd" => core.cd_to(argv, stdout, stderr),
130        "pwd" => core.pwd_of(stdout),
131        "jobs" => core.list_jobs(stdout),
132        "fg" => core.foreground_job(argv, stdout, stderr),
133        "bg" => core.background_job(argv, stdout, stderr),
134        "wait" => core.wait_for_jobs(argv, stderr),
135        "hash" => core.hash_table(argv, stdout, stderr),
136        "dirs" => core.print_dirs(stdout),
137        "pushd" => core.push_directory(argv, stdout, stderr),
138        "popd" => core.pop_directory(argv, stdout, stderr),
139        "unset" => core.unset_names(argv, stderr),
140        "source" | "." => core.source_file(argv, stdin, stdout, stderr),
141        "clear" => core.clear_screen(stdout),
142        ":" => core.null_command(),
143        // Zsh-owned semantics on shared mechanisms (the dialect carries the
144        // phrasing).
145        "echo" => core.builtin_echo(argv, stdout),
146        "print" => zsh_print(argv, stdout),
147        "export" => core.builtin_export(argv, stdout, stderr),
148        "history" => core.builtin_history(stdout),
149        "alias" => core.builtin_alias(argv, stdout, stderr),
150        "unalias" => core.builtin_unalias(argv, stderr),
151        "whence" => zsh_whence(core, argv, stdout, stderr),
152        "which" => zsh_which(core, argv, stdout, stderr),
153        "where" => zsh_where(core, argv, stdout, stderr),
154        "type" => zsh_type(core, argv, stdout, stderr),
155        "exit" => core.request_exit(argv.get(1).map(String::as_str)),
156        _ => return None,
157    };
158    Some(status)
159}
160
161/// The Zsh `print` builtin: like `echo`, with `-n` (no newline) and `-r`
162/// (no escape processing).
163fn zsh_print(argv: &[String], stdout: &mut dyn Output) -> ExitStatus {
164    let mut output = String::new();
165    let mut no_newline = false;
166    let mut start = 1;
167    while let Some(argument) = argv.get(start) {
168        if argument == "-n" && !no_newline {
169            no_newline = true;
170            start += 1;
171        } else if argument == "-r" {
172            start += 1;
173        } else {
174            break;
175        }
176    }
177    for (index, argument) in argv.iter().skip(start).enumerate() {
178        if index > 0 {
179            output.push(' ');
180        }
181        output.push_str(argument);
182    }
183    if !no_newline {
184        output.push('\n');
185    }
186    let _ = stdout.write(output.as_bytes());
187    ExitStatus::SUCCESS
188}
189
190/// The Zsh `whence` builtin: prints how the name resolves — the alias
191/// expansion, the name for a builtin or function, or the first path.
192fn zsh_whence(
193    core: &mut ShellCore,
194    argv: &[String],
195    stdout: &mut dyn Output,
196    stderr: &mut dyn Output,
197) -> ExitStatus {
198    let mut exit_status = ExitStatus::SUCCESS;
199    for name in argv.iter().skip(1) {
200        let resolution = core.resolve_name(name, zsh_is_builtin);
201        if let Some(alias) = resolution.alias {
202            let _ = stdout.write(format!("{alias}\n").as_bytes());
203            continue;
204        }
205        if resolution.function || resolution.builtin || !resolution.paths.is_empty() {
206            let _ = stdout.write(format!("{name}\n").as_bytes());
207            continue;
208        }
209        let _ = stderr;
210        exit_status = ExitStatus::FAILURE;
211    }
212    exit_status
213}
214
215/// The Zsh `which` builtin: reports the resolution like zsh — an alias as
216/// `name: aliased to <expansion>`, a builtin as `name: shell built-in
217/// command`, and the first filesystem hit from `PATH`.
218fn zsh_which(
219    core: &mut ShellCore,
220    argv: &[String],
221    stdout: &mut dyn Output,
222    stderr: &mut dyn Output,
223) -> ExitStatus {
224    let mut exit_status = ExitStatus::SUCCESS;
225    for name in argv.iter().skip(1) {
226        let resolution = core.resolve_name(name, zsh_is_builtin);
227        if let Some(alias) = resolution.alias {
228            let _ = stdout.write(format!("{name}: aliased to {alias}\n").as_bytes());
229            continue;
230        }
231        if resolution.function {
232            let _ = stdout.write(format!("{name}: shell function\n").as_bytes());
233            continue;
234        }
235        if resolution.builtin {
236            let _ = stdout.write(format!("{name}: shell built-in command\n").as_bytes());
237            continue;
238        }
239        if let Some(path) = resolution.paths.into_iter().next() {
240            let _ = stdout.write(format!("{path}\n").as_bytes());
241        } else {
242            let _ = stderr.write(format!("{name} not found\n").as_bytes());
243            exit_status = ExitStatus::FAILURE;
244        }
245    }
246    exit_status
247}
248
249/// The Zsh `where` builtin: prints every location of a command — an alias
250/// as `name: aliased to <expansion>`, the builtin as `name: shell built-in
251/// command`, and each filesystem hit from `PATH`, in order.
252fn zsh_where(
253    core: &mut ShellCore,
254    argv: &[String],
255    stdout: &mut dyn Output,
256    stderr: &mut dyn Output,
257) -> ExitStatus {
258    let mut exit_status = ExitStatus::SUCCESS;
259    for name in argv.iter().skip(1) {
260        let resolution = core.resolve_name(name, zsh_is_builtin);
261        let mut found = false;
262        if let Some(alias) = &resolution.alias {
263            let _ = stdout.write(format!("{name}: aliased to {alias}\n").as_bytes());
264            found = true;
265        }
266        if resolution.function {
267            let _ = stdout.write(format!("{name}: shell function\n").as_bytes());
268            found = true;
269        }
270        if resolution.builtin {
271            let _ = stdout.write(format!("{name}: shell built-in command\n").as_bytes());
272            found = true;
273        }
274        for path in resolution.paths {
275            let _ = stdout.write(format!("{path}\n").as_bytes());
276            found = true;
277        }
278        if !found {
279            let _ = stderr.write(format!("{name} not found\n").as_bytes());
280            exit_status = ExitStatus::FAILURE;
281        }
282    }
283    exit_status
284}
285
286/// The Zsh `type` builtin: reports how a name would be resolved, in zsh's
287/// phrasing (`name is an alias for ...`).
288fn zsh_type(
289    core: &mut ShellCore,
290    argv: &[String],
291    stdout: &mut dyn Output,
292    stderr: &mut dyn Output,
293) -> ExitStatus {
294    let mut exit_status = ExitStatus::SUCCESS;
295    for name in argv.iter().skip(1) {
296        let resolution = core.resolve_name(name, zsh_is_builtin);
297        if let Some(alias) = resolution.alias {
298            let _ = stdout.write(format!("{name} is an alias for {alias}\n").as_bytes());
299            continue;
300        }
301        if resolution.function {
302            let _ = stdout.write(format!("{name} is a shell function\n").as_bytes());
303            continue;
304        }
305        if resolution.builtin {
306            let _ = stdout.write(format!("{name} is a shell builtin\n").as_bytes());
307            continue;
308        }
309        if let Some(path) = resolution.paths.into_iter().next() {
310            let _ = stdout.write(format!("{name} is {path}\n").as_bytes());
311        } else {
312            let _ = stderr.write(format!("{name} not found\n").as_bytes());
313            exit_status = ExitStatus::FAILURE;
314        }
315    }
316    exit_status
317}
318
319impl<'os> crate::Shell for Zsh<'os> {
320    fn name(&self) -> &'static str {
321        "zsh"
322    }
323
324    fn actor(&self) -> engine::ActorId {
325        self.core.credentials().actor()
326    }
327
328    fn environment(&self) -> &os::Environment {
329        self.core.environment()
330    }
331
332    fn engine(&self) -> &engine::Engine {
333        self.core.os().engine()
334    }
335
336    fn boot_time(&self) -> engine::Timestamp {
337        self.core.os().boot_time()
338    }
339
340    fn hostname(&self) -> String {
341        crate::core::hostname_from_etc(self.core.os())
342    }
343
344    fn cwd(&self) -> &VirtualPath {
345        self.core.cwd()
346    }
347
348    fn banner(&self) -> Option<String> {
349        Some(format!(
350            "Last login: {} on ttys000\n",
351            crate::core::format_login_line(self.core.os().boot_time())
352        ))
353    }
354
355    fn prompt(&self, hostname: &str) -> String {
356        // Zsh abbreviates the home directory to `~` in the prompt.
357        let home = self.core.credentials().user().home();
358        let cwd = self.core.cwd();
359        let display = if cwd.to_string() == home {
360            "~".to_owned()
361        } else if let Some(rest) = cwd.to_string().strip_prefix(&format!("{home}/")) {
362            format!("~/{rest}")
363        } else {
364            cwd.to_string()
365        };
366        format!(
367            "{}@{}:{}{} ",
368            self.core.credentials().username(),
369            hostname,
370            display,
371            '%'
372        )
373    }
374
375    fn set_terminal_size(&mut self, rows: u16, cols: u16) {
376        self.core.set_terminal_size(rows, cols);
377    }
378
379    fn execute(
380        &mut self,
381        line: &str,
382        stdin: &mut dyn Input,
383        stdout: &mut dyn Output,
384        stderr: &mut dyn Output,
385    ) -> ExitStatus {
386        self.core.execute(line, stdin, stdout, stderr)
387    }
388
389    fn execute_with_terminal(
390        &mut self,
391        line: &str,
392        stdin: &mut dyn Input,
393        stdout: &mut dyn Output,
394        stderr: &mut dyn Output,
395        terminal: Option<&mut dyn Terminal>,
396    ) -> ExitStatus {
397        self.core
398            .execute_with_terminal(line, stdin, stdout, stderr, terminal)
399    }
400
401    fn take_exit_status(&mut self) -> Option<ExitStatus> {
402        self.core.take_exit_request()
403    }
404
405    fn history(&self) -> &[String] {
406        self.core.history()
407    }
408
409    fn record_history(&mut self, line: &str) {
410        self.core.record_history(line);
411    }
412
413    fn needs_continuation(&self, input: &str) -> bool {
414        crate::core::needs_continuation(input)
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::Shell;
422    use engine::{BytesInput, BytesOutput, Timestamp};
423    use os::HostIdentity;
424    use os::linux::Linux;
425
426    fn test_shell() -> Zsh<'static> {
427        let linux = Box::leak(Box::new(
428            Linux::with_identity(
429                &HostIdentity::new("demo", "demo-host"),
430                Timestamp::from_nanos(1_000_000),
431            )
432            .unwrap(),
433        ));
434        let credentials = linux
435            .unix()
436            .users()
437            .authenticate("demo", "demo", linux.unix().groups())
438            .unwrap();
439        Zsh::new(linux.unix(), credentials).unwrap()
440    }
441
442    fn run(shell: &mut Zsh<'static>, line: &str) -> (ExitStatus, Vec<u8>, Vec<u8>) {
443        let mut stdin = BytesInput::new(b"");
444        let mut stdout = BytesOutput::new();
445        let mut stderr = BytesOutput::new();
446        let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
447        (status, stdout.into_bytes(), stderr.into_bytes())
448    }
449
450    #[test]
451    fn zsh_prompt_abbreviates_home() {
452        let mut shell = test_shell();
453        assert_eq!(shell.prompt("demo-host"), "demo@demo-host:~% ");
454        run(&mut shell, "cd /etc");
455        assert_eq!(shell.prompt("demo-host"), "demo@demo-host:/etc% ");
456    }
457
458    #[test]
459    fn zsh_echo_interpret_escapes_by_default() {
460        let mut shell = test_shell();
461        let (_, out, _) = run(&mut shell, "echo 'a\\tb'");
462        assert_eq!(out, b"a\tb\n");
463        let (_, out, _) = run(&mut shell, "echo -E 'a\\tb'");
464        assert_eq!(out, b"a\\tb\n");
465    }
466
467    #[test]
468    fn zsh_print_builtin() {
469        let mut shell = test_shell();
470        let (_, out, _) = run(&mut shell, "print hello world");
471        assert_eq!(out, b"hello world\n");
472        let (_, out, _) = run(&mut shell, "print -n no-newline");
473        assert_eq!(out, b"no-newline");
474    }
475
476    #[test]
477    fn zsh_alias_lists_without_prefix() {
478        let mut shell = test_shell();
479        run(&mut shell, "alias ll='ls -l'");
480        let (_, out, _) = run(&mut shell, "alias");
481        assert_eq!(out, b"ll='ls -l'\n");
482    }
483
484    #[test]
485    fn zsh_where_reports_all_locations() {
486        let mut shell = test_shell();
487        run(&mut shell, "alias ll='ls -l'");
488        let (status, out, _) = run(&mut shell, "where ll");
489        assert_eq!(status, ExitStatus::SUCCESS);
490        assert_eq!(out, b"ll: aliased to ls -l\n");
491        let (_, out, _) = run(&mut shell, "where echo");
492        assert_eq!(out, b"echo: shell built-in command\n/usr/bin/echo\n");
493        let (status, _, err) = run(&mut shell, "where foobar");
494        assert_eq!(status, ExitStatus::FAILURE);
495        assert_eq!(err, b"foobar not found\n");
496    }
497
498    #[test]
499    fn zsh_which_reports_like_zsh() {
500        let mut shell = test_shell();
501        let (_, out, _) = run(&mut shell, "which cd");
502        assert_eq!(out, b"cd: shell built-in command\n");
503        let (_, out, _) = run(&mut shell, "which ls");
504        assert_eq!(out, b"/usr/bin/ls\n");
505    }
506
507    #[test]
508    fn zsh_whence_prints_plain_resolution() {
509        let mut shell = test_shell();
510        run(&mut shell, "alias ll='ls -l'");
511        let (_, out, _) = run(&mut shell, "whence ll");
512        assert_eq!(out, b"ls -l\n");
513        let (_, out, _) = run(&mut shell, "whence cd");
514        assert_eq!(out, b"cd\n");
515    }
516
517    #[test]
518    fn zsh_type_uses_zsh_phrasing() {
519        let mut shell = test_shell();
520        run(&mut shell, "alias ll='ls -l'");
521        let (_, out, _) = run(&mut shell, "type ll");
522        assert_eq!(out, b"ll is an alias for ls -l\n");
523        let (_, out, _) = run(&mut shell, "type cd");
524        assert_eq!(out, b"cd is a shell builtin\n");
525    }
526
527    #[test]
528    fn zsh_export_lists_as_export() {
529        let mut shell = test_shell();
530        run(&mut shell, "export FOO=bar");
531        let (_, out, _) = run(&mut shell, "export");
532        let text = String::from_utf8(out).unwrap();
533        assert!(text.lines().any(|line| line == "export FOO=bar"));
534    }
535}