zshrs 0.11.40

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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! Termcap module — port of `Src/Modules/termcap.c`.
//!
//! This depends on the termcap stuff in init.c                              // c:150
//!
//! C source has 0 structs/enums (uses libtermcap globals + the
//! `boolcodes[]`/`numcodes[]`/`strcodes[]` arrays from libtermcap
//! itself). Rust port matches: 0 types, only static capability
//! tables for an in-memory ANSI approximation.
//!
//! Architectural divergence: C links against libtermcap (or
//! libtinfo) and reads `/etc/termcap` via `tgetent(3)` /
//! `tgetflag(3)` / `tgetnum(3)` / `tgetstr(3)`. zshrs computes a
//! minimal capability set inline based on `$TERM` so we don't drag
//! libtermcap into the build. Function signatures + observable
//! outputs match C 1:1.

use crate::ported::options::optlookup;
use crate::ported::params::{getsparam, TERMFLAGS};
use crate::ported::utils::{zsetupterm, zwarnnam};
use crate::ported::zsh_h::{features, isset, module, INTERACTIVE};
use crate::zsh_h::TERM_UNKNOWN;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Mutex, OnceLock};

/// Port of `ztgetflag(char *s)` from `Src/Modules/termcap.c:54`. Wraps
/// libtermcap's `tgetflag()` to disambiguate "off" from "not
/// present" via the `boolcodes[]` table walk: if `tgetflag`
/// returns 0 AND the cap is in `boolcodes`, it's a known cap that's
/// off (return 0); if not in boolcodes, it's unknown (return -1).
///
/// C signature: `static int ztgetflag(char *s)`. Returns 1 / 0 / -1.
pub fn ztgetflag(s: &str) -> i32 {
    // c:54
    if !ensure_termcap_loaded() {
        return -1; // tgetent failed
    }
    let s_c = match std::ffi::CString::new(s) {
        Ok(c) => c,
        Err(_) => return -1,
    };
    // c:62 — `switch (tgetflag(s)) { case 1: return 1; case 0: ...; }`
    let flag = {
        let _g = TERMCAP_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { tgetflag(s_c.as_ptr()) }
    };
    match flag {
        // c:62
        1 => 1, // c:64
        _ => {
            // c:65-72 — `for (b = boolcodes; *b; b++) if (!strcmp(*b, s)) return 0;`
            for b in BOOLCODES {
                // c:65
                if *b == s {
                    // c:66
                    return 0; // c:68
                }
            }
            -1 // c:80
        }
    }
}

/// Port of `bin_echotc(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))` from `Src/Modules/termcap.c:80`. The
/// `echotc` builtin: looks up a capability and emits its value
/// (or its tparam'd form when args follow).
///
/// C signature: `static int bin_echotc(char *name, char **argv, Options ops, int func)`.
/// WARNING: param names don't match C — Rust=(name, argv, _ops) vs C=(name, argv, ops, func)
pub fn bin_echotc(
    name: &str,
    argv: &[String],
    _ops: &crate::ported::zsh_h::options,
    _func: i32,
) -> i32 {
    // c:80
    const TERM_BAD: i32 = 1 << 1;
    if argv.is_empty() {
        // c:85
        zwarnnam(name, "missing argument");
        return 1;
    }
    let s: &str = argv[0].as_str();
    let argv_rest: Vec<&str> = argv[1..].iter().map(String::as_str).collect(); // c:85 (s = *argv++)

    // c:87 — `if (termflags & TERM_BAD) return 1;`
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_BAD) != 0 {
        // c:87
        return 1; // c:88
    }
    // c:89 — `if ((termflags & TERM_UNKNOWN) && (isset(INTERACTIVE) || !init_term())) return 1;`
    if (TERMFLAGS.load(Ordering::Relaxed) & TERM_UNKNOWN) != 0 {
        // c:89
        let interactive = isset(INTERACTIVE);
        if interactive || !ensure_termcap_loaded() {
            // c:89-90
            return 1; // c:90
        }
    }
    if !ensure_termcap_loaded() {
        return 1;
    }
    let s_c = match std::ffi::CString::new(s) {
        Ok(c) => c,
        Err(_) => return 1,
    };

    // c:92 — `if ((num = tgetnum(s)) != -1) { printf("%d\n", num); return 0; }`
    let num = {
        let _g = TERMCAP_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { tgetnum(s_c.as_ptr()) }
    }; // c:92
    if num != -1 {
        // c:92
        println!("{}", num); // c:93
        return 0; // c:94
    }
    // c:97 — `switch (ztgetflag(s))`.
    match ztgetflag(s) {
        // c:97
        -1 => {} // c:99
        0 => {
            // c:100
            println!("no"); // c:101
            return 0; // c:102
        }
        _ => {
            // c:103
            println!("yes"); // c:104
            return 0; // c:105
        }
    }
    // c:108-110 — `t = tgetstr(s, &u);`
    let mut buf: [libc::c_char; 2048] = [0; 2048]; // c:84
    let mut area = buf.as_mut_ptr();
    let value = {
        let _g = TERMCAP_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let t = unsafe { tgetstr(s_c.as_ptr(), &mut area) }; // c:109
        if t.is_null() || (t as isize) == -1 || unsafe { *t } == 0 {
            // c:110
            // capability doesn't exist, or (if boolean) is off           // c:110
            drop(_g);
            zwarnnam(name, &format!("no such capability: {}", s)); // c:113
            return 1; // c:114
        }
        unsafe { std::ffi::CStr::from_ptr(t) }
            .to_string_lossy()
            .into_owned()
    };

    // c:117-122 — count arguments expected by the cap's `%d/%2/%3/%./%+` codes.
    let mut argct = 0usize; // c:117
    let bytes = value.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        // c:117
        if bytes[i] == b'%' {
            // c:118
            i += 1;
            if i < bytes.len() {
                // c:119
                match bytes[i] {
                    // c:119-120
                    b'd' | b'2' | b'3' | b'.' | b'+' => argct += 1, // c:120
                    _ => {}
                }
            }
        }
        i += 1;
    }

    // c:124-128 — `if (arrlen(argv) != argct) zwarnnam("not enough/too many args"); return 1;`
    if argv_rest.len() != argct {
        // c:124
        let msg = if argv_rest.len() < argct {
            "not enough arguments"
        }
        // c:125
        else {
            "too many arguments"
        }; // c:126
        zwarnnam(name, msg); // c:125-126
        return 1; // c:127
    }

    // c:131-137 — `tputs(t, 1, putraw)` or `tputs(tgoto(t, num, atoi(*argv)), 1, putraw)`.
    if argct == 0 {
        // c:131
        // c:132 — `tputs(t, 1, putraw);` — direct emit of raw cap.
        print!("{}", value); // c:132
    } else {
        // c:135 — `num = (argv[1]) ? atoi(argv[1]) : atoi(*argv);`
        // c:136 — `tputs(tgoto(t, num, atoi(*argv)), 1, putraw);`
        // libtinfo `tgoto` resolves the cap with col=arg0/line=arg1; the
        // static-link path emits the cap with %d/%2 replacement so cm
        // ("\E[%i%d;%dH") still produces a usable ANSI sequence.
        let mut out = value;
        for arg in &argv_rest {
            out = out.replacen("%d", arg, 1);
            out = out.replacen("%2", arg, 1);
            out = out.replacen("%3", arg, 1);
        }
        print!("{}", out); // c:136
    }
    0 // c:144
}

/// Port of `static HashNode gettermcap(UNUSED(HashTable ht), const char *name)`
/// from `Src/Modules/termcap.c:144-199`. Synthesised Param with
/// PM_SCALAR + value or PM_UNSET on no match.
pub fn gettermcap(
    _ht: *mut crate::ported::zsh_h::HashTable,
    name: &str,
) -> Option<crate::ported::zsh_h::Param> {
    // c:144
    use crate::ported::zsh_h::{hashnode, param, Param, PM_READONLY, PM_SCALAR, PM_UNSET};

    let mk = |s: String, extra: i32| -> Param {
        Box::new(param {
            node: hashnode {
                next: None,
                nam: name.to_string(),
                flags: PM_READONLY as i32 | extra,
            },
            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,
        })
    };

    if !ensure_termcap_loaded() {
        return None;
    }
    let n_c = std::ffi::CString::new(name).ok()?;
    // c:163 — try string cap first (most common via `${termcap[name]}`).
    let mut buf: [libc::c_char; 1024] = [0; 1024];
    let mut area = buf.as_mut_ptr();
    let _g = TERMCAP_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let raw = unsafe { tgetstr(n_c.as_ptr(), &mut area) }; // c:163
    if !raw.is_null() {
        let s = unsafe { std::ffi::CStr::from_ptr(raw) }
            .to_string_lossy()
            .into_owned();
        return Some(mk(s, PM_SCALAR as i32));
    }
    // c:170 — numeric cap fallback.
    let n = unsafe { tgetnum(n_c.as_ptr()) }; // c:170
    if n != -1 {
        return Some(mk(n.to_string(), PM_SCALAR as i32));
    }
    // c:175 — boolean cap fallback.
    match unsafe { tgetflag(n_c.as_ptr()) } {
        1 => Some(mk("yes".to_string(), PM_SCALAR as i32)),
        0 => {
            // Known but off → "" only if it's in BOOLCODES.
            if BOOLCODES.iter().any(|b| *b == name) {
                Some(mk(String::new(), PM_SCALAR as i32))
            } else {
                // c:191-193 — `pm->u.str = ""; pm->node.flags |= PM_UNSET;`
                Some(mk(String::new(), PM_SCALAR as i32 | PM_UNSET as i32))
            }
        }
        _ => Some(mk(String::new(), PM_SCALAR as i32 | PM_UNSET as i32)),
    }
}

/// Port of `scantermcap(UNUSED(HashTable ht), ScanFunc func, int flags)` from `Src/Modules/termcap.c:200`. The
/// magic-assoc scan callback for `${(k)termcap}` / `${(kv)termcap}`.
/// Walks the bool/num/string code arrays and yields each
/// (name, value) pair where the capability is known.
///
/// Port of `static void scantermcap(UNUSED(HashTable ht), ScanFunc func, int flags)`
/// from `Src/Modules/termcap.c:200-235`. Walks the bool/num/string
/// code arrays and invokes the callback per known cap.
pub fn scantermcap(
    _ht: *mut crate::ported::zsh_h::HashTable,
    func: Option<crate::ported::zsh_h::ScanFunc>,
    flags: i32,
) {
    // c:200
    use crate::ported::zsh_h::{hashnode, param, PM_SCALAR};
    let f = match func {
        Some(f) => f,
        None => return,
    };
    if !ensure_termcap_loaded() {
        return;
    }
    for &name in BOOLCODES
        .iter()
        .chain(NUMCODES.iter())
        .chain(STRCODES.iter())
    {
        if let Some(pm) = gettermcap(std::ptr::null_mut(), name) {
            // Skip PM_UNSET entries (unknown caps).
            use crate::ported::zsh_h::PM_UNSET;
            if (pm.node.flags & PM_UNSET as i32) != 0 {
                continue;
            }
            let node = param {
                node: hashnode {
                    next: None,
                    nam: name.to_string(),
                    flags: PM_SCALAR as i32,
                },
                u_data: 0,
                u_arr: None,
                u_str: pm.u_str.clone(),
                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(node.node.clone());
            f(&node_box, flags);
        }
    }
}

// `capability_lookup` removed — Rust-only invention with hardcoded
// ANSI escapes that has no counterpart in Src/Modules/termcap.c.
// The C source links libtermcap (or libtinfo) and reads /etc/termcap
// via tgetent(3) + tgetflag(3) / tgetnum(3) / tgetstr(3) directly.
// Each call site below now invokes those libc-level routines via FFI.

unsafe extern "C" {
    fn tgetent(bp: *mut libc::c_char, name: *const libc::c_char) -> libc::c_int;
    fn tgetflag(id: *const libc::c_char) -> libc::c_int;
    fn tgetnum(id: *const libc::c_char) -> libc::c_int;
    fn tgetstr(id: *const libc::c_char, area: *mut *mut libc::c_char) -> *mut libc::c_char;
}

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

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

// `module_features` — port of `static struct features module_features`
// from termcap.c:314.

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

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

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

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/termcap.c:345`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {
    // c:345
    // C body c:347-350 — `#ifdef HAVE_TGETENT zsetupterm(); #endif
    //                     return 0`. Initializes the termcap database
    //                     for echotc/$termcap to use.
    let _ = zsetupterm(); // c:365
    0
}

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

// =====================================================================
// static struct features module_features                            c:314 (termcap.c)
// =====================================================================

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

/// Serialises every call into libtermcap. C `Src/Modules/termcap.c`
/// uses `tgetent(3)` / `tgetflag(3)` / `tgetnum(3)` / `tgetstr(3)`
/// directly; libtermcap (and libtinfo's compat layer) reads/writes
/// file-scope globals (`PC`, `BC`, `UP`, `ospeed`, the term-entry
/// buffer populated by `tgetent`) and is not thread-safe. zsh is
/// single-threaded so the C source is race-free under that invariant.
/// Rust callers (`ztgetflag`, `bin_echotc`, `gettermcap`, `scantermcap`)
/// can fire from concurrent test threads, so the lock restores the
/// single-writer assumption.
static TERMCAP_LOCK: Mutex<()> = Mutex::new(());

/// `boolcodes[]` from libtermcap — list of all known boolean
/// capability 2-char codes. The subset zshrs's in-memory table
/// recognises; full libtermcap has more.
static BOOLCODES: &[&str] = &[
    "am", "bs", "bw", "da", "db", "eo", "es", "gn", "hc", "hs", "in", "km", "mi", "ms", "nc", "ns",
    "os", "ul", "ut", "xb", "xn", "xo", "xs", "xt",
];

/// `numcodes[]` from libtermcap — list of known numeric codes.
static NUMCODES: &[&str] = &[
    "co", "it", "lh", "lm", "lw", "li", "ma", "MW", "Nl", "pa", "Nco", "sg", "tw", "ug", "vt", "ws",
];

/// `strcodes[]` from libtermcap — list of known string codes.
static STRCODES: &[&str] = &[
    "ae", "al", "AL", "ac", "as", "bc", "bl", "bt", "cb", "cd", "ce", "cm", "cr", "cs", "ct", "cl",
    "cv", "DC", "DL", "DO", "do", "ds", "ec", "ed", "ei", "fs", "ho", "hd", "hu", "i1", "i3", "i2",
    "ic", "IC", "if", "im", "ip", "is", "kA", "kb", "kB", "kC", "kd", "kD", "kE", "kF", "ke", "kh",
    "kH", "kI",
    // `km` is a BOOLEAN cap ("Has Meta Key") per termcap(5); it lives
    // in BOOLCODES (line 316) and must NOT also appear here. Removed
    // 2026-05 to fix scantermcap duplicate-key emission.
    "kL", "kl", "kM", "kN", "kP", "kr", "kR", "kS", "ks", "kT", "kt", "ku", "l0", "l1", "l2", "l3",
    "l4", "l5", "l6", "l7", "l8", "l9", "le", "ll", "ma", "mb", "MC", "md", "me", "mh", "mk", "mm",
    "mo", "mp", "mr", "nd", "nl", "nw", "pc", "pf", "pk", "pl", "pn", "po", "pO", "ps", "px", "rc",
    "rf", "RI", "rp", "rs", "sa", "sc", "se", "SF", "sf", "so", "SR", "sr", "st", "ta", "te", "ti",
    "ts", "uc", "ue", "up", "UP", "us", "vb", "ve", "vi", "vs", "wi",
];

/// WARNING: NOT IN TERMCAP.C — AtomicI32-protected lazy termcap init; C uses libtermcap `tgetent` once at boot
/// (equivalent C logic at Src/Modules/termcap.c:82).
/// Initialize libtermcap's database for `$TERM`. Returns true on success.
/// C call site: `tgetent(NULL, term)` (zsh.h-compatible portable form).
fn ensure_termcap_loaded() -> bool {
    // 0 = uninit, 1 = ok, -1 = failed. Cache the libtermcap state for
    // the lifetime of the process, matching libtermcap's own behavior.
    static STATE: AtomicI32 = AtomicI32::new(0);
    match STATE.load(Ordering::Relaxed) {
        1 => true,
        -1 => false,
        _ => {
            // C `init_term` (Src/init.c:771) reads the `term` global
            // which is the shell's $TERM param. The previous Rust port
            // read \`std::env::var(\"TERM\")\` which diverges when the
            // shell has updated TERM via paramtab without exporting yet.
            // Route through getsparam — same env-vs-paramtab family as
            // the recent newuser HOME / bin_strftime TZ fixes.
            let term = getsparam("TERM").unwrap_or_else(|| "dumb".into());
            let term_c = match std::ffi::CString::new(term) {
                Ok(c) => c,
                Err(_) => return false,
            };
            let r = {
                let _g = TERMCAP_LOCK.lock().unwrap_or_else(|e| e.into_inner());
                unsafe { tgetent(std::ptr::null_mut(), term_c.as_ptr()) }
            };
            let ok = r > 0;
            STATE.store(if ok { 1 } else { -1 }, Ordering::Relaxed);
            ok
        }
    }
}

// =====================================================
// ShellExecutor shim
// =====================================================

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

static MODULE_FEATURES: OnceLock<Mutex<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 TERMCAP.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>) -> Vec<String> {
    vec!["b:echotc".to_string(), "p:termcap".to_string()]
}

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

// WARNING: NOT IN TERMCAP.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>, _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 TERMCAP.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> {
    MODULE_FEATURES.get_or_init(|| {
        Mutex::new(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::*;

    #[test]
    fn ztgetflag_known_on_returns_one() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(ztgetflag("am"), 1);
    }

    #[test]
    fn ztgetflag_unknown_returns_minus_one() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(ztgetflag("zz"), -1);
    }

    #[test]
    fn gettermcap_co_returns_columns() {
        let _g = crate::test_util::global_state_lock();
        let pm = gettermcap(std::ptr::null_mut(), "co").expect("co must resolve to Param");
        let v = pm.u_str.as_deref().unwrap_or("");
        let n: i32 = v.parse().unwrap_or(0);
        assert!(n > 0);
    }

    #[test]
    fn gettermcap_unknown_returns_unset_param() {
        let _g = crate::test_util::global_state_lock();
        use crate::ported::zsh_h::PM_UNSET;
        // C semantics (c:191-193): unknown caps return non-NULL Param
        // with PM_UNSET flag + empty u_str (not NULL HashNode).
        if let Some(pm) = gettermcap(std::ptr::null_mut(), "zz_nonexistent") {
            assert!(pm.node.flags & PM_UNSET as i32 != 0, "PM_UNSET set");
        }
    }

    #[test]
    fn scantermcap_emits_bool_caps() {
        let _g = crate::test_util::global_state_lock();
        use std::sync::Mutex;
        static SEEN: Mutex<Vec<String>> = Mutex::new(Vec::new());
        SEEN.lock().unwrap().clear();
        fn cb(node: &crate::ported::zsh_h::HashNode, _flags: i32) {
            SEEN.lock().unwrap().push(node.nam.clone());
        }
        scantermcap(std::ptr::null_mut(), Some(cb), 0);
        let seen = SEEN.lock().unwrap().clone();
        assert!(seen.iter().any(|k| k == "am"));
    }

    /// c:80-85 — `bin_echotc` with no args writes "missing argument"
    /// to stderr and returns 1. Catches a regression that
    /// dereferences argv[0] on empty input.
    #[test]
    fn echotc_with_no_args_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_echotc("echotc", &[], &ops, 0);
        assert_eq!(r, 1, "echotc must report missing-arg error");
    }

    /// c:97 — `echotc <unknown>` falls through tgetnum / tgetstr /
    /// ztgetflag, all return -1 / null, so the function exits
    /// nonzero. Verifies the unknown-cap default path doesn't write
    /// garbage to stdout.
    #[test]
    fn echotc_unknown_cap_returns_nonzero() {
        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_echotc("echotc", &["zz_definitely_not_a_cap".to_string()], &ops, 0);
        assert_ne!(r, 0, "unknown cap must error");
    }

    /// c:54-72 — `ztgetflag` on a NUL-byte-containing string must
    /// not panic. CString::new fails for embedded NULs; the port
    /// must catch that and return -1.
    #[test]
    fn ztgetflag_rejects_embedded_nul() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            ztgetflag("a\0m"),
            -1,
            "embedded NUL must surface as -1, not panic or false-match"
        );
    }

    /// c:54 — `ztgetflag("")` must be -1 (the empty string is in
    /// neither the live termcap nor the boolcodes table).
    #[test]
    fn ztgetflag_empty_string_returns_neg_one() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(ztgetflag(""), -1);
    }

    /// c:200 — `scantermcap` results must have unique keys (the
    /// boolcodes / numcodes / strcodes tables are disjoint by C
    /// design). Catches a regression that double-emits a cap when
    /// two tables claim it.
    #[test]
    fn scantermcap_keys_are_unique() {
        let _g = crate::test_util::global_state_lock();
        use std::sync::Mutex;
        static KEYS: Mutex<Vec<String>> = Mutex::new(Vec::new());
        KEYS.lock().unwrap().clear();
        fn cb(node: &crate::ported::zsh_h::HashNode, _flags: i32) {
            KEYS.lock().unwrap().push(node.nam.clone());
        }
        scantermcap(std::ptr::null_mut(), Some(cb), 0);
        let collected = KEYS.lock().unwrap().clone();
        let mut seen = std::collections::HashSet::new();
        for k in &collected {
            assert!(
                seen.insert(k.clone()),
                "duplicate termcap key emitted: {}",
                k
            );
        }
    }

    /// c:200 — `scantermcap` must never produce empty key strings
    /// (every entry's key comes from the *codes tables, all of
    /// which have non-empty names per the termcap spec).
    #[test]
    fn scantermcap_keys_are_nonempty() {
        let _g = crate::test_util::global_state_lock();
        use std::sync::Mutex;
        static KEYS: Mutex<Vec<String>> = Mutex::new(Vec::new());
        KEYS.lock().unwrap().clear();
        fn cb(node: &crate::ported::zsh_h::HashNode, _flags: i32) {
            KEYS.lock().unwrap().push(node.nam.clone());
        }
        scantermcap(std::ptr::null_mut(), Some(cb), 0);
        for k in KEYS.lock().unwrap().iter() {
            assert!(
                !k.is_empty(),
                "scantermcap emitted empty key — null entry leak?"
            );
        }
    }

    /// c:144 — `gettermcap` is case-sensitive (termcap names are
    /// always 2 lowercase letters). Pinning the case-sensitive
    /// behavior protects scripts that grep for specific cap names.
    #[test]
    fn gettermcap_is_case_sensitive() {
        let _g = crate::test_util::global_state_lock();
        use crate::ported::zsh_h::PM_UNSET;
        // "co" is the columns cap; "CO" is unknown (PM_UNSET).
        let r1 = gettermcap(std::ptr::null_mut(), "co").expect("co Param");
        assert!(r1.node.flags & PM_UNSET as i32 == 0, "co must be set");
        if let Some(r2) = gettermcap(std::ptr::null_mut(), "CO") {
            assert!(
                r2.node.flags & PM_UNSET as i32 != 0,
                "termcap names case-sensitive; CO must be PM_UNSET"
            );
        }
    }

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

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Modules/termcap.c.
    // ═══════════════════════════════════════════════════════════════════

    /// c:54 — `ztgetflag("")` returns -1 (no such cap).
    #[test]
    fn ztgetflag_empty_string_returns_minus_one() {
        let _g = crate::test_util::global_state_lock();
        let r = ztgetflag("");
        assert_eq!(r, -1, "empty cap name → -1");
    }

    /// c:54 — `ztgetflag("zz")` returns -1 (no such 2-letter cap).
    #[test]
    fn ztgetflag_unknown_cap_returns_minus_one() {
        let _g = crate::test_util::global_state_lock();
        let r = ztgetflag("zz");
        assert_eq!(r, -1, "unknown cap → -1");
    }

    /// c:54 — `ztgetflag("am")` (auto-margin) returns 0 or 1
    /// (depending on terminal). Pin: not -1 since 'am' is a known cap.
    #[test]
    fn ztgetflag_known_cap_returns_zero_or_one() {
        let _g = crate::test_util::global_state_lock();
        let r = ztgetflag("am");
        assert!(r == 0 || r == 1, "known cap → 0 or 1, got {}", r);
    }

    /// c:54 — `ztgetflag` is deterministic for the same input.
    #[test]
    fn ztgetflag_is_deterministic() {
        let _g = crate::test_util::global_state_lock();
        for cap in &["am", "co", "zz", ""] {
            let first = ztgetflag(cap);
            for _ in 0..5 {
                assert_eq!(ztgetflag(cap), first, "{:?} must be pure", cap);
            }
        }
    }

    /// c:80 — `bin_echotc` with no args returns nonzero (usage error).
    #[test]
    fn bin_echotc_no_args_returns_nonzero() {
        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_echotc("echotc", &[], &ops, 0);
        assert_ne!(r, 0, "no cap name → usage error");
    }

    /// c:210 — `gettermcap(_, "")` returns Some(PM_UNSET).
    #[test]
    fn gettermcap_empty_name_returns_pm_unset() {
        let _g = crate::test_util::global_state_lock();
        use crate::ported::zsh_h::PM_UNSET;
        if let Some(pm) = gettermcap(std::ptr::null_mut(), "") {
            assert!(pm.node.flags & PM_UNSET as i32 != 0);
        }
    }

    /// c:323 — split per-hook lifecycle for finer failure resolution.
    #[test]
    fn termcap_setup_returns_zero_pin() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(setup_(std::ptr::null()), 0);
    }

    /// c:373 — features_ returns 0.
    #[test]
    fn termcap_features_returns_zero_pin() {
        let _g = crate::test_util::global_state_lock();
        let mut f = Vec::new();
        assert_eq!(features_(std::ptr::null(), &mut f), 0);
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Modules/termcap.c
    // c:32 ztgetflag / c:69 bin_echotc / c:210 gettermcap / c:288 scantermcap
    // ═══════════════════════════════════════════════════════════════════

    /// c:32 — `ztgetflag` is pure (multiple calls same result).
    #[test]
    fn ztgetflag_is_pure() {
        let _g = crate::test_util::global_state_lock();
        let r = ztgetflag("am");
        for _ in 0..5 {
            assert_eq!(ztgetflag("am"), r, "ztgetflag must be pure");
        }
    }

    /// c:32 — `ztgetflag` returns -1/0/1 only (no other values).
    #[test]
    fn ztgetflag_return_value_in_canonical_set() {
        let _g = crate::test_util::global_state_lock();
        for cap in ["am", "bw", "xn", "co", "li", "xyz_unknown_cap"] {
            let r = ztgetflag(cap);
            assert!(
                r == -1 || r == 0 || r == 1,
                "ztgetflag({:?}) = {} not in {{-1, 0, 1}}",
                cap,
                r
            );
        }
    }

    /// c:32 — multi-char/unknown caps still return -1.
    #[test]
    fn ztgetflag_arbitrary_strings_return_minus_one() {
        let _g = crate::test_util::global_state_lock();
        for s in ["xyz", "long_unknown_cap_name", "AAA", "zzz"] {
            assert_eq!(ztgetflag(s), -1, "unknown cap {:?} must return -1", s);
        }
    }

    /// c:69 — `bin_echotc` returns i32 (type pinning).
    #[test]
    fn bin_echotc_returns_i32_type() {
        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 _: i32 = bin_echotc("echotc", &[], &ops, 0);
    }

    /// c:69 — `bin_echotc` empty + known-bad inputs all return nonzero.
    #[test]
    fn bin_echotc_empty_string_returns_nonzero() {
        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_echotc("echotc", &["".into()], &ops, 0);
        assert_ne!(r, 0, "empty cap name → error");
    }

    /// c:210 — `gettermcap("")` returns None (empty cap name).
    #[test]
    fn gettermcap_empty_string_returns_none() {
        let _g = crate::test_util::global_state_lock();
        let r = gettermcap(std::ptr::null_mut(), "");
        // Either None or Some(PM_UNSET) per C convention.
        let _ = r; // pin no-panic
    }

    /// c:210 — `gettermcap` is deterministic for same input.
    #[test]
    fn gettermcap_is_deterministic() {
        let _g = crate::test_util::global_state_lock();
        let a = gettermcap(std::ptr::null_mut(), "co").is_some();
        for _ in 0..5 {
            let b = gettermcap(std::ptr::null_mut(), "co").is_some();
            assert_eq!(a, b, "gettermcap must be deterministic");
        }
    }

    /// c:365-410 — full lifecycle setup→features→enables→boot→cleanup→finish.
    #[test]
    fn termcap_full_lifecycle_returns_zero() {
        let _g = crate::test_util::global_state_lock();
        let null = std::ptr::null();
        assert_eq!(setup_(null), 0);
        let mut feats = Vec::new();
        let _ = features_(null, &mut feats);
        let mut enables: Option<Vec<i32>> = None;
        let _ = enables_(null, &mut enables);
        assert_eq!(boot_(null), 0);
        assert_eq!(cleanup_(null), 0);
        assert_eq!(finish_(null), 0);
    }

    /// c:365 — setup_ idempotent.
    #[test]
    fn termcap_setup_idempotent() {
        let _g = crate::test_util::global_state_lock();
        for _ in 0..10 {
            assert_eq!(setup_(std::ptr::null()), 0);
        }
    }

    /// c:410 — finish_ idempotent.
    #[test]
    fn termcap_finish_idempotent() {
        let _g = crate::test_util::global_state_lock();
        for _ in 0..10 {
            assert_eq!(finish_(std::ptr::null()), 0);
        }
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity tests for Src/Modules/termcap.c
    // c:32 ztgetflag / c:69 bin_echotc / c:210 gettermcap / c:288 scantermcap
    // ═══════════════════════════════════════════════════════════════════

    /// c:32 — `ztgetflag` returns i32 (compile-time pin).
    #[test]
    fn ztgetflag_returns_i32_type() {
        let _g = crate::test_util::global_state_lock();
        let _: i32 = ztgetflag("am");
    }

    /// c:32 — `ztgetflag("")` empty input returns -1 (unknown cap).
    #[test]
    fn ztgetflag_empty_string_returns_negative() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(ztgetflag(""), -1, "empty cap name must return -1 (unknown)");
    }

    /// c:32 — `ztgetflag` is deterministic.
    #[test]
    fn ztgetflag_deterministic_for_unknown() {
        let _g = crate::test_util::global_state_lock();
        for s in ["zz_unknown", "AAA", "garbage"] {
            let first = ztgetflag(s);
            for _ in 0..5 {
                assert_eq!(ztgetflag(s), first, "ztgetflag({:?}) must be pure", s);
            }
        }
    }

    /// c:69 — `bin_echotc` no-args returns nonzero (usage error, alt pin).
    #[test]
    fn bin_echotc_no_args_usage_error_alt() {
        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_echotc("echotc", &[], &ops, 0);
        assert_ne!(r, 0, "no args → usage error");
    }

    /// c:69 — `bin_echotc` exit code is non-negative across argv shapes.
    #[test]
    fn bin_echotc_exit_code_non_negative() {
        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,
        };
        for argv in [
            vec![],
            vec!["".into()],
            vec!["bl".into()],
            vec!["zz_unknown".into()],
            vec!["cm".into(), "5".into(), "10".into()],
        ] {
            let r = bin_echotc("echotc", &argv, &ops, 0);
            assert!(
                r >= 0,
                "exit code must be non-negative, got {} for {:?}",
                r,
                argv
            );
        }
    }

    /// c:210 — `gettermcap` returns Option<Param> (compile-time pin).
    #[test]
    fn gettermcap_returns_option_param_type() {
        let _g = crate::test_util::global_state_lock();
        let _: Option<crate::ported::zsh_h::Param> = gettermcap(std::ptr::null_mut(), "co");
    }

    /// c:288 — `scantermcap` returns void (compile-time pin).
    #[test]
    fn scantermcap_none_callback_returns_void_type() {
        let _g = crate::test_util::global_state_lock();
        let _: () = scantermcap(std::ptr::null_mut(), None, 0);
    }

    /// c:288 — `scantermcap` is safe across various flag values.
    #[test]
    fn scantermcap_various_flags_no_panic() {
        let _g = crate::test_util::global_state_lock();
        for flags in [0i32, 1, 2, 0xff, -1] {
            scantermcap(std::ptr::null_mut(), None, flags);
        }
    }

    /// c:365 — `setup_` returns i32 (compile-time pin).
    #[test]
    fn termcap_setup_returns_i32_type() {
        let _g = crate::test_util::global_state_lock();
        let _: i32 = setup_(std::ptr::null());
    }

    /// c:381 — `enables_` returns i32 + None enables-out safe.
    #[test]
    fn termcap_enables_with_none_returns_i32() {
        let _g = crate::test_util::global_state_lock();
        let mut e: Option<Vec<i32>> = None;
        let _: i32 = enables_(std::ptr::null(), &mut e);
    }

    /// c:365/373/381/388/399/410 — each lifecycle hook returns 0 individually.
    #[test]
    fn termcap_each_lifecycle_hook_returns_zero_individually() {
        let _g = crate::test_util::global_state_lock();
        let null = std::ptr::null();
        let mut v: Vec<String> = Vec::new();
        let mut e: Option<Vec<i32>> = None;
        assert_eq!(setup_(null), 0, "c:365 setup_");
        assert_eq!(features_(null, &mut v), 0, "c:373 features_");
        assert_eq!(enables_(null, &mut e), 0, "c:381 enables_");
        assert_eq!(boot_(null), 0, "c:388 boot_");
        assert_eq!(cleanup_(null), 0, "c:399 cleanup_");
        assert_eq!(finish_(null), 0, "c:410 finish_");
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional C-parity pins for Src/Modules/termcap.c
    // c:32 ztgetflag / c:69 bin_echotc / c:210 gettermcap /
    // c:288 scantermcap / c:399/410 cleanup/finish idempotency
    // ═══════════════════════════════════════════════════════════════════

    /// c:399 — `cleanup_` is idempotent.
    #[test]
    fn termcap_cleanup_idempotent_repeated_calls() {
        let _g = crate::test_util::global_state_lock();
        for _ in 0..10 {
            assert_eq!(cleanup_(std::ptr::null()), 0);
        }
    }

    /// c:399 — `cleanup_` return type i32 (compile-time pin).
    #[test]
    fn termcap_cleanup_returns_i32_type() {
        let _g = crate::test_util::global_state_lock();
        let _: i32 = cleanup_(std::ptr::null());
    }

    /// c:410 — `finish_` return type i32 (compile-time pin).
    #[test]
    fn termcap_finish_returns_i32_type() {
        let _g = crate::test_util::global_state_lock();
        let _: i32 = finish_(std::ptr::null());
    }

    /// c:388 — `boot_` return type i32 (compile-time pin).
    #[test]
    fn termcap_boot_returns_i32_type() {
        let _g = crate::test_util::global_state_lock();
        let _: i32 = boot_(std::ptr::null());
    }

    /// c:388 — `boot_` is idempotent.
    #[test]
    fn termcap_boot_idempotent_repeated_calls() {
        let _g = crate::test_util::global_state_lock();
        for _ in 0..10 {
            let _ = boot_(std::ptr::null());
        }
    }

    /// c:32 — `ztgetflag` deterministic for known cap names.
    #[test]
    fn ztgetflag_deterministic_for_common_caps() {
        let _g = crate::test_util::global_state_lock();
        for cap in ["am", "bw", "xn", "km"] {
            let a = ztgetflag(cap);
            let b = ztgetflag(cap);
            assert_eq!(a, b, "ztgetflag({:?}) must be deterministic", cap);
        }
    }

    /// c:32 — `ztgetflag` very long cap name doesn't panic.
    #[test]
    fn ztgetflag_long_cap_name_no_panic() {
        let _g = crate::test_util::global_state_lock();
        let long = "x".repeat(500);
        let _ = ztgetflag(&long);
    }

    /// c:69 — `bin_echotc` various func values don't panic.
    #[test]
    fn bin_echotc_various_func_values_no_panic() {
        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,
        };
        for func in [-1, 0, 1, 100, i32::MAX] {
            let _ = bin_echotc("echotc", &[], &ops, func);
        }
    }

    /// c:69 — `bin_echotc` deterministic for unknown cap name.
    #[test]
    fn bin_echotc_deterministic_unknown_cap() {
        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 args = vec!["__never_real_cap_xyz__".to_string()];
        let r1 = bin_echotc("echotc", &args, &ops, 0);
        let r2 = bin_echotc("echotc", &args, &ops, 0);
        assert_eq!(r1, r2, "bin_echotc unknown cap must be deterministic");
    }

    /// c:210 — `gettermcap("")` empty name doesn't panic.
    #[test]
    fn gettermcap_empty_name_no_panic() {
        let _g = crate::test_util::global_state_lock();
        let _ = gettermcap(std::ptr::null_mut(), "");
    }

    /// c:288 — `scantermcap` with None callback safe on repeat.
    #[test]
    fn scantermcap_none_callback_repeated_safe() {
        let _g = crate::test_util::global_state_lock();
        for _ in 0..5 {
            scantermcap(std::ptr::null_mut(), None, 0);
        }
    }

    /// c:381 — `enables_` with Some(non-empty) doesn't panic.
    #[test]
    fn termcap_enables_with_some_non_empty_no_panic() {
        let _g = crate::test_util::global_state_lock();
        let mut e: Option<Vec<i32>> = Some(vec![1, 2, 3]);
        let _ = enables_(std::ptr::null(), &mut e);
    }
}