mxsh 0.1.0

Embeddable POSIX-style shell parser and runtime
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
//! Advanced borrowed-runtime embedding and planning APIs.
//!
//! Most embedders should start with [`crate::Shell`] and [`crate::ShellBuilder`].
//! This module keeps the lower-level session and planning APIs available for
//! hosts that intentionally need separate parse, prepare, and execute phases or
//! one runtime shared across many sessions.

use std::io;
use std::path::Path;
use std::sync::Arc;

use crate::ast::{Command as AstCommand, Program, SimpleCommand};
#[cfg(feature = "frontend")]
use crate::embed::{HistoryAppender, interactive_buffer_needs_more_input};
use crate::embed::{NamedFileDescriptor, RunOutcome, StdioConfig, capture_outcome_for_state};
use crate::policy::{
    ShellIdentity, ShellLanguage, ShellOptionSchema, ShellOptions, ShellSecurityPolicy,
    StartupPolicy, StartupSources,
};
use crate::runtime::{Runtime, fd::FileDescriptor};
use crate::shell;

pub use crate::embed::ShellBlueprint;
pub use crate::plan::{
    CommandResolutionError, DeferredExpansion, DeferredPipelineStageWork, DeferredReason,
    ExecutionPlan as PreparedProgram, PipelineExecutionPlan as PreparedPipeline, PlannedAndOr,
    PlannedCommandList, PlannedLazyAst, PlannedLazyNode, PlannedPipeline, PlannedPipelineStage,
    PlannedProgram, PlannedSimpleCommand, PlannedSimpleCommandKind, PreparedExternalStagePlan,
};

/// Detached mutable shell session snapshot for save-and-restore flows.
#[derive(Debug, Clone)]
pub struct SessionSnapshot {
    pub(crate) state: shell::ShellState,
}

/// Mutable shell session state for advanced borrowed-runtime embedding.
///
/// Most embedders should prefer [`crate::Shell`]. Use `SessionState` when you
/// need to share one runtime across sessions or intentionally separate planning
/// from execution.
#[derive(Debug, Clone)]
pub struct SessionState {
    pub(crate) definition: Arc<crate::embed::ShellDefinition>,
    pub(crate) state: shell::ShellState,
}

impl Default for SessionState {
    fn default() -> Self {
        ShellBlueprint::default().new_session()
    }
}

impl SessionState {
    /// Create a default mutable shell session.
    pub fn new() -> Self {
        Self::default()
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn state_mut(&mut self) -> &mut shell::ShellState {
        &mut self.state
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn state(&self) -> &shell::ShellState {
        &self.state
    }

    #[cfg(feature = "frontend")]
    fn update_definition(&mut self, update: impl FnOnce(&mut crate::embed::ShellDefinition)) {
        let definition = Arc::make_mut(&mut self.definition);
        update(definition);
        self.state.definition = Arc::clone(&self.definition);
    }

    pub fn identity(&self) -> &ShellIdentity {
        &self.definition.identity
    }

    pub fn shell_name(&self) -> &str {
        self.identity().name()
    }

    pub fn option_schema(&self) -> &ShellOptionSchema {
        &self.definition.option_schema
    }

    pub fn startup_sources(&self) -> &StartupSources {
        &self.definition.startup_sources
    }

    pub fn security_policy(&self) -> ShellSecurityPolicy {
        self.definition.security_policy
    }

    pub fn language(&self) -> &ShellLanguage {
        &self.definition.language
    }

    pub fn initialize<R: Runtime>(&mut self, runtime: &mut R) {
        shell::initialize_shell_session(&mut self.state, runtime);
    }

    /// Return the active shell frame: `argv[0]` followed by positional parameters.
    pub fn frame(&self) -> &[String] {
        &self.state.frame
    }

    /// Execute one parsed program directly.
    pub fn run_program<R: Runtime>(&mut self, runtime: &mut R, program: &Program) -> RunOutcome {
        capture_outcome_for_state(&mut self.state, |state| {
            let status = shell::run_program(state, runtime, program);
            state.set_last_status(status);
            status
        })
    }

    /// Parse and execute shell source text.
    ///
    /// This is the convenience API that combines parsing, planning, and
    /// execution in one step.
    pub fn run<R: Runtime>(&mut self, runtime: &mut R, text: &str) -> RunOutcome {
        capture_outcome_for_state(&mut self.state, |state| {
            let status = shell::run_string(state, runtime, text);
            state.set_last_status(status);
            status
        })
    }

    pub fn env_get(&self, key: &str) -> Option<&str> {
        self.state.env_get(key)
    }

    pub fn exported_env(&self) -> Vec<(String, String)> {
        self.state.exported_env()
    }

    pub fn aliases(&self) -> Vec<(String, String)> {
        self.state.aliases()
    }

    pub fn alias(&self, name: &str) -> Option<&str> {
        self.state.alias(name)
    }

    pub fn functions(&self) -> Vec<(String, AstCommand)> {
        self.state.functions()
    }

    pub fn function(&self, name: &str) -> Option<&AstCommand> {
        self.state.function(name)
    }

    pub fn argv0(&self) -> Option<&str> {
        self.state.argv0()
    }

    pub fn positional_parameters(&self) -> &[String] {
        self.state.positional_parameters()
    }

    pub fn inherited_file_descriptors(&self) -> Vec<(i32, FileDescriptor)> {
        self.state.inherited_fd_entries()
    }

    pub fn named_inherited_file_descriptors(&self) -> Vec<NamedFileDescriptor> {
        self.state.named_inherited_fd_entries()
    }

    pub fn named_inherited_file_descriptor(&self, name: &str) -> Option<NamedFileDescriptor> {
        self.state.named_inherited_fd(name)
    }

    pub fn snapshot(&self) -> SessionSnapshot {
        SessionSnapshot {
            state: self.state.detached_session(),
        }
    }

    pub fn restore(&mut self, snapshot: SessionSnapshot) {
        self.state = snapshot.state;
        self.state.definition = Arc::clone(&self.definition);
    }

    pub fn fork(&self) -> Self {
        Self {
            definition: Arc::clone(&self.definition),
            state: self.state.detached_session(),
        }
    }

    pub fn current_dir(&self) -> &Path {
        &self.state.cwd
    }

    pub fn options(&self) -> ShellOptions {
        ShellOptions::from_bits(self.state.options)
    }

    pub fn has_option(&self, option: ShellOptions) -> bool {
        (self.state.options & option.bits()) != 0
    }

    pub fn interactive(&self) -> bool {
        self.state.interactive
    }

    pub fn manage_signals(&self) -> bool {
        self.state.manage_signals
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn set_manage_signals(&mut self, manage_signals: bool) {
        self.state.manage_signals = manage_signals;
    }

    pub fn stdio(&self) -> StdioConfig {
        StdioConfig {
            stdin: self.state.stdin_fd,
            stdout: self.state.stdout_fd,
            stderr: self.state.stderr_fd,
        }
    }

    pub fn last_status(&self) -> i32 {
        self.state.last_status
    }

    pub fn exit_code(&self) -> Option<i32> {
        (self.state.exit_code >= 0).then_some(self.state.exit_code)
    }

    pub fn last_background_pid(&self) -> Option<u32> {
        self.state.last_background_pid()
    }

    pub fn startup_policy(&self) -> StartupPolicy {
        self.definition.startup_policy
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn has_explicit_startup_policy(&self) -> bool {
        self.definition.startup_policy_explicit
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn warn_vi_unsupported_once(&mut self) {
        shell::maybe_warn_vi_unsupported(&mut self.state);
    }

    #[cfg(feature = "frontend")]
    pub fn run_interactive<R: Runtime>(&mut self, runtime: &mut R) -> io::Result<RunOutcome> {
        let mut frontend = crate::frontend::FdFrontend;
        self.run_interactive_with_frontend(runtime, &mut frontend)
    }

    #[cfg(feature = "frontend")]
    pub fn run_interactive_with_frontend<R: Runtime, F: crate::frontend::InteractiveFrontend>(
        &mut self,
        runtime: &mut R,
        frontend: &mut F,
    ) -> io::Result<RunOutcome> {
        frontend.on_unsupported_vi_mode(self)?;
        let mut pending = String::new();
        loop {
            if pending.is_empty() && self.has_option(ShellOptions::NOTIFY) {
                shell::maybe_notify_jobs(&mut self.state, runtime);
            }
            let prompt = frontend.prompt(self, !pending.is_empty())?;
            let input = frontend.read_line(self, &prompt)?;
            let Some(input) = input else {
                if pending.is_empty() && self.has_option(ShellOptions::IGNOREEOF) {
                    self.write_stderr("Use \"exit\" to leave the shell.")?;
                    continue;
                }
                if !pending.is_empty() {
                    let result = self.run(runtime, &pending);
                    return Ok(result);
                }
                let status = self.state.last_status;
                return Ok(RunOutcome::empty_from_state(status, &self.state));
            };
            if !pending.is_empty() {
                pending.push('\n');
            }
            pending.push_str(&input);
            if interactive_buffer_needs_more_input(&pending, self.language()) {
                continue;
            }
            frontend.append_history(self, &pending)?;
            let result = self.run(runtime, &pending);
            pending.clear();
            if result.exit_code.is_some() {
                return Ok(result);
            }
        }
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn set_startup_policy(&mut self, startup_policy: StartupPolicy) {
        self.update_definition(|definition| {
            definition.startup_policy = startup_policy;
            definition.startup_policy_explicit = true;
        });
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn set_history_path<P: Into<std::path::PathBuf>>(
        &mut self,
        history_path: Option<P>,
    ) {
        let history_path = history_path.map(Into::into);
        self.update_definition(|definition| definition.history_path = history_path);
    }

    pub fn history_path(&self) -> Option<&Path> {
        self.definition.history_path.as_deref()
    }

    #[cfg(feature = "frontend")]
    pub(crate) fn history_appender(&self) -> Option<&Arc<HistoryAppender>> {
        self.definition.history_appender.as_ref()
    }

    pub fn write_stdout(&self, message: &str) -> io::Result<()> {
        self.state.stdout_fd.write_str(message)
    }

    pub fn write_stdout_line(&self, message: &str) -> io::Result<()> {
        self.state.stdout_fd.write_line(message)
    }

    pub fn write_stderr(&self, message: &str) -> io::Result<()> {
        self.state.stderr_fd.write_line(message)
    }
}

/// Advanced planning adapter for borrowed-runtime embedding.
///
/// Most embedders should prefer [`crate::Shell`]. Use `Planner` when you
/// intentionally need to separate parsing, planning, inspection, and execution
/// while borrowing a [`SessionState`] and [`Runtime`].
pub struct Planner<'session, 'runtime, R> {
    session: &'session mut SessionState,
    runtime: &'runtime mut R,
}

impl<'session, 'runtime, R: Runtime> Planner<'session, 'runtime, R> {
    /// Create a planner over one mutable session and one mutable runtime.
    pub fn new(session: &'session mut SessionState, runtime: &'runtime mut R) -> Self {
        Self { session, runtime }
    }

    /// Plan one simple command using the current session state and runtime.
    pub fn prepare_simple_command<'ast>(
        &mut self,
        command: &'ast SimpleCommand,
    ) -> Result<PlannedSimpleCommand<'ast>, i32> {
        shell::plan_simple_command(&mut self.session.state, self.runtime, command)
    }

    /// Build an execution plan for a parsed pipeline.
    pub fn prepare_pipeline<'ast>(
        &mut self,
        pipeline: &'ast crate::ast::Pipeline,
    ) -> PreparedPipeline<'ast> {
        crate::plan::PipelineExecutionPlan {
            pipeline,
            inner: shell::build_pipeline_execution(&mut self.session.state, self.runtime, pipeline),
        }
    }

    /// Build an execution plan for a parsed program.
    pub fn prepare<'ast>(&mut self, program: &'ast Program) -> PreparedProgram<'ast> {
        crate::plan::ExecutionPlan {
            program,
            inner: shell::build_program_execution(&mut self.session.state, self.runtime, program),
        }
    }

    /// Execute a previously prepared pipeline and update session status.
    pub fn execute_pipeline(&mut self, plan: &PreparedPipeline<'_>) -> RunOutcome {
        capture_outcome_for_state(&mut self.session.state, |state| {
            let status = shell::execute_pipeline_plan(state, self.runtime, &plan.inner);
            state.set_last_status(status);
            status
        })
    }

    /// Execute a previously prepared program and update session status.
    pub fn execute_plan(&mut self, plan: &PreparedProgram<'_>) -> RunOutcome {
        capture_outcome_for_state(&mut self.session.state, |state| {
            let status = shell::run_planned_program(
                state,
                self.runtime,
                plan.program,
                &plan.inner,
                None,
                None,
            );
            state.set_last_status(status);
            status
        })
    }
}