Skip to main content

ShellExecutor

Struct ShellExecutor 

Source
pub struct ShellExecutor {
Show 73 fields pub aliases: HashMap<String, String>, pub global_aliases: HashMap<String, String>, pub suffix_aliases: HashMap<String, String>, pub expanding_aliases: HashSet<String>, pub loop_signal: Option<LoopSignal>, pub subshell_snapshots: Vec<SubshellSnapshot>, pub last_status: i32, pub variables: HashMap<String, String>, pub arrays: HashMap<String, Vec<String>>, pub assoc_arrays: HashMap<String, IndexMap<String, String>>, pub jobs: JobTable, pub fpath: Vec<PathBuf>, pub zwc_cache: HashMap<PathBuf, ZwcFile>, pub positional_params: Vec<String>, pub history: Option<HistoryEngine>, pub session_histnum: i64, pub traps: HashMap<String, String>, pub options: HashMap<String, bool>, pub completions: HashMap<String, CompSpec>, pub dir_stack: Vec<PathBuf>, pub comp_matches: Vec<CompMatch>, pub comp_groups: Vec<CompGroup>, pub comp_state: CompState, pub zstyles: Vec<ZStyle>, pub comp_words: Vec<String>, pub comp_current: i32, pub comp_prefix: String, pub comp_suffix: String, pub comp_iprefix: String, pub comp_isuffix: String, pub readonly_vars: HashSet<String>, pub var_attrs: HashMap<String, VarAttr>, pub local_save_stack: Vec<(String, Option<String>)>, pub local_array_save_stack: Vec<(String, Option<Vec<String>>)>, pub local_assoc_save_stack: Vec<(String, Option<IndexMap<String, String>>)>, pub local_scope_depth: usize, pub pending_underscore: Option<String>, pub in_dq_context: u32, pub session_history_ids: Vec<i64>, pub autoload_pending: HashMap<String, AutoloadFlags>, pub hook_functions: HashMap<String, Vec<String>>, pub named_dirs: HashMap<String, PathBuf>, pub zptys: HashMap<String, ZptyState>, pub open_fds: HashMap<i32, File>, pub next_fd: i32, pub scheduled_commands: Vec<ScheduledCommand>, pub profile_data: HashMap<String, ProfileEntry>, pub profiling_enabled: bool, pub unix_sockets: HashMap<i32, UnixSocketState>, pub compsys_cache: Option<CompsysCache>, pub compinit_pending: Option<(Receiver<CompInitBgResult>, Instant)>, pub plugin_cache: Option<PluginCache>, pub deferred_compdefs: Vec<Vec<String>>, pub command_hash: HashMap<String, String>, pub pcre_state: PcreState, pub tcp_sessions: TcpSessions, pub zftp: Zftp, pub profiler: Profiler, pub style_table: StyleTable, pub zsh_compat: bool, pub posix_mode: bool, pub worker_pool: Arc<WorkerPool>, pub intercepts: Vec<Intercept>, pub async_jobs: HashMap<u32, Receiver<(i32, String)>>, pub next_async_id: u32, pub defer_stack: Vec<Vec<String>>, pub redirect_scope_stack: Vec<Vec<(i32, i32)>>, pub pending_stdin: Option<String>, pub functions_compiled: HashMap<String, Chunk>, pub function_source: HashMap<String, String>, pub tied_scalar_to_array: HashMap<String, (String, String)>, pub tied_array_to_scalar: HashMap<String, (String, String)>, pub buffer_stack: Vec<String>, /* private fields */
}

Fields§

§aliases: HashMap<String, String>§global_aliases: HashMap<String, String>§suffix_aliases: HashMap<String, String>§expanding_aliases: HashSet<String>

Names whose alias is currently mid-expansion. zsh’s lexer disables an alias from re-expanding inside its own body (so alias ls='ls -la' works without infinite recursion). zshrs expands aliases at run time, so we need an explicit recursion guard. Cleared when expansion of that name finishes.

§loop_signal: Option<LoopSignal>

Set by break/continue keywords when no enclosing loop in the current chunk’s patch lists. Outer-loop builtins (BUILTIN_RUN_SELECT) observe + clear this after each body run.

§subshell_snapshots: Vec<SubshellSnapshot>

Stack of subshell-state snapshots. Each (…) subshell pushes a copy of variables/arrays/assoc_arrays at entry and pops/restores at exit. Without this, (x=inner; …); echo $x shows inner instead of the outer-scope value.

§last_status: i32§variables: HashMap<String, String>§arrays: HashMap<String, Vec<String>>§assoc_arrays: HashMap<String, IndexMap<String, String>>§jobs: JobTable§fpath: Vec<PathBuf>§zwc_cache: HashMap<PathBuf, ZwcFile>§positional_params: Vec<String>§history: Option<HistoryEngine>§session_histnum: i64

Session-relative history line counter. Starts at 0; incremented when an interactive command is recorded. Used by %h/%! in prompt expansion (zsh’s “current history line number”), distinct from the persistent disk history total.

§traps: HashMap<String, String>§options: HashMap<String, bool>§completions: HashMap<String, CompSpec>§dir_stack: Vec<PathBuf>§comp_matches: Vec<CompMatch>§comp_groups: Vec<CompGroup>§comp_state: CompState§zstyles: Vec<ZStyle>§comp_words: Vec<String>§comp_current: i32§comp_prefix: String§comp_suffix: String§comp_iprefix: String§comp_isuffix: String§readonly_vars: HashSet<String>§var_attrs: HashMap<String, VarAttr>

Per-variable attribute table. Tracks the type/flag declared via typeset -i / -F / -E / -L / -R / -Z / -r / -x / -A / -a so the (t) parameter flag can return the canonical zsh type string (integer, float, scalar-left, scalar-readonly-export, …).

§local_save_stack: Vec<(String, Option<String>)>

Stack for local variable save/restore (name, old_value).

§local_array_save_stack: Vec<(String, Option<Vec<String>>)>

Parallel stack for local arr=(...) array save/restore. Some(prev) means restore on exit; None means the name had no outer array binding and should be removed.

§local_assoc_save_stack: Vec<(String, Option<IndexMap<String, String>>)>

Parallel stack for local -A h=(...) assoc save/restore. zsh shadows the outer assoc binding; without this, typeset -A h inside a function leaked into the parent.

§local_scope_depth: usize

Current function scope depth for local tracking.

§pending_underscore: Option<String>

Last arg of the currently-running command, deferred into $_ when the next command dispatches. zsh: $_ reflects the LAST command’s last arg, so echo hi; echo $_ prints hi (not the _ arg of echo $_ itself). Promoted in pop_args and host.exec before the command’s args are read.

§in_dq_context: u32

True while expanding inside a double-quoted context. Set by BUILTIN_EXPAND_TEXT mode 1 around expand_string calls. Used by parameter-flag application to suppress array-only flags ((o)/(O)/(n)/(i)/(M)/(u)) — zsh’s behaviour: those flags only fire in array context.

§session_history_ids: Vec<i64>

IDs of history entries explicitly added during this session via print -s. fc -l uses this to scope listings to just the script-added entries (matches zsh’s -c semantics where session history is the only thing visible to the script).

§autoload_pending: HashMap<String, AutoloadFlags>§hook_functions: HashMap<String, Vec<String>>§named_dirs: HashMap<String, PathBuf>§zptys: HashMap<String, ZptyState>§open_fds: HashMap<i32, File>§next_fd: i32§scheduled_commands: Vec<ScheduledCommand>§profile_data: HashMap<String, ProfileEntry>§profiling_enabled: bool§unix_sockets: HashMap<i32, UnixSocketState>§compsys_cache: Option<CompsysCache>§compinit_pending: Option<(Receiver<CompInitBgResult>, Instant)>§plugin_cache: Option<PluginCache>§deferred_compdefs: Vec<Vec<String>>§command_hash: HashMap<String, String>§pcre_state: PcreState§tcp_sessions: TcpSessions§zftp: Zftp§profiler: Profiler§style_table: StyleTable§zsh_compat: bool

zsh compatibility mode - use .zcompdump, fpath scanning, etc.

§posix_mode: bool

POSIX sh strict mode — no SQLite, no worker pool, no zsh extensions

§worker_pool: Arc<WorkerPool>

Worker thread pool for background tasks (compinit, process subs, etc.)

§intercepts: Vec<Intercept>

AOP intercept table: command/function name → advice chain. Glob patterns supported (e.g. “git ”, “”).

§async_jobs: HashMap<u32, Receiver<(i32, String)>>

Async job handles: id → receiver for (status, stdout)

§next_async_id: u32

Next async job ID

§defer_stack: Vec<Vec<String>>

Defer stack: commands to run on scope exit (LIFO).

§redirect_scope_stack: Vec<Vec<(i32, i32)>>

Per-scope saved-fd stacks for Op::WithRedirectsBegin/End. Each entry is a Vec of (fd, saved_dup_fd) pairs taken from dup(fd) before the redirect was applied; with_redirects_end dup2s them back and closes.

§pending_stdin: Option<String>

Stdin content set by Op::HereDoc(idx) / Op::HereString for the next command/builtin in this VM. Consumed (and cleared) by the next command.

§functions_compiled: HashMap<String, Chunk>

Compiled function bodies — name → fusevm::Chunk. Populated by BUILTIN_REGISTER_FUNCTION (from FunctionDef lowering) and lazily by ZshrsHost::call_function when only an AST exists in self.functions (autoloaded, sourced, etc.). Op::CallFunction dispatches through here.

§function_source: HashMap<String, String>

Canonical source text for functions. Populated by autoload paths (the raw file/cache body), runtime FuncDef compile (the parsed source span), and unfunction removal. Used by introspection (whence, which, typeset -f) instead of reconstructing from a ShellCommand AST. When a function is in functions_compiled but not here, introspection falls back to text::getpermtext(self.functions[name]).

§tied_scalar_to_array: HashMap<String, (String, String)>

Scalar→(array, sep) tie table set up by typeset -T VAR var [SEP]. Used by BUILTIN_SET_VAR to split the assigned scalar on sep and mirror it into array.

§tied_array_to_scalar: HashMap<String, (String, String)>

Array→(scalar, sep) reverse-tie table. Used by BUILTIN_SET_ARRAY to join the array elements with sep and mirror to the scalar side.

§buffer_stack: Vec<String>

ZLE buffer stack — port of bufstack (zsh/Src/builtin.c:4567, LinkList bufstack). print -z (builtin.c:5039-5045) pushes joined args onto it; read -z and getln (builtin.c:6769-6770) pop the top entry as the input source. zsh treats this as a stack shared between the buffer/zle subsystem and the read path.

Implementations§

Source§

impl ShellExecutor

Source

pub fn new() -> ShellExecutor

Source

pub fn enter_posix_mode(&mut self)

Enter POSIX strict mode — drop all SQLite caches, shrink worker pool to minimum. No zsh extensions, no caching, no threads beyond the bare minimum. Dinosaur mode.

Source

pub fn run_hooks(&mut self, hook_name: &str)

Run hook functions (precmd, preexec, chpwd, etc.)

Source

pub fn add_hook(&mut self, hook_name: &str, func_name: &str)

Add a function to a hook

Source

pub fn add_named_dir(&mut self, name: &str, path: &str)

Add a named directory (hash -d name=path)

Source

pub fn host_apply_redirect(&mut self, fd: u8, op_byte: u8, target: &str)

Apply a single redirection. The current scope’s saved-fd vec gets a dup of the original fd so it can be restored by host_redirect_scope_end. op_byte matches fusevm::op::redirect_op::*.

Source

pub fn host_redirect_scope_begin(&mut self, _count: u8)

Push a fresh redirect scope. _count is informational — the actual saved fds are appended by host_apply_redirect into the top scope.

Source

pub fn host_redirect_scope_end(&mut self)

Pop the top redirect scope, restoring saved fds.

Source

pub fn host_set_pending_stdin(&mut self, content: String)

Set up content as stdin (fd 0) for the next command via a real pipe. Used by Op::HereDoc(idx) and Op::HereString.

The pattern: dup2 the read end of a fresh pipe onto fd 0, save the original fd 0 into the active redirect scope so WithRedirectsEnd restores it, and spawn a thread that writes content to the write end and closes it (so the consumer sees EOF after the body). A thread is needed because writing could block on a finite pipe buffer.

Source

pub fn host_exec_external(&mut self, args: &[String]) -> i32

Spawn an external command using zshrs’s full dispatch logic (intercepts, command_hash, redirect handling). Used by ZshrsHost::exec so the bytecode VM’s Op::Exec and Op::CallFunction external fallback get the same semantics as the tree-walker’s execute_external rather than a plain Command::new shortcut. Returns the exit status.

Source

pub fn expand_tilde_named(&self, path: &str) -> String

Expand ~ with named directories

Source

pub fn autoload_function(&mut self, name: &str) -> bool

Try to load a function from ZWC files in fpath. Returns true iff the function ended up resolvable (already loaded, or a ZWC scan landed it in functions_compiled / function_source / self.functions). Callers re-check via function_exists(name) after the call.

Source

pub fn add_fpath(&mut self, path: PathBuf)

Add a directory to fpath

Source

pub fn glob_match_static(s: &str, pattern: &str) -> bool

Static glob match — same logic as glob_match but callable without &self, needed for Rayon parallel iterators that can’t capture &self.

Source

pub fn execute_script_file(&mut self, file_path: &str) -> Result<i32, String>

Execute a script file with bytecode caching — skips lex+parse+compile on cache hit. Bytecode is stored in SQLite keyed by (path, mtime).

Source

pub fn execute_script_zsh_pipeline( &mut self, script: &str, ) -> Result<i32, String>

Execute via the ZshLexer + ZshParser + ZshCompiler pipeline. This is the only execution path; execute_script delegates here.

Source

pub fn execute_script(&mut self, script: &str) -> Result<i32, String>

Source

pub fn function_exists(&self, name: &str) -> bool

Whether name is a known function. Checks the compiled-functions table and the autoload-pending registry — autoload foo should make whence foo/type foo/functions foo recognize foo as a function before it’s actually loaded. Doesn’t trigger autoload itself; use maybe_autoload first if you need to load before introspecting.

Source

pub fn function_definition_text(&self, name: &str) -> Option<String>

Canonical source text for a function. Returns from function_source (populated by autoload paths and runtime FuncDef registration via BUILTIN_REGISTER_COMPILED_FN with body_source). Returns None if no canonical source is on file.

Source

pub fn remove_function(&mut self, name: &str) -> bool

Remove a function from both tables (compiled chunk + canonical source). Returns true iff at least one table held it.

Source

pub fn function_names(&self) -> Vec<String>

Sorted list of every known function name (union of compiled + source).

Source

pub fn dispatch_function_call( &mut self, name: &str, args: &[String], ) -> Option<i32>

Dispatch a function by name through the new (compiled) pipeline. Mirrors ZshrsHost::call_function’s resolution order — checks functions_compiled first, triggers autoload if needed, then falls back to the legacy AST recompile path. Returns None if the name isn’t a function (caller falls back to external dispatch).

This is the synchronous-side replacement for the legacy call_function(&ShellCommand, args). It avoids the AST detour when the new pipeline already has a Chunk for the function.

Source

pub fn run_command_substitution(&mut self, cmd_str: &str) -> String

Source

pub fn maybe_autoload(&mut self, name: &str) -> bool

Check if a function is autoload pending and load it if so. The new pipeline populates functions_compiled directly via load_autoload_function’s side effects; success is functions_compiled.contains_key(name) (not function_exists, which is now true for autoload-pending names regardless of load outcome).

Source§

impl ShellExecutor

Source

pub fn run_trap(&mut self, signal: &str)

Execute trap handlers for a signal

Source

pub fn drain_compinit_bg(&mut self)

Non-blocking drain of background compinit results. Call this before any completion lookup (prompt, tab-complete, etc.). If the background thread hasn’t finished yet, this is a no-op.

Source§

impl ShellExecutor

Source

pub fn zfork(&mut self, flags: ForkFlags) -> Result<ForkResult, Error>

Fork a new process Port of zfork() from exec.c

Source

pub fn zexecve(&self, cmd: &str, args: &[String]) -> !

Execute a command in the current process (exec family) Port of zexecve() from exec.c

Source

pub fn entersubsh(&mut self, flags: SubshellFlags)

Enter a subshell Port of entersubsh() from exec.c

Source

pub fn execarith(&mut self, expr: &str) -> i32

Execute arithmetic expression Port of execarith() from exec.c

Source

pub fn findcmd(&self, name: &str, do_hash: bool) -> Option<String>

Find command in PATH Port of findcmd() from exec.c

Source

pub fn hashcmd(&mut self, name: &str, path: &str)

Hash a command (add to command hash table) Port of hashcmd() from exec.c

Source

pub fn iscom(&self, name: &str) -> bool

Check if command exists and is executable Port of iscom() from exec.c

Source

pub fn closem(&self, exceptions: &[i32])

Close all file descriptors except stdin/stdout/stderr Port of closem() from exec.c

Source

pub fn mpipe(&self) -> Result<(i32, i32), Error>

Create a pipe Port of mpipe() from exec.c

Source

pub fn addfd( &self, fd: i32, target_fd: i32, mode: RedirMode, ) -> Result<(), Error>

Add a file descriptor for redirection Port of addfd() from exec.c

Source

pub fn gethere(&mut self, terminator: &str, strip_tabs: bool) -> String

Get heredoc content Port of gethere() from exec.c

Source

pub fn getherestr(&mut self, word: &str) -> String

Get herestring content Port of getherestr() from exec.c

Source

pub fn resolvebuiltin(&self, name: &str) -> Option<BuiltinType>

Resolve a builtin command Port of resolvebuiltin() from exec.c

Source

pub fn cancd(&self, path_str: &str) -> bool

Check if cd is possible Port of cancd() from exec.c

Source

pub fn commandnotfound(&mut self, name: &str, args: &[String]) -> i32

Command not found handler Port of commandnotfound() from exec.c

Trait Implementations§

Source§

impl Default for ShellExecutor

Source§

fn default() -> ShellExecutor

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

Source§

fn deserialize( &self, deserializer: &mut D, ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
Source§

impl<T> Finish for T

Source§

fn finish(self)

Does nothing but move self, equivalent to drop.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Gets the layout of the type.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The type for metadata in pointers and references to Self.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<U, T> ToOwnedObj<U> for T
where U: FromObjRef<T>,

Source§

fn to_owned_obj(&self, data: FontData<'_>) -> U

Convert this type into T, using the provided data to resolve any offsets.
Source§

impl<U, T> ToOwnedTable<U> for T
where U: FromTableRef<T>,

Source§

fn to_owned_table(&self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more