zshrs 0.11.1

The first compiled Unix shell — bytecode VM, 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! `zsh/hlgroup` module — port of `Src/Modules/hlgroup.c`.
//!
//! Exposes two read-only special parameters that bridge the
//! `$.zle.hlgroups` user-defined hash to the rendered ANSI escape
//! sequences zle uses internally:
//!   - `${.zle.esc[name]}` → full `\033[...m` escape stream
//!   - `${.zle.sgr[name]}` → bare `;`-joined SGR parameter list
//!
//! C source: 13 fns total — `convertattr`, `getgroup`, `scangroup`,
//! `getpmesc`, `scanpmesc`, `getpmsgr`, `scanpmsgr`, `setup_`,
//! `features_`, `enables_`, `boot_`, `cleanup_`, `finish_`.
//! Zero structs/enums in hlgroup.c (only `static const struct
//! gsu_scalar pmesc_gsu` and `static struct paramdef partab[]`
//! aggregates of pre-defined zsh-framework types).
//!
//! Order in this file mirrors C source order verbatim.

use std::fmt::Write;

/// Port of `GROUPVAR` from `Src/Modules/hlgroup.c:33`.
/// `#define GROUPVAR ".zle.hlgroups"`. Name of the user-defined
/// associative array that maps group names to highlight-attribute
/// strings. Read by `getgroup` (c:82) + `scangroup` (c:117).
pub const GROUPVAR: &str = ".zle.hlgroups";                                  // c:33

/// Port of `convertattr(char *attrstr, int sgr)` from `Src/Modules/hlgroup.c:40`.
///
/// C body (c:42-77):
/// ```c
/// zattr atr;
/// match_highlight(attrstr, &atr, NULL, NULL);    // c:46
/// s = zattrescape(atr, sgr ? NULL : &len);        // c:47
/// if (sgr) { ...strip ESC[ and m, join with ; ... }
/// r = dupstring_wlen(s, len);                     // c:75
/// free(s);
/// return r;
/// ```
///
/// **Strict-rule status: PARTIAL.** A faithful 1:1 port requires
/// the matching ports of `match_highlight()` (Src/prompt.c:2031)
/// and `zattrescape()` (Src/prompt.c:257) to land in
/// `src/ported/prompt.rs` first — the current `prompt::match_highlight`
/// and `prompt::zattrescape` use Rust-only `TextAttrs` shapes and
/// produce `%`-prefix prompt syntax instead of the ANSI escape
/// stream the C versions return. See `TODO.md` for the gap.
///
/// Until those land, the Rust port inlines a minimal colour/attr
/// parser that handles the common spec set (`bold`, `underline`,
/// `fg=NAME`, `fg=NN`, `fg=#RRGGBB`, etc.) directly. No Rust-only
/// helper fn is introduced — the parsing is entirely inline so the
/// fn-name set matches C exactly. The SGR post-processing block at
/// c:40-72 is mirrored when `sgr=true`.
///
/// C signature: `static char *convertattr(char *attrstr, int sgr)`.
pub fn convertattr(attrstr: &str, sgr: bool) -> String {                 // c:40
    // c:40 — `match_highlight(attrstr, &atr, NULL, NULL);`
    // c:47 — `s = zattrescape(atr, sgr ? NULL : &len);`
    // Inlined — see fn-doc note about the prompt.rs gap. The
    // attribute and colour name tables below mirror the data tables
    // `match_highlight` (Src/prompt.c:2031) and `match_colour`
    // (Src/prompt.c:1957) consult; emission format matches
    // `zattrescape` (Src/prompt.c:257) for the escape-mode output.
    let mut esc_stream = String::new();
    for part in attrstr.split(',') {
        let part = part.trim();
        // Attribute names → SGR integers (Src/prompt.c attribute table).
        let attr_n: Option<i32> = match part {
            "" | "none" | "reset" => Some(0),
            "bold"          => Some(1),
            "dim" | "faint" => Some(2),
            "italic"        => Some(3),
            "underline"     => Some(4),
            "blink"         => Some(5),
            "reverse" | "inverse" => Some(7),
            "hidden" | "invisible" => Some(8),
            "strikethrough" => Some(9),
            _ => None,
        };
        if let Some(n) = attr_n {
            let _ = write!(esc_stream, "\x1b[{}m", n);
            continue;
        }
        // fg= / bg= colour resolution (Src/prompt.c:1957 match_colour).
        let (is_fg, rest) = if let Some(r) = part.strip_prefix("fg=") {
            (true, r)
        } else if let Some(r) = part.strip_prefix("bg=") {
            (false, r)
        } else {
            continue;
        };
        let base = if is_fg { 30 } else { 40 };
        let bright_base = if is_fg { 90 } else { 100 };
        let prefix = if is_fg { 38 } else { 48 };
        let named: Option<i32> = match rest {
            "black"   => Some(base),
            "red"     => Some(base + 1),
            "green"   => Some(base + 2),
            "yellow"  => Some(base + 3),
            "blue"    => Some(base + 4),
            "magenta" => Some(base + 5),
            "cyan"    => Some(base + 6),
            "white"   => Some(base + 7),
            "default" => Some(base + 9),
            _ => None,
        };
        if let Some(n) = named {
            let _ = write!(esc_stream, "\x1b[{}m", n);
            continue;
        }
        if let Some(inner) = rest.strip_prefix("bright-")
                                .or_else(|| rest.strip_prefix("light-"))
        {
            let bn: Option<i32> = match inner {
                "black"   => Some(bright_base),
                "red"     => Some(bright_base + 1),
                "green"   => Some(bright_base + 2),
                "yellow"  => Some(bright_base + 3),
                "blue"    => Some(bright_base + 4),
                "magenta" => Some(bright_base + 5),
                "cyan"    => Some(bright_base + 6),
                "white"   => Some(bright_base + 7),
                _ => None,
            };
            if let Some(n) = bn {
                let _ = write!(esc_stream, "\x1b[{}m", n);
                continue;
            }
        }
        if let Ok(n) = rest.parse::<u8>() {
            let _ = write!(esc_stream, "\x1b[{};5;{}m", prefix, n);
            continue;
        }
        if let Some(hex) = rest.strip_prefix('#') {
            if hex.len() == 6 {
                let r = u8::from_str_radix(&hex[0..2], 16);
                let g = u8::from_str_radix(&hex[2..4], 16);
                let b = u8::from_str_radix(&hex[4..6], 16);
                if let (Ok(r), Ok(g), Ok(b)) = (r, g, b) {
                    let _ = write!(esc_stream, "\x1b[{};2;{};{};{}m",
                                   prefix, r, g, b);
                }
            }
        }
    }

    if sgr {
        // c:49-72 — strip `\033[` prefix and `m` suffix, join with `;`,
        // skip non-digit / non-`;` / non-`:` chars, replace `;`/`:` with `;`.
        // Always return at least "0" (c:67-70).
        let bytes = esc_stream.as_bytes();
        let mut out = String::new();
        let mut i = 0;
        while i + 1 < bytes.len() && bytes[i] == 0x1b && bytes[i + 1] == b'[' {
            i += 2;                                                      // c:53 c += 2
            // c:54-60 — accumulate digits, treat ; or : as separator,
            // break on anything else.
            while i < bytes.len() {
                let b = bytes[i];
                if b.is_ascii_digit() {                                  // c:54
                    out.push(b as char);                                 // c:55
                    i += 1;
                } else if b == b';' || b == b':' {                       // c:56
                    out.push(';');                                       // c:57
                    i += 1;
                } else {
                    break;                                               // c:59
                }
            }
            // c:62-65 — `if (*c != 'm') break;` else continue with `;`.
            if i >= bytes.len() || bytes[i] != b'm' {
                break;                                                   // c:62-63
            }
            out.push(';');                                               // c:64
            i += 1;                                                      // c:65 c++
        }
        // Trim trailing ';'.
        while out.ends_with(';') {
            out.pop();
        }
        // c:67-70 — `if (t <= s) { *s = '0'; t = s + 1; }`
        if out.is_empty() {
            out.push('0');
        }
        out
    } else {
        esc_stream                                                       // c:75 dupstring_wlen
    }
}

/// Port of `getgroup(const char *name, int sgr)` from `Src/Modules/hlgroup.c:82`. The shared
/// magic-assoc lookup behind both `${.zle.esc[name]}` and
/// `${.zle.sgr[name]}`. Reads `$.zle.hlgroups` (the `GROUPVAR`
/// `#define` at c:33), looks up `name`, runs `convertattr` on the
/// matched value's attribute string. Returns PM_UNSET (Rust `None`)
/// when the var isn't a hash, the group entry is missing, or the
/// entry has PM_UNSET set.
///
/// C signature: `static HashNode getgroup(const char *name, int sgr)`.
/// Rust port returns `Option<String>` — the synthesised Param's
/// rendered value (or None for PM_UNSET).
///
/// **Strict-rule status: PARTIAL.** Reading `$.zle.hlgroups` requires
/// the magic-assoc dispatch path through the executor's hash-param
/// table; that wiring depends on a faithful Param/HashTable port
/// which is a multi-file undertaking. Current body returns None
/// (mirrors C's c:99-103 PM_UNSET branch). See `TODO.md`.
pub fn getgroup(_name: &str, _sgr: bool) -> Option<String> {             // c:82
    // c:82-94 — pm setup with PM_SCALAR|PM_SPECIAL.
    // c:96-100 — `if (!(v = getvalue(...)) || ... PM_HASHED ... ||
    //                 (((Param) hn)->node.flags & PM_UNSET))`
    //   → c:102-103: `pm->u.str = ""; pm->node.flags |= PM_UNSET;`
    // c:104-106 — `else: pm->u.str = convertattr(((Param) hn)->u.str, sgr);`
    None                                                                 // c:103 PM_UNSET
}

/// shared magic-assoc scanner behind `${(k).zle.esc}` /
/// `${(kv).zle.esc}` (and the `.zle.sgr` variants). Walks the
/// `$.zle.hlgroups` hash and yields each entry as
/// `(name, convertattr(value, sgr))`.
///
/// C signature: `static void scangroup(ScanFunc func, int flags, int sgr)`.
/// Rust port returns the `(name, value)` pairs as a Vec since
/// zshrs's magic-assoc dispatcher consumes the entire list rather
/// than a per-entry callback.
///
/// **Strict-rule status: PARTIAL** for the same reason as `getgroup`
/// (depends on the `$.zle.hlgroups` hash being readable through the
/// param table). See `TODO.md`.
/// Port of `scangroup(ScanFunc func, int flags, int sgr)` from `Src/Modules/hlgroup.c:113`.
/// WARNING: param names don't match C — Rust=(_sgr) vs C=(func, flags, sgr)
pub fn scangroup(_sgr: bool) -> Vec<(String, String)> {                  // c:113
    // c:113-125 — `if (!(v = getvalue(...)) || ... PM_HASHED) return;`
    // c:141 — hlg = v->pm->gsu.h->getfn(v->pm)
    // c:141-130 — `pm` setup + PM_SCALAR + pmesc_gsu
    // c:141-137 — for each hashnode: `pm.u.str = convertattr(...,sgr);
    //                                   pm.node.nam = hn->nam;
    //                                   func(&pm.node, flags);`
    Vec::new()                                                           // c:141-125 empty exit
}

/// Port of `getpmesc(UNUSED(HashTable ht), const char *name)` from `Src/Modules/hlgroup.c:141`.
/// C body is `return getgroup(name, 0);` — escape-form variant.
/// WARNING: param names don't match C — Rust=(name) vs C=(ht, name)
pub fn getpmesc(name: &str) -> Option<String> {                          // c:141
    getgroup(name, false)                                                // c:148
}

/// Port of `scanpmesc(UNUSED(HashTable ht), ScanFunc func, int flags)` from `Src/Modules/hlgroup.c:148`.
/// C body is `scangroup(func, flags, 0);` — escape-form scanner.
/// WARNING: param names don't match C — Rust=() vs C=(ht, func, flags)
pub fn scanpmesc() -> Vec<(String, String)> {                            // c:148
    scangroup(false)                                                     // c:155
}

/// Port of `getpmsgr(UNUSED(HashTable ht), const char *name)` from `Src/Modules/hlgroup.c:155`.
/// C body is `return getgroup(name, 1);` — SGR-form variant.
/// WARNING: param names don't match C — Rust=(name) vs C=(ht, name)
pub fn getpmsgr(name: &str) -> Option<String> {                          // c:155
    getgroup(name, true)                                                 // c:162
}

/// Port of `scanpmsgr(UNUSED(HashTable ht), ScanFunc func, int flags)` from `Src/Modules/hlgroup.c:162`.
/// C body is `scangroup(func, flags, 1);` — SGR-form scanner.
/// WARNING: param names don't match C — Rust=() vs C=(ht, func, flags)
pub fn scanpmsgr() -> Vec<(String, String)> {                            // c:162
    scangroup(true)                                                      // c:162
}

// =====================================================================
// static struct features module_features                            c:170 (hlgroup)
// =====================================================================

use crate::ported::zsh_h::module;

// `partab` — port of `static struct paramdef partab[]` (hlgroup.c).


// `module_features` — port of `static struct features module_features`
// from hlgroup.c:170.



/// Port of `setup_(UNUSED(Module m))` from `Src/Modules/hlgroup.c:182`.
#[allow(unused_variables)]
pub fn setup_(m: *const module) -> i32 {                                // c:182
    0                                                                    // c:197
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from `Src/Modules/hlgroup.c:189`.
/// C body: `*features = featuresarray(m, &module_features); return 0;`
pub fn features_(m: *const module, features: &mut Vec<String>) -> i32 { // c:189
    *features = featuresarray(m, module_features());
    0                                                                    // c:204
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from `Src/Modules/hlgroup.c:197`.
/// C body: `return handlefeatures(m, &module_features, enables);`
pub fn enables_(m: *const module, enables: &mut Option<Vec<i32>>) -> i32 { // c:197
    handlefeatures(m, module_features(), enables) // c:211
}

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/hlgroup.c:204`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {                                 // c:204
    0                                                                    // c:218
}

/// Port of `cleanup_(UNUSED(Module m))` from `Src/Modules/hlgroup.c:211`.
/// C body: `return setfeatureenables(m, &module_features, NULL);`
pub fn cleanup_(m: *const module) -> i32 {                              // c:211
    setfeatureenables(m, module_features(), None) // c:218
}

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/hlgroup.c:218`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {                               // c:218
    0                                                                    // c:218
}

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

    /// `convertattr("bold", false)` emits `\e[1m` per Src/prompt.c
    /// attribute table.
    #[test]
    fn convertattr_bold_escape() {
        assert_eq!(convertattr("bold", false), "\x1b[1m");
    }

    /// `convertattr("bold,underline", false)` chains the two
    /// `\e[Nm` escapes.
    #[test]
    fn convertattr_chained_escape() {
        let s = convertattr("bold,underline", false);
        assert!(s.contains("\x1b[1m"));
        assert!(s.contains("\x1b[4m"));
    }

    /// `convertattr("fg=red", false)` emits `\e[31m`.
    #[test]
    fn convertattr_fg_red_escape() {
        let s = convertattr("fg=red", false);
        assert!(s.contains("\x1b[31m"));
    }

    /// SGR-mode `convertattr("bold", true)` returns `"1"`.
    #[test]
    fn convertattr_sgr_bold() {
        assert_eq!(convertattr("bold", true), "1");
    }

    /// SGR-mode chains: `convertattr("bold,underline", true)` →
    /// `"1;4"`.
    #[test]
    fn convertattr_sgr_chain() {
        let s = convertattr("bold,underline", true);
        assert!(s.contains('1'));
        assert!(s.contains('4'));
    }

    /// SGR-mode empty input returns `"0"` per c:67-70 fallback.
    #[test]
    fn convertattr_sgr_empty_returns_zero() {
        assert_eq!(convertattr("", true), "0");
    }

    /// 256-colour spec `fg=196` emits `\e[38;5;196m`.
    #[test]
    fn convertattr_256_color() {
        let s = convertattr("fg=196", false);
        assert!(s.contains("\x1b[38;5;196m"));
    }

    /// Truecolor spec `fg=#ff0000` emits `\e[38;2;255;0;0m`.
    #[test]
    fn convertattr_truecolor() {
        let s = convertattr("fg=#ff0000", false);
        assert!(s.contains("\x1b[38;2;255;0;0m"));
    }

    /// SGR-mode 256-colour: `fg=196` → `38;5;196`.
    #[test]
    fn convertattr_sgr_256_color() {
        let s = convertattr("fg=196", true);
        assert!(s.contains("38;5;196"));
    }

    /// SGR-mode truecolor: `fg=#00ff00` → `38;2;0;255;0`.
    #[test]
    fn convertattr_sgr_truecolor() {
        let s = convertattr("fg=#00ff00", true);
        assert!(s.contains("38;2;0;255;0"));
    }

    /// `getgroup` returns None until the magic-assoc dispatch is
    /// wired (c:99-103 PM_UNSET branch).
    #[test]
    fn getgroup_returns_none_until_paramtable_wired() {
        assert_eq!(getgroup("any", false), None);
        assert_eq!(getgroup("any", true), None);
    }

    /// `scangroup` returns empty until paramtable wiring lands
    /// (c:124-125 early exit).
    #[test]
    fn scangroup_returns_empty_until_paramtable_wired() {
        assert!(scangroup(false).is_empty());
        assert!(scangroup(true).is_empty());
    }
}

use crate::ported::zsh_h::features as features_t;
use std::sync::{Mutex, OnceLock};

static MODULE_FEATURES: OnceLock<Mutex<features_t>> = OnceLock::new();

// WARNING: NOT IN HLGROUP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn module_features() -> &'static Mutex<features_t> {
    MODULE_FEATURES.get_or_init(|| Mutex::new(features_t {
        bn_list: None,
        bn_size: 0,
        cd_list: None,
        cd_size: 0,
        mf_list: None,
        mf_size: 0,
        pd_list: None,
        pd_size: 2,
        n_abstract: 0,
    }))
}

// Local stubs for the per-module entry points. C uses generic
// `featuresarray`/`handlefeatures`/`setfeatureenables` (module.c:
// 3275/3370/3445) but those take `Builtin` + `Features` pointer
// fields the Rust port doesn't carry. The hardcoded descriptor
// list mirrors the C bintab/conddefs/mathfuncs/paramdefs.
// WARNING: NOT IN HLGROUP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn featuresarray(_m: *const module, _f: &Mutex<features_t>) -> Vec<String> {
    vec!["p:.zle.esc".to_string(), "p:.zle.sgr".to_string()]
}

// WARNING: NOT IN HLGROUP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn handlefeatures(
    _m: *const module,
    _f: &Mutex<features_t>,
    enables: &mut Option<Vec<i32>>,
) -> i32 {
    if enables.is_none() {
        *enables = Some(vec![1; 2]);
    }
    0
}

// WARNING: NOT IN HLGROUP.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn setfeatureenables(
    _m: *const module,
    _f: &Mutex<features_t>,
    _e: Option<&[i32]>,
) -> i32 {
    0
}