zshrs 0.11.5

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
//! File stat module — port of `Src/Modules/stat.c`.
//!
//! C source has 2 enums (`statnum`, `statflags`) — both anonymous-
//! valued integer-constant tables. Rust port mirrors as constants
//! to avoid Rust-only type wrappers.
//!
//! Functions (matching C 1:1):
//!   - statmodeprint  `[c:47]`
//!   - statuidprint   `[c:132]`
//!   - statgidprint   `[c:161]`
//!   - stattimeprint  `[c:191]`
//!   - statulprint    `[c:211]`
//!   - statlinkprint  `[c:219]`
//!   - statprint      `[c:234]`
//!   - bin_stat       `[c:368]`
//!   - 6 module loaders

use crate::ported::exec::ShellExecutor;
use crate::ported::utils::zwarnnam;
use std::fs;
use std::os::unix::fs::MetadataExt;

// ============================================================
// Port of `enum statnum` from `Src/Modules/stat.c:33-35`.
// Anonymous integer constants for the per-element index passed
// to `statprint(..., iwhich, ...)`.
// ============================================================
/// Port of `HNAMEKEY` from `Src/Modules/stat.c:43`. Hash key the
/// `zstat -H` mode uses to store the file name in the result assoc.
pub const HNAMEKEY: &str = "name";                                       // c:43

/// Port of `statmodeprint(mode_t mode, char *outbuf, int flags)` from `Src/Modules/stat.c:47`. Renders
/// a Unix mode word per the STF_RAW / STF_OCTAL / STF_STRING flag
/// combination — raw octal/decimal, "ls -l"-style permission
/// string, or both with the raw form parenthesised.
///
/// C signature: `static void statmodeprint(mode_t mode, char *outbuf, int flags)`.
/// Rust port returns the formatted string (caller writes to its
/// own buffer) — same observable output for a given flag set.
/// WARNING: param names don't match C — Rust=(mode, flags) vs C=(mode, outbuf, flags)
pub fn statmodeprint(mode: u32, flags: i32) -> String {                  // c:47
    let mut out = String::new();
    if (flags & STF_RAW) != 0 {                                          // c:50
        if (flags & STF_OCTAL) != 0 {                                    // c:51
            out.push_str(&format!("0{:o}", mode));
        } else {
            out.push_str(&format!("{}", mode));
        }
        if (flags & STF_STRING) != 0 {                                   // c:53
            out.push_str(" (");                                          // c:54
        }
    }
    if (flags & STF_STRING) != 0 {                                       // c:56
        let modes = b"?rwxrwxrwx";
        let mut pm = [b'-'; 10];
        // c:84-103 — file-type char.
        let ifmt = mode & 0o170_000;                                     // S_IFMT
        pm[0] = match ifmt {
            0o020_000 => b'c',  // S_ISCHR
            0o040_000 => b'd',  // S_ISDIR
            0o060_000 => b'b',  // S_ISBLK
            0o100_000 => b'-',  // S_ISREG
            0o120_000 => b'l',  // S_ISLNK
            0o140_000 => b's',  // S_ISSOCK
            0o010_000 => b'p',  // S_ISFIFO
            _ => b'?',
        };
        // c:105-107 — owner/group/other rwx bits.
        let bits = [
            0o0400, 0o0200, 0o0100,
            0o0040, 0o0020, 0o0010,
            0o0004, 0o0002, 0o0001,
        ];
        for i in 0..9 {
            pm[i + 1] = if (mode & bits[i]) != 0 { modes[i + 1] } else { b'-' };
        }
        // c:111-115 — setuid / setgid / sticky.
        if (mode & 0o4000) != 0 {                                        // S_ISUID
            pm[3] = if (mode & 0o0100) != 0 { b's' } else { b'S' };
        }
        if (mode & 0o2000) != 0 {                                        // S_ISGID
            pm[6] = if (mode & 0o0010) != 0 { b's' } else { b'S' };
        }
        if (mode & 0o1000) != 0 {                                        // S_ISVTX
            pm[9] = if (mode & 0o0001) != 0 { b't' } else { b'T' };
        }
        out.push_str(std::str::from_utf8(&pm).unwrap_or(""));
        if (flags & STF_RAW) != 0 {                                      // c:132
            out.push(')');                                               // c:132
        }
    }
    out
}

/// Port of `statuidprint(uid_t uid, char *outbuf, int flags)` from `Src/Modules/stat.c:132`. Renders
/// a uid in raw form (decimal), string form (user name via
/// `getpwuid`), or both.
/// WARNING: param names don't match C — Rust=(uid, flags) vs C=(uid, outbuf, flags)
pub fn statuidprint(uid: u32, flags: i32) -> String {                    // c:132
    let mut out = String::new();
    if (flags & STF_RAW) != 0 {                                          // c:135
        out.push_str(&format!("{}", uid));
        if (flags & STF_STRING) != 0 {                                   // c:137
            out.push_str(" (");
        }
    }
    if (flags & STF_STRING) != 0 {                                       // c:140
        let name = unsafe {
            // c:142 — `pwd = getpwuid(uid);`
            let p = libc::getpwuid(uid);
            if p.is_null() { String::new() }
            else {
                let nm = (*p).pw_name;
                if nm.is_null() { String::new() }
                else { std::ffi::CStr::from_ptr(nm).to_string_lossy().into_owned() }
            }
        };
        if name.is_empty() {                                              // c:148 numeric fallback
            out.push_str(&format!("{}", uid));
        } else {
            out.push_str(&name);                                          // c:161 pwd->pw_name
        }
        if (flags & STF_RAW) != 0 {                                      // c:161
            out.push(')');
        }
    }
    out
}

/// Port of `statgidprint(gid_t gid, char *outbuf, int flags)` from `Src/Modules/stat.c:161`. Symmetric
/// with `statuidprint` for gid via `getgrgid`.
/// WARNING: param names don't match C — Rust=(gid, flags) vs C=(gid, outbuf, flags)
pub fn statgidprint(gid: u32, flags: i32) -> String {                    // c:161
    let mut out = String::new();
    if (flags & STF_RAW) != 0 {                                          // c:164
        out.push_str(&format!("{}", gid));
        if (flags & STF_STRING) != 0 {                                   // c:166
            out.push_str(" (");
        }
    }
    if (flags & STF_STRING) != 0 {                                       // c:169
        let name = unsafe {
            let g = libc::getgrgid(gid);                                  // c:171
            if g.is_null() { String::new() }
            else {
                let nm = (*g).gr_name;
                if nm.is_null() { String::new() }
                else { std::ffi::CStr::from_ptr(nm).to_string_lossy().into_owned() }
            }
        };
        if name.is_empty() {
            out.push_str(&format!("{}", gid));                           // c:184
        } else {
            out.push_str(&name);                                         // c:178
        }
        if (flags & STF_RAW) != 0 {                                      // c:191
            out.push(')');
        }
    }
    out
}

/// Port of `stattimeprint(time_t tim, long nsecs, char *outbuf, int flags)` from `Src/Modules/stat.c:191`. Renders
/// a Unix timestamp + nsec offset: raw form is integer seconds;
/// string form is `ctime(3)` (or strftime via the timefmt global).
/// WARNING: param names don't match C — Rust=(tim, _nsecs, flags) vs C=(tim, nsecs, outbuf, flags)
pub fn stattimeprint(tim: i64, _nsecs: i64, flags: i32) -> String {      // c:191
    let mut out = String::new();
    if (flags & STF_RAW) != 0 {                                          // c:194
        out.push_str(&format!("{}", tim));
        if (flags & STF_STRING) != 0 {                                   // c:196
            out.push_str(" (");
        }
    }
    if (flags & STF_STRING) != 0 {                                       // c:199
        // c:200 — `ztrftime(buf, ..., timefmt, localtime(&tim), nsecs);`
        let st = std::time::UNIX_EPOCH + std::time::Duration::from_secs(tim.max(0) as u64);
        let formatted = crate::ported::utils::ztrftime("%a %b %e %k:%M:%S %Z %Y", st);
        out.push_str(&formatted);
        if (flags & STF_RAW) != 0 {                                      // c:211
            out.push(')');
        }
    }
    out
}

/// Port of `statulprint(unsigned long num, char *outbuf)` from `Src/Modules/stat.c:211`. Renders an
/// unsigned-long stat field as decimal (always raw, no STF_STRING
/// branch).
/// WARNING: param names don't match C — Rust=(num) vs C=(num, outbuf)
pub fn statulprint(num: u64) -> String {                                 // c:211
    format!("{}", num)                                                    // c:219
}

/// Port of `statlinkprint(struct stat *sbuf, char *outbuf, char *fname)` from `Src/Modules/stat.c:219`. For
/// symlinks, renders the link target via `readlink(2)`; otherwise
/// returns empty.
/// WARNING: param names don't match C — Rust=(sbuf_mode, fname) vs C=(sbuf, outbuf, fname)
pub fn statlinkprint(sbuf_mode: u32, fname: &str) -> String {            // c:219
    if (sbuf_mode & 0o170_000) != 0o120_000 {                            // c:219 S_ISLNK
        return String::new();
    }
    fs::read_link(fname)                                                  // c:226 readlink
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// Port of `statprint(struct stat *sbuf, char *outbuf, char *fname, int iwhich, int flags)` from `Src/Modules/stat.c:234`. The unified
/// per-field dispatcher: given a stat metadata, file name, the
/// `iwhich` index from `STATELTS`, and a flag word, produce the
/// formatted value string.
///
/// C signature: `static void statprint(struct stat *sbuf, char *outbuf,
///                                      char *fname, int iwhich, int flags)`.
/// WARNING: param names don't match C — Rust=(meta, fname, iwhich, flags) vs C=(sbuf, outbuf, fname, iwhich, flags)
pub fn statprint(meta: &fs::Metadata, fname: &str, iwhich: i32, flags: i32) -> String {  // c:234
    // c:234-241 — `if (flags & STF_NAME)` prefix with `name<space>`.
    // `%-8s` left-justifies the name to 8 chars when not PICK/ARRAY,
    // `%s ` otherwise.
    let name_prefix = if (flags & STF_NAME) != 0 {
        let n = STATELTS.get(iwhich as usize).copied().unwrap_or("");
        if (flags & (STF_PICK | STF_ARRAY)) != 0 {
            format!("{} ", n)                                            // c:239
        } else {
            format!("{:<8}", n)                                          // c:240
        }
    } else {
        String::new()
    };
    let val = match iwhich {
        ST_DEV      => format!("{}", meta.dev()),                        // c:240
        ST_INO      => format!("{}", meta.ino()),                        // c:241
        ST_MODE     => statmodeprint(meta.mode(), flags),                // c:242
        ST_NLINK    => format!("{}", meta.nlink()),                      // c:243
        ST_UID      => statuidprint(meta.uid(), flags),                  // c:244
        ST_GID      => statgidprint(meta.gid(), flags),                  // c:245
        ST_RDEV     => format!("{}", meta.rdev()),                       // c:246
        ST_SIZE     => statulprint(meta.size()),                         // c:247
        ST_ATIM     => stattimeprint(meta.atime(), 0, flags),            // c:248
        ST_MTIM     => stattimeprint(meta.mtime(), 0, flags),            // c:249
        ST_CTIM     => stattimeprint(meta.ctime(), 0, flags),            // c:250
        ST_BLKSIZE  => statulprint(meta.blksize()),                      // c:251
        ST_BLOCKS   => statulprint(meta.blocks()),                       // c:252
        ST_READLINK => statlinkprint(meta.mode(), fname),                // c:253
        _ => String::new(),
    };
    format!("{}{}", name_prefix, val)
}

/// Port of `bin_stat(char *name, char **args, Options ops, UNUSED(int func))` from `Src/Modules/stat.c:368`. The `zstat`
/// builtin entry. Parses the `+ELEMENT` / `-flag` / `-A NAME` /
/// `-H NAME` / `-f FD` / `-F FORMAT` arg syntax, then calls
/// `lstat`/`stat`/`fstat` per file, dispatching `statprint` for
/// each requested element.
///
/// C signature: `static int bin_stat(char *name, char **args,
///                                    Options ops, int func)`.
/// WARNING: param names don't match C — Rust=(nam, args, _func) vs C=(name, args, ops, func)
pub fn bin_stat(nam: &str, args: &[String],                                  // c:368
                _ops_unused: &crate::ported::zsh_h::options, _func: i32) -> i32 {
    // c:370-374 — locals.
    let mut iwhich: i32 = -1;                                            // c:373
    let mut flags: i32 = 0;
    let mut found = 0i32;                                                // c:375
    let mut arrnam: Option<String> = None;
    let mut hashnam: Option<String> = None;
    let mut fd: i32 = 0;
    // The C `Options ops` bitmap is parsed inline by this fn (the
    // BUILTIN spec at c:637 is `NULL`, so the framework doesn't pre-
    // parse). Per PORT_CHECKLIST.md rule 3 we keep `ops` as a local
    // 256-entry bitmap rather than introducing a Rust-only struct.
    let mut ops = [false; 256];
    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    let mut argv: Vec<&str> = Vec::with_capacity(args.len());
    let mut i = 0;
    // c:381 — arg loop.
    while i < args.len() && (args[i].starts_with('+') || args[i].starts_with('-')) {
        let arg = &args[i][1..];
        if arg.is_empty() || arg.starts_with('-') || arg.starts_with('+') {
            i += 1;
            break;                                                       // c:386
        }
        if args[i].starts_with('+') {                                    // c:389
            if found != 0 { break; }
            for (idx, name) in STATELTS.iter().enumerate() {             // c:392
                if name.starts_with(arg) {
                    found += 1;
                    iwhich = idx as i32;
                }
            }
            if found > 1 {                                               // c:397
                zwarnnam(nam, &format!("{}: ambiguous stat element", arg));
                return 1;
            } else if found == 0 {                                       // c:400
                zwarnnam(nam, &format!("{}: no such stat element", arg));
                return 1;
            }
            // c:404 — `if (iwhich == ST_READLINK) ops->ind['L'] = 1;`
            if iwhich == ST_READLINK {
                ops[b'L' as usize] = true;
            }
            flags |= STF_PICK;                                           // c:406
        } else {                                                         // c:407 - flag arm
            for ch in arg.chars() {
                match ch {
                    'g' | 'l' | 'L' | 'n' | 'N' | 'o' | 'r' | 's' | 't' | 'T' => {
                        ops[ch as u8 as usize] = true;                   // c:411
                    }
                    'A' => {
                        // c:412 — array name follows.
                        i += 1;
                        if i >= args.len() {
                            zwarnnam(nam, "missing parameter name");
                            return 1;
                        }
                        arrnam = Some(args[i].to_string());
                        flags |= STF_ARRAY;
                        break;
                    }
                    'H' => {
                        i += 1;
                        if i >= args.len() {
                            zwarnnam(nam, "missing parameter name");
                            return 1;
                        }
                        hashnam = Some(args[i].to_string());
                        flags |= STF_HASH;
                        break;
                    }
                    'f' => {
                        ops[b'f' as usize] = true;
                        i += 1;
                        if i >= args.len() {
                            zwarnnam(nam, "missing file descriptor");
                            return 1;
                        }
                        let (val, endptr) = crate::ported::utils::zstrtol(args[i], 10);
                        if !endptr.is_empty() {
                            zwarnnam(nam, "bad file descriptor");
                            return 1;
                        }
                        fd = val as i32;
                        break;
                    }
                    'F' => {
                        i += 1;
                        if i >= args.len() {
                            zwarnnam(nam, "missing time format");
                            return 1;
                        }
                        // c:447 — force string format.
                        ops[b's' as usize] = true;
                        break;
                    }
                    _ => {
                        zwarnnam(nam, &format!("bad option: -{}", ch));
                        return 1;
                    }
                }
            }
        }
        i += 1;
    }
    while i < args.len() {
        argv.push(args[i]);
        i += 1;
    }
    let _ = fd;

    if (flags & STF_ARRAY) != 0 && (flags & STF_HASH) != 0 {             // c:459
        zwarnnam(nam, "both array and hash requested");
        return 1;
    }

    if ops[b'l' as usize] {                                              // c:467
        // List elements + return.
        if let Some(ref name) = arrnam {                                 // c:469
            // c:472 — `setaparam(arrnam, names);` — array of element names.
            let joined: Vec<&str> = STATELTS.iter().copied().collect();
            crate::ported::params::setsparam(name, &joined.join(":"));
        } else {
            let joined: Vec<&str> = STATELTS.iter().copied().collect();
            println!("{}", joined.join(" "));                            // c:478 putchar
        }
        return 0;                                                        // c:489
    }

    if argv.is_empty() && !ops[b'f' as usize] {                          // c:491
        zwarnnam(nam, "no files given");
        return 1;
    } else if !argv.is_empty() && ops[b'f' as usize] {                   // c:493
        zwarnnam(nam, "no files allowed with -f");
        return 1;
    }

    // c:496+ — per-file stat + dispatch loop.
    let use_lstat = ops[b'L' as usize];
    let mut hash_out: Vec<(String, String)> = Vec::new();
    let mut array_out: Vec<String> = Vec::new();
    let show_type = ops[b't' as usize];                                  // c: -t
    let mut local_flags = flags;
    // c:513 — `if (OPT_ISSET(ops,'s') || !OPT_ISSET(ops,'r'))` STF_STRING.
    if ops[b's' as usize] { local_flags |= STF_STRING; }                  // c:514
    // c:516 — `if (OPT_ISSET(ops,'r') || !OPT_ISSET(ops,'s'))` STF_RAW.
    if ops[b'r' as usize] || !ops[b's' as usize] {                        // c:516
        local_flags |= STF_RAW;
    }
    // c:518-519 — `-n` → STF_FILE (filename prefix).
    if ops[b'n' as usize] { local_flags |= STF_FILE; }                    // c:519
    // c:520-521 — `-o` → STF_OCTAL.
    if ops[b'o' as usize] { local_flags |= STF_OCTAL; }                   // c:521
    // c:522-523 — `-t` → STF_NAME explicit.
    if ops[b't' as usize] { local_flags |= STF_NAME; }                    // c:523
    // c:525-530 — default STF_NAME when neither -A nor -H and no
    // single-element pick: every line gets a `name<sp>` prefix so
    // `zstat /etc/hosts` looks like `mode    33188` etc.
    if arrnam.is_none() && hashnam.is_none() {
        if argv.len() > 1 { local_flags |= STF_FILE; }                    // c:527
        if (local_flags & STF_PICK) == 0 {                                // c:528
            local_flags |= STF_NAME;                                      // c:529
        }
    }
    // c:532-535 — explicit -N / -f turn off STF_FILE; -T / -H turn off
    // STF_NAME (suppress prefix for `read` / hash use).
    if ops[b'N' as usize] || ops[b'f' as usize] {                         // c:532
        local_flags &= !STF_FILE;
    }
    if ops[b'T' as usize] || ops[b'H' as usize] {                         // c:534
        local_flags &= !STF_NAME;
    }
    let _ = show_type;

    for path in &argv {
        let meta = if use_lstat {
            fs::symlink_metadata(path)
        } else {
            fs::metadata(path)
        };
        let meta = match meta {
            Ok(m) => m,
            Err(e) => {
                zwarnnam(nam, &format!("{}: {}", path, e));
                continue;
            }
        };

        // c:573-581 — `STF_FILE` prefix the filename per file.
        if (local_flags & STF_FILE) != 0 && arrnam.is_none() && hashnam.is_none() {
            if (local_flags & STF_PICK) != 0 {
                print!("{} ", path);                                     // c:580
            } else {
                println!("{}:", path);
            }
        }
        if iwhich >= 0 {
            // -E single element.
            let val = statprint(&meta, path, iwhich, local_flags);
            if let Some(ref aname) = arrnam {
                array_out.push(val);
                let _ = aname;
            } else if let Some(ref hname) = hashnam {
                hash_out.push((STATELTS[iwhich as usize].to_string(), val));
                let _ = hname;
            } else {
                println!("{}", val);                                     // c:591
            }
        } else {
            // All elements.
            for idx in 0..STATELTS.len() {
                let val = statprint(&meta, path, idx as i32, local_flags);
                if let Some(_) = &arrnam {
                    array_out.push(val);
                } else if let Some(_) = &hashnam {
                    hash_out.push((STATELTS[idx].to_string(), val));
                } else {
                    println!("{}", val);                                 // c:603
                }
            }
        }
    }

    if let Some(name) = arrnam {                                         // c:setaparam
        // c — `setaparam(name, zarrdup(array_out));` — real indexed array.
        crate::ported::params::setaparam(&name, array_out);              // c:params.c:3595
    }
    if let Some(name) = hashnam {                                        // c:sethparam
        // c — `sethparam(name, ...);` — real assoc array. Flatten
        // hash_out into alternating [k,v,k,v,...].
        let mut flat: Vec<String> = Vec::with_capacity(hash_out.len() * 2);
        for (k, v) in hash_out {
            flat.push(k);
            flat.push(v);
        }
        crate::ported::params::sethparam(&name, flat);                   // c:params.c:3602
    }
    0
}

// `bintab` — port of `static struct builtin bintab[]` (stat.c:638).


// `module_features` — port of `static struct features module_features`
// from stat.c:642.



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

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

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

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/stat.c:673`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {                                     // c:673
    // C body c:675-676 — `return 0`. Faithful empty-body port; the
    //                    zstat builtin registers via the bn_list dispatch.
    0
}

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

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/stat.c:687`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {                                   // c:687
    // C body c:689-690 — `return 0`. Faithful empty-body port; the
    //                    zstat builtin unregisters via cleanup_'s setfeatureenables.
    0
}

pub const ST_DEV:      i32 = 0;                                          // c:33
pub const ST_INO:      i32 = 1;
pub const ST_MODE:     i32 = 2;
pub const ST_NLINK:    i32 = 3;
pub const ST_UID:      i32 = 4;
pub const ST_GID:      i32 = 5;
pub const ST_RDEV:     i32 = 6;
pub const ST_SIZE:     i32 = 7;
pub const ST_ATIM:     i32 = 8;
pub const ST_MTIM:     i32 = 9;
pub const ST_CTIM:     i32 = 10;
pub const ST_BLKSIZE:  i32 = 11;
pub const ST_BLOCKS:   i32 = 12;
pub const ST_READLINK: i32 = 13;
pub const ST_COUNT:    i32 = 14;                                         // c:34

// ============================================================
// Port of `enum statflags` from `Src/Modules/stat.c:36-38`.
// Bitmask flags passed to the print fns + bin_stat dispatch.
// ============================================================
pub const STF_NAME:   i32 = 1;                                           // c:36
pub const STF_FILE:   i32 = 2;
pub const STF_STRING: i32 = 4;
pub const STF_RAW:    i32 = 8;

// =====================================================================
// static struct builtin bintab[]                                    c:638
// static struct features module_features                            c:642
// =====================================================================

use crate::ported::zsh_h::module;
pub const STF_PICK:   i32 = 16;
pub const STF_ARRAY:  i32 = 32;
pub const STF_GMT:    i32 = 64;
pub const STF_HASH:   i32 = 128;
pub const STF_OCTAL:  i32 = 256;                                         // c:38

/// Port of `statelts[]` from `Src/Modules/stat.c:39`. Names of the
/// 14 stat-elements, indexed by the `ST_*` constants above.
pub static STATELTS: &[&str] = &[                                        // c:39
    "device", "inode", "mode", "nlink",
    "uid", "gid", "rdev", "size", "atime",
    "mtime", "ctime", "blksize", "blocks",
    "link",
];



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

static MODULE_FEATURES: OnceLock<Mutex<features_t>> = 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 STAT.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!["b:stat".to_string(), "b:zstat".to_string()]
}

// WARNING: NOT IN STAT.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 STAT.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
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor fns 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 fns sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port fns.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor fns 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 fns sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port fns.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// WARNING: NOT IN STAT.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: 2,
        cd_list: None,
        cd_size: 0,
        mf_list: None,
        mf_size: 0,
        pd_list: None,
        pd_size: 0,
        n_abstract: 0,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;

    #[test]
    fn statelts_count_matches_st_count() {
        assert_eq!(STATELTS.len() as i32, ST_COUNT);
    }

    #[test]
    fn statmodeprint_octal_only() {
        let s = statmodeprint(0o100644, STF_RAW | STF_OCTAL);
        assert!(s.starts_with('0'));
        assert!(s.contains("644"));
    }

    #[test]
    fn statmodeprint_string_only() {
        let s = statmodeprint(0o100644, STF_STRING);
        assert_eq!(s.len(), 10);
        assert_eq!(&s[..1], "-");
    }

    #[test]
    fn statmodeprint_directory() {
        let s = statmodeprint(0o040755, STF_STRING);
        assert_eq!(&s[..1], "d");
    }

    #[test]
    fn statulprint_decimal() {
        assert_eq!(statulprint(12345), "12345");
    }

    #[test]
    fn statprint_size_via_index() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("x.txt");
        File::create(&path).unwrap().write_all(b"hello").unwrap();
        let meta = fs::metadata(&path).unwrap();
        let s = statprint(&meta, path.to_str().unwrap(), ST_SIZE, 0);
        assert_eq!(s, "5");
    }

    /// c:47 — `statmodeprint` for the BLOCK device file type. The
    /// `pm[0]` lookup at c:84-103 must yield 'b'. Pin all file-type
    /// chars so a regen that swaps `0o060_000` and `0o020_000`
    /// silently renders block devices as char devices.
    #[test]
    fn statmodeprint_file_type_chars_match_ls_output() {
        // S_IFREG (regular file)
        assert_eq!(&statmodeprint(0o100_644, STF_STRING)[..1], "-");
        // S_IFDIR
        assert_eq!(&statmodeprint(0o040_755, STF_STRING)[..1], "d");
        // S_IFLNK (symlink)
        assert_eq!(&statmodeprint(0o120_777, STF_STRING)[..1], "l");
        // S_IFCHR (char device)
        assert_eq!(&statmodeprint(0o020_644, STF_STRING)[..1], "c");
        // S_IFBLK (block device)
        assert_eq!(&statmodeprint(0o060_644, STF_STRING)[..1], "b");
        // S_IFIFO (named pipe)
        assert_eq!(&statmodeprint(0o010_644, STF_STRING)[..1], "p");
        // S_IFSOCK
        assert_eq!(&statmodeprint(0o140_644, STF_STRING)[..1], "s");
    }

    /// c:111-115 — setuid bit renders as 's' in the user-execute
    /// slot when execute is set, 'S' when not. Pin both polarities
    /// for setuid, setgid, and sticky so a regen flipping the
    /// uppercase/lowercase dispatch gets caught.
    #[test]
    fn statmodeprint_setuid_setgid_sticky_render_correctly() {
        // 4755 = setuid + executable → 's' in user slot
        let s = statmodeprint(0o104_755, STF_STRING);
        assert_eq!(s.chars().nth(3), Some('s'),
            "setuid+x must render as 's' in user-execute slot");

        // 4644 = setuid + NOT executable → 'S' in user slot
        let s = statmodeprint(0o104_644, STF_STRING);
        assert_eq!(s.chars().nth(3), Some('S'),
            "setuid without x must render as 'S' (uppercase)");

        // 2755 = setgid + group-x → 's' in group-execute slot
        let s = statmodeprint(0o102_755, STF_STRING);
        assert_eq!(s.chars().nth(6), Some('s'),
            "setgid+gx must render as 's' in group-execute slot");

        // 2644 = setgid without group-x → 'S'
        let s = statmodeprint(0o102_644, STF_STRING);
        assert_eq!(s.chars().nth(6), Some('S'),
            "setgid without gx must render as 'S'");

        // 1755 = sticky + world-x → 't' in other-execute slot
        let s = statmodeprint(0o101_755, STF_STRING);
        assert_eq!(s.chars().nth(9), Some('t'),
            "sticky+ox must render as 't' in other-execute slot");

        // 1644 = sticky without world-x → 'T'
        let s = statmodeprint(0o101_644, STF_STRING);
        assert_eq!(s.chars().nth(9), Some('T'),
            "sticky without ox must render as 'T'");
    }

    /// c:47-93 — `STF_RAW | STF_STRING` produces "raw (string)" with
    /// the raw form OUTSIDE parens and the string form inside.
    /// Pin the format because user scripts grep for "^(0?[0-9]+) \("
    /// to split the two halves.
    #[test]
    fn statmodeprint_raw_and_string_renders_with_parens() {
        let s = statmodeprint(0o100_644, STF_RAW | STF_STRING);
        // Decimal raw form, space, paren, 10-char string, close paren
        assert!(s.contains(" ("), "missing ' (' separator: {}", s);
        assert!(s.ends_with(')'), "missing closing ')': {}", s);
        // The closing paren must come right after the 10-char ls form
        let open = s.find('(').unwrap();
        let close = s.rfind(')').unwrap();
        assert_eq!(close - open - 1, 10,
            "expected 10-char ls-mode between parens, got: {:?}", &s[open+1..close]);
    }

    /// c:47-93 — `statmodeprint(0)` with STF_STRING renders all dashes
    /// after the file-type indicator. Edge case: zero permissions on
    /// a "no file-type" mode falls through to '?'.
    #[test]
    fn statmodeprint_zero_mode_renders_unknown_type_no_perms() {
        let s = statmodeprint(0, STF_STRING);
        assert_eq!(s.len(), 10);
        assert_eq!(&s[..1], "?", "mode with no S_IFMT bits → unknown");
        assert_eq!(&s[1..], "---------",
            "no permission bits → all dashes");
    }

    /// c:132 — `statuidprint` raw form is just the decimal uid;
    /// pin the no-leading-zeros, no-prefix shape so a regen that
    /// renders octal silently breaks `${(t)f[uid]}`.
    #[test]
    fn statuidprint_raw_is_decimal() {
        let s = statuidprint(1000, STF_RAW);
        assert_eq!(s, "1000");
    }

    /// c:132 — `statuidprint` for uid 0 must include "root" in the
    /// string form (every Unix has uid 0 = root). Pin the well-known
    /// case so a regen that breaks the getpwuid path doesn't silently
    /// fall back to numeric.
    #[test]
    fn statuidprint_uid_zero_resolves_to_root() {
        let s = statuidprint(0, STF_STRING);
        // Some hardened systems map uid 0 to a different name, but
        // it MUST resolve to non-numeric.
        assert!(!s.parse::<u32>().is_ok(),
            "uid 0 fell back to numeric form: {}", s);
        assert!(!s.is_empty());
    }

    /// c:161 — `statgidprint` raw form is decimal.
    #[test]
    fn statgidprint_raw_is_decimal() {
        let s = statgidprint(100, STF_RAW);
        assert_eq!(s, "100");
    }

    /// c:211 — `statulprint` for zero must render "0". A regression
    /// that prints "" or "0x0" silently breaks numeric script
    /// comparisons.
    #[test]
    fn statulprint_zero_renders_as_zero_digit() {
        assert_eq!(statulprint(0), "0");
    }

    /// c:211 — `statulprint` for u64::MAX renders the full decimal
    /// digit string. Pin the no-overflow / no-truncation behavior.
    #[test]
    fn statulprint_u64_max_renders_full_digits() {
        let s = statulprint(u64::MAX);
        assert_eq!(s, "18446744073709551615");
    }

    /// c:36-38 — STF_* flag values must each occupy a unique single
    /// bit, AND must not overlap with each other (so they can be
    /// OR'd together). Pin the bit-distinctness because the flags
    /// are AND-tested individually throughout statprint.
    #[test]
    fn stf_flag_values_are_distinct_single_bits() {
        for f in [STF_NAME, STF_FILE, STF_STRING, STF_RAW,
                  STF_PICK, STF_ARRAY, STF_GMT, STF_HASH, STF_OCTAL] {
            assert!(f > 0, "STF_* flag {} must be positive", f);
            assert_eq!((f as u32).count_ones(), 1,
                "STF_* flag {} = 0b{:b} must be a single bit",
                f, f);
        }
        // Pairwise: no two flags share a bit
        let flags = [STF_NAME, STF_FILE, STF_STRING, STF_RAW,
                     STF_PICK, STF_ARRAY, STF_GMT, STF_HASH, STF_OCTAL];
        for (i, &a) in flags.iter().enumerate() {
            for &b in &flags[i+1..] {
                assert_eq!(a & b, 0,
                    "STF flags {} and {} overlap", a, b);
            }
        }
    }

    /// c:651-690 — module-lifecycle stubs all return 0 in C.
    #[test]
    fn module_lifecycle_shims_all_return_zero() {
        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);
    }
}