zshrs 0.10.9

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, SQLite 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
//! Loop execution for zshrs
//!
//! Port from zsh/Src/loop.c (802 lines)
//!
//! In C, loop.c contains execfor, execwhile, execif, execcase, execselect,
//! execrepeat, and exectry as separate functions operating on bytecode.
//! In Rust, all of these are implemented as match arms in
//! ShellExecutor::execute_compound() in exec.rs, operating on the typed AST
//! (CompoundCommand::For, While, If, Case, Select, Repeat, Try).
//!
//! This module provides the loop state management and helper functions
//! that support the executor's loop implementation.

use std::sync::atomic::{AtomicI32, Ordering};

/// Number of nested loops.
/// Port of the global `loops` counter from Src/loop.c — every
/// `execfor`/`execwhile`/`execrepeat`/`execselect` entry bumps it
/// and decrements on exit.
static LOOP_DEPTH: AtomicI32 = AtomicI32::new(0);

/// Continue flag / level.
/// Port of the global `contflag` from Src/loop.c — set by the
/// `continue` builtin (Src/builtin.c:bin_break) and consumed by
/// the loop body's exit check.
static CONT_FLAG: AtomicI32 = AtomicI32::new(0);

/// Break level.
/// Port of the global `breaks` counter from Src/loop.c — set by
/// the `break` builtin (Src/builtin.c:bin_break) and tested by
/// each enclosing loop on exit.
static BREAK_LEVEL: AtomicI32 = AtomicI32::new(0);

/// Loop state for the executor.
/// Port of the (`loops`, `breaks`, `contflag`) globals Src/loop.c
/// uses to coordinate `break`/`continue` with the loop bodies.
/// Bundling them into a struct gives us a single owner per executor
/// thread instead of file-static globals.
#[derive(Debug, Clone, Default)]
pub struct LoopState {
    /// Current nesting depth
    pub depth: i32,
    /// Break requested (and how many levels)
    pub breaks: i32,
    /// Continue requested (and how many levels)
    pub contflag: i32,
}

impl LoopState {
    pub fn new() -> Self {
        Self::default()
    }

    /// Enter a loop.
    /// Port of the `loops++` increment Src/loop.c performs at the
    /// top of every `execfor`/`execwhile`/etc. body before running
    /// any iterations.
    pub fn enter(&mut self) {
        self.depth += 1;
        LOOP_DEPTH.store(self.depth, Ordering::Relaxed);
    }

    /// Exit a loop.
    /// Port of the `loops--` decrement Src/loop.c performs at the
    /// end of each loop body. Also decrements pending `break` /
    /// `continue` levels so the next-outer loop sees them satisfied.
    pub fn exit(&mut self) {
        self.depth -= 1;
        if self.depth < 0 {
            self.depth = 0;
        }
        LOOP_DEPTH.store(self.depth, Ordering::Relaxed);

        // Decrement break/continue levels as we leave
        if self.breaks > 0 {
            self.breaks -= 1;
        }
        if self.contflag > 0 {
            self.contflag -= 1;
        }
        BREAK_LEVEL.store(self.breaks, Ordering::Relaxed);
        CONT_FLAG.store(self.contflag, Ordering::Relaxed);
    }

    /// Request break.
    /// Port of the `breaks = nlevels` write inside `bin_break()`
    /// (Src/builtin.c) — the C source clamps the level to the
    /// active loop depth.
    pub fn do_break(&mut self, levels: i32) {
        self.breaks = levels.min(self.depth);
        BREAK_LEVEL.store(self.breaks, Ordering::Relaxed);
    }

    /// Request continue.
    /// Port of the `contflag = nlevels` write inside `bin_break()`
    /// (Src/builtin.c) — same clamp to active loop depth.
    pub fn do_continue(&mut self, levels: i32) {
        self.contflag = levels.min(self.depth);
        CONT_FLAG.store(self.contflag, Ordering::Relaxed);
    }

    /// Check if break is active.
    /// Equivalent to the `breaks > 0` test inside `execfor`/etc.
    /// (Src/loop.c) that triggers loop-body teardown.
    pub fn should_break(&self) -> bool {
        self.breaks > 0
    }

    /// Check if continue is active.
    /// Equivalent to the `contflag > 0` test Src/loop.c uses to
    /// skip the rest of the iteration body.
    pub fn should_continue(&self) -> bool {
        self.contflag > 0
    }

    /// Check if we're inside any loop.
    /// Equivalent to the `loops > 0` test `bin_break()` uses to
    /// reject `break`/`continue` outside of a loop.
    pub fn in_loop(&self) -> bool {
        self.depth > 0
    }

    /// Reset break/continue (after handling).
    /// Port of the `contflag = 0` reset Src/loop.c performs at the
    /// top of each loop iteration — the body has consumed the
    /// continue request and is about to start fresh.
    pub fn reset_flow(&mut self) {
        self.contflag = 0;
        CONT_FLAG.store(0, Ordering::Relaxed);
    }

    /// Get current nesting depth.
    /// Returns the equivalent of the C source's `loops` value.
    pub fn current_depth(&self) -> i32 {
        self.depth
    }
}

/// Get global loop depth.
/// Returns the live `loops` value (Src/loop.c) for callers that
/// don't carry a `LoopState` reference.
pub fn loop_depth() -> i32 {
    LOOP_DEPTH.load(Ordering::Relaxed)
}

/// Get global break level.
/// Returns the live `breaks` value (Src/loop.c).
pub fn break_level() -> i32 {
    BREAK_LEVEL.load(Ordering::Relaxed)
}

/// Get global continue flag.
/// Returns the live `contflag` value (Src/loop.c).
pub fn cont_flag() -> i32 {
    CONT_FLAG.load(Ordering::Relaxed)
}

/// Select-menu display.
/// Port of `selectlist()` from Src/loop.c:347 — formats the
/// numbered menu the C source uses for `select var in words`. Picks
/// columns automatically when `columns == 0`, mirroring the C
/// source's terminal-width auto-detection.
pub fn selectlist(items: &[String], prompt: &str, columns: usize) -> String {
    let mut output = String::new();
    let max_width = items.iter().map(|s| s.len()).max().unwrap_or(0);
    let item_width = max_width + 4; // number + ") " + padding
    let cols = if columns > 0 {
        columns
    } else {
        // Auto-detect columns based on terminal width
        let term_width = crate::utils::get_term_width();
        (term_width / item_width.max(1)).max(1)
    };

    for (i, item) in items.iter().enumerate() {
        let num = i + 1;
        let entry = format!("{:>2}) {:<width$}", num, item, width = max_width);
        output.push_str(&entry);

        if (i + 1) % cols == 0 || i + 1 == items.len() {
            output.push('\n');
        } else {
            output.push_str("  ");
        }
    }

    if !prompt.is_empty() {
        output.push_str(prompt);
    }

    output
}

/// Parse a `select` reply.
/// Port of the input-parsing block of `execselect()` from
/// Src/loop.c:217 — accepts a 1-based numeric index that maps onto
/// the original word list. Empty / out-of-range / non-numeric
/// replies return `None`, matching the C source's "redisplay menu"
/// fallback.
pub fn select_parse_reply(reply: &str, items: &[String]) -> Option<String> {
    let reply = reply.trim();
    if reply.is_empty() {
        return None;
    }

    // Try as number
    if let Ok(n) = reply.parse::<usize>() {
        if n >= 1 && n <= items.len() {
            return Some(items[n - 1].clone());
        }
    }

    None
}

/// `for` loop variable iteration helper.
/// Port of the word-list walk inside `execfor()` (Src/loop.c:50)
/// plus the integer-range walk inside `execfor`'s C-style branch.
/// The Rust struct exposes both shapes through a single `Iterator`
/// impl.
pub struct ForIterator {
    items: Vec<String>,
    pos: usize,
}

impl ForIterator {
    pub fn new(items: Vec<String>) -> Self {
        ForIterator { items, pos: 0 }
    }

    pub fn from_range(start: i64, end: i64, step: i64) -> Self {
        let mut items = Vec::new();
        let step = if step == 0 { 1 } else { step };
        if step > 0 {
            let mut i = start;
            while i <= end {
                items.push(i.to_string());
                i += step;
            }
        } else {
            let mut i = start;
            while i >= end {
                items.push(i.to_string());
                i += step;
            }
        }
        ForIterator { items, pos: 0 }
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

impl Iterator for ForIterator {
    type Item = String;

    fn next(&mut self) -> Option<String> {
        if self.pos < self.items.len() {
            let item = self.items[self.pos].clone();
            self.pos += 1;
            Some(item)
        } else {
            None
        }
    }
}

/// C-style `for` loop state (`(( init; cond; advance ))`).
/// Port of the `cs` (C-style) branch flags inside `execfor()`
/// (Src/loop.c:50). The C source threads init/cond/advance through
/// the bytecode walker; we keep a tiny init-done flag for the
/// equivalent first-iteration guard.
pub struct CForState {
    pub init_done: bool,
}

impl CForState {
    pub fn new() -> Self {
        CForState { init_done: false }
    }
}

impl Default for CForState {
    fn default() -> Self {
        Self::new()
    }
}

/// Try/always block state.
/// Port of the `try_errflag` / `try_retval` machinery
/// `exectry()` from Src/loop.c:735 saves and restores around the
/// `always { ... }` block. The C source uses globals here; we
/// scope them per executor instance.
#[derive(Debug, Clone, Default)]
pub struct TryState {
    pub in_try: bool,
    pub try_errflag: i32,
    pub try_retval: i32,
}

impl TryState {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn enter_try(&mut self) {
        self.in_try = true;
        self.try_errflag = 0;
        self.try_retval = 0;
    }

    pub fn exit_try(&mut self) {
        self.in_try = false;
    }

    pub fn set_error(&mut self, errflag: i32, retval: i32) {
        self.try_errflag = errflag;
        self.try_retval = retval;
    }
}

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

    #[test]
    fn test_loop_state() {
        let mut state = LoopState::new();
        assert!(!state.in_loop());

        state.enter();
        assert!(state.in_loop());
        assert_eq!(state.current_depth(), 1);

        state.enter();
        assert_eq!(state.current_depth(), 2);

        state.exit();
        assert_eq!(state.current_depth(), 1);
        assert!(state.in_loop());

        state.exit();
        assert!(!state.in_loop());
    }

    #[test]
    fn test_break_continue() {
        let mut state = LoopState::new();
        state.enter();
        state.enter();

        state.do_break(1);
        assert!(state.should_break());

        state.exit();
        assert!(!state.should_break());
    }

    #[test]
    fn test_for_iterator() {
        let iter = ForIterator::new(vec!["a".into(), "b".into(), "c".into()]);
        let items: Vec<String> = iter.collect();
        assert_eq!(items, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_for_range() {
        let iter = ForIterator::from_range(1, 5, 1);
        let items: Vec<String> = iter.collect();
        assert_eq!(items, vec!["1", "2", "3", "4", "5"]);
    }

    #[test]
    fn test_select_parse() {
        let items = vec!["apple".into(), "banana".into(), "cherry".into()];
        assert_eq!(select_parse_reply("1", &items), Some("apple".to_string()));
        assert_eq!(select_parse_reply("3", &items), Some("cherry".to_string()));
        assert_eq!(select_parse_reply("0", &items), None);
        assert_eq!(select_parse_reply("4", &items), None);
        assert_eq!(select_parse_reply("", &items), None);
    }

    #[test]
    fn test_selectlist() {
        let items = vec!["one".into(), "two".into(), "three".into()];
        let output = selectlist(&items, "? ", 0);
        assert!(output.contains("1)"));
        assert!(output.contains("one"));
        assert!(output.contains("three"));
    }

    #[test]
    fn test_try_state() {
        let mut state = TryState::new();
        assert!(!state.in_try);

        state.enter_try();
        assert!(state.in_try);

        state.set_error(1, 42);
        assert_eq!(state.try_errflag, 1);
        assert_eq!(state.try_retval, 42);

        state.exit_try();
        assert!(!state.in_try);
    }
}