zshrs 0.11.18

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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! `zsh/terminfo` module — direct port of `Src/Modules/terminfo.c`.
//!
//! This depends on the termcap stuff in init.c                              // c:72
//!
//! Exposes the live terminfo database to scripts via the
//! `${terminfo[capname]}` associative array. The C source binds
//! ncurses' `setupterm`/`tigetstr`/`tigetnum`/`tigetflag`; this file
//! does the same through Rust FFI against the system curses library
//! that ships with macOS / Linux SDKs.
//!
//! Lookup precedence matches `getterminfo()` in the C source:
//!   1. String capability  (`tigetstr`)
//!   2. Numeric capability (`tigetnum`)
//!   3. Boolean capability (`tigetflag`)  →  rendered as `"yes"`/`"no"`
//!
//! Unknown capabilities return `None` so callers can emit `""`
//! matching zsh's `PM_UNSET` fallback (terminfo.c:165-168).

use crate::ported::params::{TERMFLAGS };
use std::sync::atomic::Ordering;
use crate::ported::zsh_h::module;
use std::sync::{Mutex, OnceLock};
use crate::options::optlookup;
use crate::zsh_h::{isset, TERM_UNKNOWN};

// FFI bindings to the system ncurses terminfo interface. Direct
// port of the call sites in `zsh/Src/Modules/terminfo.c`. macOS
// and Linux SDKs ship libcurses by default — no extra build dep.
#[link(name = "ncurses")]
extern "C" {
    fn setupterm(
        term: *const libc::c_char,
        filedes: libc::c_int,
        errret: *mut libc::c_int,
    ) -> libc::c_int;
    fn tigetstr(capname: *const libc::c_char) -> *const libc::c_char;
    fn tigetnum(capname: *const libc::c_char) -> libc::c_int;
    fn tigetflag(capname: *const libc::c_char) -> libc::c_int;
    fn putp(s: *const libc::c_char) -> libc::c_int;
    fn tparm(
        s: *const libc::c_char,
        p1: libc::c_long,
        p2: libc::c_long,
        p3: libc::c_long,
        p4: libc::c_long,
        p5: libc::c_long,
        p6: libc::c_long,
        p7: libc::c_long,
        p8: libc::c_long,
        p9: libc::c_long,
    ) -> *const libc::c_char;
}

/// Direct port of `bin_echoti(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))` from `Src/Modules/terminfo.c:64`.
/// C body (c:67-127): probe `tigetnum` → `tigetflag` → `tigetstr`
/// in turn; numeric/boolean caps print and return; string caps go
/// through `tparm` (with up to 9 long args) then `putp`.
/// WARNING: param names don't match C — Rust=(name, argv, _func) vs C=(name, argv, ops, func)
pub fn bin_echoti(
    name: &str,
    argv: &[String], // c:64
    _ops: &crate::ported::zsh_h::options,
    _func: i32,
) -> i32 {
    const TERM_BAD: i32 = 1 << 1;

    if argv.is_empty() {
        crate::ported::utils::zwarnnam(name, "missing capability name");
        return 1;
    }
    let s = &argv[0]; // c:73 s = *argv++
    let argv_rest = &argv[1..];

    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_BAD) != 0 {
        // c:75
        return 1; // c:76
    }
    let interactive = isset(optlookup("interactive")); // c:77
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_UNKNOWN) != 0 && interactive {
        return 1; // c:78
    }

    let cs = match std::ffi::CString::new(s.as_str()) {
        Ok(c) => c,
        Err(_) => return 1,
    };

    // c:Src/utils.c:390 — boot_terminfo → zsetupterm() must run real
    // ncurses setupterm so tigetnum/tigetflag/tigetstr have a cur_term.
    // The Rust zsetupterm in utils.rs is a counter-only stub (no FFI),
    // so without this guard tigetnum("cols") returns -2 (uninitialized)
    // and echoti drops into "no such capability". Mirror the cur_term
    // init pattern from terminfosetfn/terminfogetfn below.
    static ECHOTI_TERM_READY: OnceLock<bool> = OnceLock::new();
    let term_ok = *ECHOTI_TERM_READY.get_or_init(|| {
        let mut errret: libc::c_int = 0;
        unsafe { setupterm(std::ptr::null(), 1, &mut errret) == 0 }
    });
    if !term_ok {
        crate::ported::utils::zwarnnam(
            name,
            &format!("no such terminfo capability: {}", s),
        );
        return 1;
    }

    // c:81 — `if (((num = tigetnum(s)) != -1) && (num != -2)) { ... }`.
    let num = unsafe { tigetnum(cs.as_ptr()) }; // c:81
    if num != -1 && num != -2 {
        // c:81
        println!("{}", num); // c:82
        return 0; // c:83
    }

    // c:86 — `switch (tigetflag(s)) { -1 break; 0 puts("no"); default puts("yes"); }`.
    match unsafe { tigetflag(cs.as_ptr()) } {
        // c:86
        -1 => {} // c:88
        0 => {
            println!("no");
            return 0;
        } // c:90
        _ => {
            println!("yes");
            return 0;
        } // c:93
    }

    // get a string-type capability                                          // c:94
    // c:97 — `t = (char *)tigetstr(s);` — string capability.
    let t = unsafe { tigetstr(cs.as_ptr()) }; // c:97
    let t_addr = t as isize;
    if t.is_null() || t_addr == -1 || unsafe { *t } == 0 {
        // c:98
        // capability doesn't exist, or (if boolean) is off                  // c:97
        crate::ported::utils::zwarnnam(
            name, // c:100
            &format!("no such terminfo capability: {}", s),
        );
        return 1; // c:101
    }

    // c:104 — `if (arrlen_gt(argv, 9)) { zwarnnam(name, "too many arguments"); return 1; }`.
    if argv_rest.len() > 9 {
        // c:104
        crate::ported::utils::zwarnnam(name, "too many arguments"); // c:105
        return 1; // c:106
    }

    // c:110 — `for (u = strcap; *u && !strarg; u++) strarg = !strcmp(s, *u);`
    // String-arg capabilities: pfkey/pfloc/pfx/pln/pfxl take a string
    // for argv[1+]; everything else takes integers.
    let strcap = ["pfkey", "pfloc", "pfx", "pln", "pfxl"];
    let strarg = strcap.iter().any(|c| s.as_str() == *c);

    // c:113 — `for (arg=0; argv[arg]; arg++) pars[arg] = ...`
    let mut pars: [libc::c_long; 9] = [0; 9]; // c:69
    let mut keep_alive: Vec<std::ffi::CString> = Vec::new(); // hold strarg pointers
    for (i, a) in argv_rest.iter().enumerate().take(9) {
        if strarg && i > 0 {
            // c:115
            let cs = std::ffi::CString::new(a.as_str()).unwrap_or_default();
            pars[i] = cs.as_ptr() as libc::c_long; // c:116
            keep_alive.push(cs);
        } else {
            pars[i] = a.parse::<libc::c_long>().unwrap_or(0); // c:118 atoi
        }
    }

    // c:122 — `if (!arg) putp(t); else putp(tparm(t, pars[0..8]));`
    if argv_rest.is_empty() {
        // c:122
        unsafe {
            putp(t);
        } // c:123
    } else {
        let formatted = unsafe {
            // c:125
            tparm(
                t, pars[0], pars[1], pars[2], pars[3], pars[4], pars[5], pars[6], pars[7], pars[8],
            )
        };
        if !formatted.is_null() {
            unsafe {
                putp(formatted);
            }
        }
    }
    drop(keep_alive);
    0 // c:128
}

/// Initialize the terminfo database for the current `$TERM`. Must
/// Port of `getterminfo(UNUSED(HashTable ht), const char *name)` from `Src/Modules/terminfo.c:135`.
///
/// Also drives `bin_echoti` at line 64. Tries `tigetstr` → `tigetnum`
/// → `tigetflag` in that order — string first, then numeric, then
/// boolean. Returns `None` for unknown names so the caller can map
/// to `""`. The terminfo database is initialised lazily via the
/// `setupterm()` call zsh's setup_/boot_ hook performs at terminfo.c:
/// init_term path; collapsed into a OnceLock here since zshrs has no
/// per-module init function shape.
/// Port of `static HashNode getterminfo(UNUSED(HashTable ht), const char *name)`
/// from `Src/Modules/terminfo.c:135-177`. Returns a synthesised Param
/// with PM_INTEGER (numeric cap), PM_SCALAR yes/no (boolean cap),
/// PM_SCALAR escape-string (string cap), or PM_UNSET ("" + flag).
pub fn getterminfo(_ht: *mut crate::ported::zsh_h::HashTable, name: &str) -> Option<crate::ported::zsh_h::Param> {
    // c:135
    use crate::ported::zsh_h::{hashnode, param, PM_INTEGER, PM_READONLY, PM_SCALAR, PM_UNSET};
    const TERM_BAD: i32 = 1 << 1;

    // c:142 — `if (termflags & TERM_BAD) return NULL;`
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_BAD) != 0 {
        return None;
    }
    // c:144 — `if ((termflags & TERM_UNKNOWN) && (isset(INTERACTIVE) || !init_term())) return NULL;`
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_UNKNOWN) != 0 {
        if isset(optlookup("interactive")) {
            return None;
        }
    }

    static INITIALIZED: OnceLock<bool> = OnceLock::new();
    let ok = *INITIALIZED.get_or_init(|| {
        let mut errret: libc::c_int = 0;
        unsafe { setupterm(std::ptr::null(), 1, &mut errret) == 0 }
    });
    if !ok {
        return None;
    }

    // Helper: build a Param shell with the given flags + u_str/u_val.
    let mk_str = |s: String, extra_flags: i32| -> crate::ported::zsh_h::Param {
        Box::new(param {
            node: hashnode {
                next: None,
                nam: name.to_string(),
                flags: PM_READONLY as i32 | extra_flags,
            },
            u_data: 0,
            u_arr: None,
            u_str: Some(s),
            u_val: 0,
            u_dval: 0.0,
            u_hash: None,
            gsu_s: None,
            gsu_i: None,
            gsu_f: None,
            gsu_a: None,
            gsu_h: None,
            base: 0,
            width: 0,
            env: None,
            ename: None,
            old: None,
            level: 0,
        })
    };

    // c:147 — `nameu = dupstring(name); unmetafy(nameu, &len);`
    let mut buf = name.as_bytes().to_vec();
    crate::ported::utils::unmetafy(&mut buf);
    let nameu = match std::str::from_utf8(&buf) {
        Ok(s) => s.to_string(),
        Err(_) => return None,
    };
    let cname = std::ffi::CString::new(nameu).ok()?;

    unsafe {
        // c:155 — PM_INTEGER for tigetnum hit.
        let n = tigetnum(cname.as_ptr());
        if n != -1 && n != -2 {
            // c:156-158 — `pm->u.val = num; PM_INTEGER;`
            // Also stamp u_str with the decimal form so callers that
            // only consume u_str (like vm_helper::partab_get) see the
            // value. `$terminfo[colors]` reads as 256, not empty.
            let mut pm = mk_str((n as i64).to_string(), PM_INTEGER as i32);
            pm.u_val = n as i64;
            return Some(pm);
        }
        // c:159-162 — PM_SCALAR yes/no for tigetflag hit.
        let b = tigetflag(cname.as_ptr());
        if b != -1 {
            let s = if b != 0 { "yes" } else { "no" }.to_string();
            return Some(mk_str(s, PM_SCALAR as i32));
        }
        // c:163-167 — PM_SCALAR escape string for tigetstr hit.
        let tistr = tigetstr(cname.as_ptr());
        let s_addr = tistr as isize;
        if !tistr.is_null() && s_addr != -1 {
            let raw = std::ffi::CStr::from_ptr(tistr)
                .to_string_lossy()
                .into_owned();
            return Some(mk_str(crate::ported::utils::metafy(&raw), PM_SCALAR as i32));
        }
    }
    // c:168-173 — `pm->u.str = ""; pm->node.flags |= PM_UNSET;`
    Some(mk_str(String::new(), PM_SCALAR as i32 | PM_UNSET as i32))
}

/// Port of `static void scanterminfo(UNUSED(HashTable ht), ScanFunc func, int flags)`
/// from `Src/Modules/terminfo.c:177-289`. Walks the bool/num/string
/// capability tables and invokes the callback per resolved cap.
pub fn scanterminfo(
    _ht: *mut crate::ported::zsh_h::HashTable,
    func: Option<crate::ported::zsh_h::ScanFunc>,
    flags: i32,
) {
    // c:177
    use crate::ported::zsh_h::{hashnode, param, PM_SCALAR};
    let f = match func {
        Some(f) => f,
        None => return,
    };
    let emit_cap = |cap_name: &str, val: &str| {
        let pm = param {
            node: hashnode {
                next: None,
                nam: cap_name.to_string(),
                flags: PM_SCALAR as i32,
            },
            u_data: 0,
            u_arr: None,
            u_str: Some(val.to_string()),
            u_val: 0,
            u_dval: 0.0,
            u_hash: None,
            gsu_s: None,
            gsu_i: None,
            gsu_f: None,
            gsu_a: None,
            gsu_h: None,
            base: 0,
            width: 0,
            env: None,
            ename: None,
            old: None,
            level: 0,
        };
        let node_box = Box::new(pm.node.clone());
        f(&node_box, flags);
    };

    // c:152-153 — `if (termflags & TERM_BAD) return;`. The full
    // termflag check at getterminfo's entry mirrors here too.
    const TERM_BAD: i32 = 1 << 1;
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_BAD) != 0 {
        return;
    }
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_UNKNOWN) != 0 {
        let interactive =
            isset(optlookup("interactive"));
        if interactive {
            return;
        }
    }
    static INITIALIZED: OnceLock<bool> = OnceLock::new();
    let ok = *INITIALIZED.get_or_init(|| {
        let mut errret: libc::c_int = 0;
        unsafe { setupterm(std::ptr::null(), 1, &mut errret) == 0 }
    });
    if !ok {
        return;
    }

    // c:184-194 — boolnames fallback when libtermcap doesn't export them.
    let boolnames = [
        "bw", "am", "bce", "ccc", "xhp", "xhpa", "cpix", "crxm", "xt", "xenl", "eo", "gn", "hc",
        "chts", "km", "daisy", "hs", "hls", "in", "lpix", "da", "db", "mir", "msgr", "nxon", "xsb",
        "npc", "ndscr", "nrrmc", "os", "mc5i", "xvpa", "sam", "eslok", "hz", "ul", "xon",
    ];
    // c:198-204 — numnames.
    let numnames = [
        "cols", "it", "lh", "lw", "lines", "lm", "xmc", "ma", "colors", "pairs", "wnum", "ncv",
        "nlab", "pb", "vt", "wsl", "bitwin", "bitype", "bufsz", "btns", "spinh", "spinv", "maddr",
        "mjump", "mcs", "mls", "npins", "orc", "orhi", "orl", "orvi", "cps", "widcs",
    ];
    // c:208-247 — strnames: full ~290-entry list matching the C source.
    let strnames: &[&str] = &[
        "acsc", "cbt", "bel", "cr", "cpi", "lpi", "chr", "cvr", "csr", "rmp", "tbc", "mgc",
        "clear", "el1", "el", "ed", "hpa", "cmdch", "cwin", "cup", "cud1", "home", "civis", "cub1",
        "mrcup", "cnorm", "cuf1", "ll", "cuu1", "cvvis", "defc", "dch1", "dl1", "dial", "dsl",
        "dclk", "hd", "enacs", "smacs", "smam", "blink", "bold", "smcup", "smdc", "dim", "swidm",
        "sdrfq", "smir", "sitm", "slm", "smicm", "snlq", "snrmq", "prot", "rev", "invis", "sshm",
        "smso", "ssubm", "ssupm", "smul", "sum", "smxon", "ech", "rmacs", "rmam", "sgr0", "rmcup",
        "rmdc", "rwidm", "rmir", "ritm", "rlm", "rmicm", "rshm", "rmso", "rsubm", "rsupm", "rmul",
        "rum", "rmxon", "pause", "hook", "flash", "ff", "fsl", "wingo", "hup", "is1", "is2", "is3",
        "if", "iprog", "initc", "initp", "ich1", "il1", "ip", "ka1", "ka3", "kb2", "kbs", "kbeg",
        "kcbt", "kc1", "kc3", "kcan", "ktbc", "kclr", "kclo", "kcmd", "kcpy", "kcrt", "kctab",
        "kdch1", "kdl1", "kcud1", "krmir", "kend", "kent", "kel", "ked", "kext", "kf0", "kf1",
        "kf10", "kf11", "kf12", "kf13", "kf14", "kf15", "kf16", "kf17", "kf18", "kf19", "kf2",
        "kf20", "kf21", "kf22", "kf23", "kf24", "kf25", "kf26", "kf27", "kf28", "kf29", "kf3",
        "kf30", "kf31", "kf32", "kf33", "kf34", "kf35", "kf36", "kf37", "kf38", "kf39", "kf4",
        "kf40", "kf41", "kf42", "kf43", "kf44", "kf45", "kf46", "kf47", "kf48", "kf49", "kf5",
        "kf50", "kf51", "kf52", "kf53", "kf54", "kf55", "kf56", "kf57", "kf58", "kf59", "kf6",
        "kf60", "kf61", "kf62", "kf63", "kf7", "kf8", "kf9", "kfnd", "khlp", "khome", "kich1",
        "kil1", "kcub1", "kll", "kmrk", "kmsg", "kmov", "knxt", "knp", "kopn", "kopt", "kpp",
        "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "kcuf1", "ksav", "kBEG",
        "kCAN", "kCMD", "kCPY", "kCRT", "kDC", "kDL", "kslt", "kEND", "kEOL", "kEXT", "kind",
        "kFND", "kHLP", "kHOM", "kIC", "kLFT", "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT",
        "kri", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "khts", "kUND", "kspd", "kund",
        "kcuu1", "rmkx", "smkx", "lf0", "lf1", "lf10", "lf2", "lf3", "lf4", "lf5", "lf6", "lf7",
        "lf8", "lf9", "fln", "rmln", "smln", "rmm", "smm", "mhpa", "mcud1", "mcub1", "mcuf1",
        "mvpa", "mcuu1", "nel", "porder", "oc", "op", "pad", "dch", "dl", "cud", "mcud", "ich",
        "indn", "il", "cub", "mcub", "cuf", "mcuf", "rin", "cuu", "mcuu", "pfkey", "pfloc", "pfx",
        "pln", "mc0", "mc5p", "mc4", "mc5", "pulse", "qdial", "rmclk", "rep", "rfi", "rs1", "rs2",
        "rs3", "rf", "rc", "vpa", "sc", "ind", "ri", "scs", "sgr", "setb", "smgb", "smgbp", "sclk",
        "scp", "setf", "smgl", "smglp", "smgr", "smgrp", "hts", "smgt", "smgtp", "wind", "sbim",
        "scsd", "rbim", "rcsd", "subcs", "supcs", "ht", "docr", "tsl", "tone", "uc", "hu", "u0",
        "u1", "u2", "u3", "u4", "u5", "u6", "u7", "u8", "u9", "wait", "xoffc", "xonc", "zerom",
        "scesa", "bicr", "binel", "birep", "csnm", "csin", "colornm", "defbi", "devt", "dispc",
        "endbi", "smpch", "smsc", "rmpch", "rmsc", "getm", "kmous", "minfo", "pctrm", "pfxl",
        "reqmp", "scesc", "s0ds", "s1ds", "s2ds", "s3ds", "setab", "setaf", "setcolor", "smglr",
        "slines", "smgtb", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm", "evhlm", "sgr1",
        "slength",
    ];

    // c:257-263 — boolean caps: tigetflag → "yes" / "no", emit when num != -1.
    for cap in &boolnames {
        // c:257
        let cn = match std::ffi::CString::new(*cap) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let n = unsafe { tigetflag(cn.as_ptr()) }; // c:258
        if n != -1 {
            // c:258
            let v = if n != 0 { "yes" } else { "no" }; // c:259
            emit_cap(cap, v); // c:261 func(&pm.node, flags)
        }
    }

    // c:268-275 — numeric caps.
    for cap in &numnames {
        // c:268
        let cn = match std::ffi::CString::new(*cap) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let n = unsafe { tigetnum(cn.as_ptr()) }; // c:269
        if n != -1 && n != -2 {
            // c:269
            emit_cap(cap, &n.to_string()); // c:270-272 func(&pm.node, flags)
        }
    }

    // c:280-287 — string caps: tigetstr → metafy, emit when non-NULL/-1.
    for cap in strnames {
        // c:280
        let cn = match std::ffi::CString::new(*cap) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let raw = unsafe { tigetstr(cn.as_ptr()) }; // c:281
        let s_addr = raw as isize;
        if !raw.is_null() && s_addr != -1 {
            // c:282
            let bytes = unsafe { std::ffi::CStr::from_ptr(raw) }
                .to_string_lossy()
                .into_owned();
            // c:283 — `pm->u.str = metafy(tistr, -1, META_HEAPDUP);`
            emit_cap(cap, &crate::ported::utils::metafy(&bytes)); // c:283-285
        }
    }
}

// ===========================================================
// Methods moved verbatim from src/ported/vm_helper because their
// C counterpart's source file maps 1:1 to this Rust module.
// Rust permits multiple inherent impl blocks for the same
// type within a crate, so call sites in vm_helper are unchanged.
// ===========================================================

// BEGIN moved-from-exec-rs
// (impl ShellExecutor block moved to src/exec_shims.rs — see file marker)

// END moved-from-exec-rs

// =====================================================================
// static struct features module_features                            c:307 (terminfo.c)
// =====================================================================


// `bintab` — port of `static struct builtin bintab[]` (terminfo.c).

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

// `module_features` — port of `static struct features module_features`
// from terminfo.c:307.

/// Port of `setup_(UNUSED(Module m))` from `Src/Modules/terminfo.c:316`.
#[allow(unused_variables)]
pub fn setup_(m: *const module) -> i32 {
    // c:316
    // C body c:318-319 — `return 0`. Faithful empty-body port.
    0
}

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

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

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/terminfo.c:338`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {
    // c:338
    // C body c:340-344 — `#ifdef USE_TERMINFO_MODULE zsetupterm(); #endif
    //                     return 0`. Initializes the terminfo database
    //                     for echoti/$terminfo to use.
    let _ = crate::ported::utils::zsetupterm(); // c:359
    0
}

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

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/terminfo.c:359`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {
    // c:359
    // C body c:361-362 — `return 0`. Faithful empty-body port; the
    //                    terminfo database is process-lifetime.
    0
}

/// Capability names pre-loaded into the `${terminfo[…]}` assoc at
/// shell start so iteration via `${(k)terminfo}` enumerates the
/// common subset. Lazy lookups for any other name still resolve
/// through `lookup()`. The list intentionally mirrors the strings
/// that zsh keymap setups commonly read (function keys, navigation,
/// editing, sgr).
pub const COMMON_STRING_CAPS: &[&str] = &[
    // Function keys F1-F20.
    "kf1", "kf2", "kf3", "kf4", "kf5", "kf6", "kf7", "kf8", "kf9", "kf10", "kf11", "kf12", "kf13",
    "kf14", "kf15", "kf16", "kf17", "kf18", "kf19", "kf20", // Cursor / arrow keys.
    "kcuu1", "kcud1", "kcuf1", "kcub1", // Navigation.
    "khome", "kend", "kpp", "knp", // Editing.
    "kbs", "kich1", "kdch1", // Clear / cursor positioning.
    "clear", "ed", "el", "home", "civis", "cnorm", // SGR.
    "smso", "rmso", "smul", "rmul", "bold", "rev", "sgr0",
    // Application keypad / alt-screen / colour.
    "smkx", "rmkx", "smcup", "rmcup", "setaf", "setab",
    // Cursor positioning + edit ops.
    "cup", "ich1", "dch1", "il1", "dl1",
];


static MODULE_FEATURES: OnceLock<Mutex<crate::ported::zsh_h::features>> = OnceLock::new();

// 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 TERMINFO.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<crate::ported::zsh_h::features>) -> Vec<String> {
    vec!["b:echoti".to_string(), "p:terminfo".to_string()]
}

// WARNING: NOT IN TERMINFO.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<crate::ported::zsh_h::features>,
    enables: &mut Option<Vec<i32>>,
) -> i32 {
    if enables.is_none() {
        *enables = Some(vec![1; 2]);
    }
    0
}

// WARNING: NOT IN TERMINFO.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<crate::ported::zsh_h::features>, _e: Option<&[i32]>) -> i32 {
    0
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor ported for `OnceLock<Mutex<T>>` / `OnceLock<
// RwLock<T>>` globals declared above. C zsh uses direct global
// access; Rust needs these wrappers because `OnceLock::get_or_init`
// is the only way to lazily construct shared state. These ported sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port ported.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor ported for `OnceLock<Mutex<T>>` / `OnceLock<
// RwLock<T>>` globals declared above. C zsh uses direct global
// access; Rust needs these wrappers because `OnceLock::get_or_init`
// is the only way to lazily construct shared state. These ported sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port ported.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// WARNING: NOT IN TERMINFO.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<crate::ported::zsh_h::features> {
    MODULE_FEATURES.get_or_init(|| {
        Mutex::new(crate::ported::zsh_h::features {
            bn_list: None,
            bn_size: 1,
            cd_list: None,
            cd_size: 0,
            mf_list: None,
            mf_size: 0,
            pd_list: None,
            pd_size: 1,
            n_abstract: 0,
        })
    })
}

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

    /// c:135 — `getterminfo` for an unknown capability name returns
    /// a Param with PM_UNSET flag set + empty u_str. C semantics:
    /// returns non-NULL HashNode wrapping a PM_UNSET Param (c:168-
    /// 173). Catches a regression where libc::tigetstr's
    /// `(unsigned char*)-1` sentinel leaks through as a valid pointer.
    #[test]
    fn getterminfo_unknown_cap_returns_unset_param() {
        let _g = crate::test_util::global_state_lock();
        use crate::ported::zsh_h::PM_UNSET;
        // termflags check may early-return None if $TERM is bad; treat
        // both Some(unset) and None as acceptable for this regression.
        if let Some(pm) = getterminfo(
            std::ptr::null_mut(),
            "definitely_not_a_real_cap_name_zshrs",
        ) {
            assert!(
                pm.node.flags & PM_UNSET as i32 != 0,
                "PM_UNSET flag must be set for unknown cap"
            );
            assert_eq!(pm.u_str.as_deref(), Some(""), "u_str empty for unknown cap");
        }
    }

    /// c:64 — `echoti` without a cap-name argument must error. The
    /// cap-name is the first positional; missing args means no work to
    /// do, and silent success would mask a usage bug.
    #[test]
    fn echoti_with_no_args_is_usage_error() {
        let _g = crate::test_util::global_state_lock();
        let ops = crate::ported::zsh_h::options {
            ind: [0u8; crate::ported::zsh_h::MAX_OPS],
            args: Vec::new(),
            argscount: 0,
            argsalloc: 0,
        };
        assert_eq!(bin_echoti("echoti", &[], &ops, 0), 1);
    }

    /// c:64 — `echoti` with an unknown capability name must error
    /// rather than emit garbage. zsh's terminfo.c rejects via
    /// `tigetstr(cap) == 0 / (char *)-1`.
    #[test]
    fn echoti_unknown_capability_returns_one() {
        let _g = crate::test_util::global_state_lock();
        let ops = crate::ported::zsh_h::options {
            ind: [0u8; crate::ported::zsh_h::MAX_OPS],
            args: Vec::new(),
            argscount: 0,
            argsalloc: 0,
        };
        let r = bin_echoti("echoti", &["__not_a_terminfo_cap__".to_string()], &ops, 0);
        assert_eq!(r, 1, "echoti must reject unknown caps, not emit garbage");
    }

    /// c:177 — `scanterminfo` iterates the table and returns a
    /// (name, value) list. Must not panic with `TERM=dumb` (a
    /// terminal with effectively zero capabilities). Empty result is
    /// acceptable; panic is not.
    #[test]
    fn scanterminfo_does_not_panic_for_dumb_term() {
        let _g = crate::test_util::global_state_lock();
        // SAFETY: env mutation is process-global. Snapshot + restore.
        let old = std::env::var_os("TERM");
        unsafe {
            std::env::set_var("TERM", "dumb");
        }
        fn cb(_n: &crate::ported::zsh_h::HashNode, _f: i32) {}
        scanterminfo(std::ptr::null_mut(), Some(cb), 0);
        match old {
            Some(v) => unsafe {
                std::env::set_var("TERM", v);
            },
            None => unsafe {
                std::env::remove_var("TERM");
            },
        }
    }

    /// c:316-360 — module-lifecycle stubs return 0 in C.
    #[test]
    fn module_lifecycle_shims_all_return_zero() {
        let _g = crate::test_util::global_state_lock();
        let m = std::ptr::null();
        assert_eq!(setup_(m), 0);
        assert_eq!(boot_(m), 0);
        assert_eq!(cleanup_(m), 0);
        assert_eq!(finish_(m), 0);
    }

    /// c:323 — `features_` writes the advertised feature names and
    /// returns 0. Must be callable without panicking.
    #[test]
    fn features_returns_success() {
        let _g = crate::test_util::global_state_lock();
        let mut features = Vec::new();
        assert_eq!(features_(std::ptr::null(), &mut features), 0);
    }

    /// c:331 — `enables_` toggles the per-feature enable bitmap and
    /// returns 0. Pass None to avoid mutating state; just verify the
    /// success contract.
    #[test]
    fn enables_returns_success_with_none_arg() {
        let _g = crate::test_util::global_state_lock();
        let mut enables: Option<Vec<i32>> = None;
        assert_eq!(enables_(std::ptr::null(), &mut enables), 0);
    }

    // ─── zsh-corpus pins for terminfo lifecycle ─────────────────────

    /// All four lifecycle shims return 0.
    #[test]
    fn terminfo_corpus_lifecycle_returns_zero() {
        let _g = crate::test_util::global_state_lock();
        let m: *const crate::ported::zsh_h::module = std::ptr::null();
        assert_eq!(setup_(m), 0);
        assert_eq!(boot_(m), 0);
        assert_eq!(cleanup_(m), 0);
        assert_eq!(finish_(m), 0);
    }

    /// `getterminfo("never_a_real_cap")` returns PM_UNSET param or None.
    #[test]
    fn terminfo_corpus_unknown_cap_returns_unset_or_none() {
        let _g = crate::test_util::global_state_lock();
        let r = getterminfo(std::ptr::null_mut(), "zzz_not_a_real_cap_xyz");
        if let Some(p) = r {
            assert!(
                (p.node.flags as u32 & crate::ported::zsh_h::PM_UNSET) != 0,
                "unknown cap → PM_UNSET",
            );
        }
    }

    /// `features_` populates feature vec and returns 0.
    #[test]
    fn terminfo_corpus_features_populates_vec() {
        let _g = crate::test_util::global_state_lock();
        let mut features = Vec::new();
        let r = features_(std::ptr::null(), &mut features);
        assert_eq!(r, 0);
    }
}