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
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
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
//! Input buffering and stack management for zshrs
//!
//! Direct port from zsh/Src/input.c
//!
//! the shell input fd                                                       // c:78
//! total # of characters waiting to be read                                 // c:88
//! the flags controlling the input routines in input.c                      // c:93
//! Reset the input buffer for SHIN, discarding any pending input            // c:155
//! stuff a whole file into memory and return it                             // c:610
//! flush input queue                                                        // c:661
//!
//! This module handles:
//! - Reading input from files, strings, and the line editor
//! - Input stack for alias expansion and history substitution
//! - Character-by-character input with push-back support
//! - Meta-character encoding for internal tokens

use std::cell::RefCell;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader, Read, Write, self};
use crate::ported::zsh_h::{
    INP_ALCONT, INP_ALIAS, INP_CONT, INP_FREE, INP_HIST, INP_HISTCONT, INP_LINENO, INP_RAW_KEEP, Meta
};


/// Port of `struct instacks` from `Src/input.c:109`. One frame in
/// the input stack — pushed by `inpush()` and popped by `inpoptop()`
/// to layer alias expansion / history-substitution / `eval`
/// continuations over the active input.
#[derive(Clone, Default)]
#[allow(non_camel_case_types)]
struct instacks {
    // c:109
    buf: String,           // c:110 char *buf
    bufpos: usize,         // c:110 char *bufptr offset
    flags: i32,            // c:112 int flags
    alias: Option<String>, // c:111 Alias alias
}

/// Initial input stack size
#[allow(dead_code)]
const INSTACK_INITIAL: usize = 4; // c:122

// `pub mod flags { … INP_* … }` deleted — Rust-only namespace with
// values that diverged from the C `#define INP_FREE (1<<0)` etc. at
// Src/zsh.h:467-476. The canonical mirror lives in
// `crate::ported::zsh_h::INP_*` (matching the C bit positions
// exactly); this file uses those constants directly.

// ---------------------------------------------------------------------------
// SHIN buffer helpers — direct ports of input.c:159/171/181/200/218/267.
// ---------------------------------------------------------------------------

/// Reset the SHIN pushback buffer.
/// Port of `shinbufreset()` from Src/input.c:159 —
/// `shinbufendptr = shinbufptr = shinbuffer`.
pub fn shinbufreset() {
    // c:159
    shinbuffer.with(|b| b.borrow_mut().clear());
    shinbufpos.with(|p| p.set(0));
}

// ---------------------------------------------------------------------------
// File-scope mirrors of `Src/input.c` globals. Per-thread because each
// worker parses independently; the C source's process-global model
// doesn't translate directly to zshrs's parallel pipeline.
// ---------------------------------------------------------------------------

thread_local! {
    /// Port of `int SHIN` from `Src/input.c:81`. Shell input fd
    /// (typically 0 for stdin).
    #[allow(non_upper_case_globals)]
    pub static SHIN: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };

    /// Port of `int strin` from `Src/input.c:86`. Non-zero while
    /// reading from a string (via `inpush` with INP_ALIAS/INP_HIST
    /// or by `bin_eval`); short-circuits `read(2)` fallback.
    #[allow(non_upper_case_globals)]
    pub static strin: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };

    /// Port of `mod_export int inbufct` from `Src/input.c:91`.
    /// Total characters waiting to be read across `inbuf` +
    /// `instack` entries.
    #[allow(non_upper_case_globals)]
    pub static inbufct: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };

    /// Port of `int inbufflags` from `Src/input.c:96`. Bit-mask of
    /// the `INP_*` flags governing the current input level.
    #[allow(non_upper_case_globals)]
    pub static inbufflags: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };

    /// Port of `static char *inbuf` from `Src/input.c:98`. Current
    /// input buffer.
    #[allow(non_upper_case_globals)]
    static inbuf: RefCell<String> = const { RefCell::new(String::new()) };

    /// Port of `static char *inbufptr` from `Src/input.c:99`. Offset
    /// into `inbuf` where the next char will be read.
    #[allow(non_upper_case_globals)]
    static inbufpos: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };

    /// Input stack — port of `static struct instacks *instack` from
    /// `Src/input.c:114`. The instacktop pointer in C maps to the
    /// Vec's length here.
    static instack: RefCell<Vec<instacks>> = const { RefCell::new(Vec::new()) };

    /// `lexstop` — set when the lexer should stop pulling chars.
    /// C mirrors this in zsh.h as an extern; per-thread here.
    #[allow(non_upper_case_globals)]
    pub static lexstop: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };

    /// Current line number for diagnostics. C `lineno` global.
    #[allow(non_upper_case_globals)]
    pub static lineno: std::cell::Cell<usize> = const { std::cell::Cell::new(1) };

    /// SHIN read buffer — C `shinbuffer`.
    #[allow(non_upper_case_globals)]
    static shinbuffer: RefCell<String> = const { RefCell::new(String::new()) };

    /// SHIN read offset — C `shinbufptr`.
    #[allow(non_upper_case_globals)]
    static shinbufpos: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };

    /// SHIN save stack — C `shinsavestack`.
    static shinsavestack: RefCell<Vec<(String, usize)>> = const { RefCell::new(Vec::new()) };

    /// Pushback queue for `inungetc`. zshrs-specific; C inlines a
    /// single inbufptr-decrement which can't model arbitrary-length
    /// pushback from a different buffer.
    static pushback: RefCell<VecDeque<char>> = const { RefCell::new(VecDeque::new()) };

    /// Raw-input accumulator for history. zshrs-specific.
    static raw_input: RefCell<String> = const { RefCell::new(String::new()) };
}

/// Allocate a fresh SHIN buffer.
/// Port of `shinbufalloc()` from Src/input.c:171.
pub fn shinbufalloc() {
    // c:171
    shinbuffer.with(|b| {
        *b.borrow_mut() = String::with_capacity(SHIN_BUF_SIZE);
    });
    shinbufreset();
}

/// Save the current SHIN buffer onto the save stack.
/// Port of `shinbufsave()` from Src/input.c:181 — push the
/// existing buffer onto a save-stack and start a fresh one for
/// nested `eval`/`source` contexts.
pub fn shinbufsave() {
    // c:181
    let (snap_buf, snap_pos) = (
        shinbuffer.with(|b| std::mem::take(&mut *b.borrow_mut())),
        shinbufpos.with(|p| p.replace(0)),
    );
    shinsavestack.with(|s| s.borrow_mut().push((snap_buf, snap_pos)));
    shinbufalloc();
}

/// Pop the top of the SHIN save stack back into the live buffer.
/// Port of `shinbufrestore()` from Src/input.c:200.
pub fn shinbufrestore() {
    // c:200
    if let Some((buf, pos)) = shinsavestack.with(|s| s.borrow_mut().pop()) {
        shinbuffer.with(|b| *b.borrow_mut() = buf);
        shinbufpos.with(|p| p.set(pos));
    }
}

// Get a character from SHIN, -1 if none available                           // c:218
/// Read one byte from SHIN; returns -1 on EOF.
/// Port of `shingetchar()` from Src/input.c:218. C source pulls
/// from `shinbuffer` first then falls through to `read(2)` on the
/// SHIN fd; Rust mirrors by reading from `std::io::stdin`.
pub fn shingetchar() -> i32 {
    // c:218
    // c:218-228 — `if (shinbufptr < shinbufendptr) return *shinbufptr++;`
    let bufd = shinbuffer.with(|b| b.borrow().clone());
    let pos = shinbufpos.with(|p| p.get());
    if pos < bufd.len() {
        if let Some(ch) = bufd.chars().nth(pos) {
            shinbufpos.with(|p| p.set(pos + 1));
            return ch as i32;
        }
    }
    // c:230-258 — refill via `read(SHIN, ...)`.
    shinbufreset();
    let stdin = std::io::stdin();
    let mut reader = BufReader::new(stdin.lock());
    let mut line = String::new();
    match reader.read_line(&mut line) {
        Ok(0) => -1,
        Ok(_) => {
            let first = line.chars().next().map(|c| c as i32).unwrap_or(-1);
            shinbuffer.with(|b| *b.borrow_mut() = line);
            shinbufpos.with(|p| p.set(1));
            first
        }
        Err(_) => -1,
    }
}

/// Read a full line from SHIN, with `\n` preserved.
/// Port of `shingetline()` from Src/input.c:267 — calls
/// `shingetchar` in a loop, metafies high bytes, returns NULL
/// (`""`) on EOF.
pub fn shingetline() -> String {
    // c:267
    let mut result = String::new();
    loop {
        match shingetchar() {
            -1 => return result,
            ch_i32 => {
                let c = char::from_u32(ch_i32 as u32).unwrap_or('\0');
                if c == '\n' {
                    result.push('\n');
                    return result;
                }
                if imeta(c) {
                    // Inline metafy XOR per Src/utils.c:4856 metafy()
                    // and Src/zsh.h Meta protocol — c ^ 32 maps the
                    // 5 reserved bytes (0x00, 0x83-0x9b) to printable
                    // form for the SHIN buffer.
                    result.push(Meta as char);
                    result.push(char::from_u32((c as u32) ^ 32).unwrap_or(c));
                } else {
                    result.push(c);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// ingetc / inungetc / inpush / inpop / inpopalias — Src/input.c:318+/546/675/785/804.
// ---------------------------------------------------------------------------

/// Get the next char from the active input source.
/// Port of `ingetc()` from Src/input.c:318 — drives the
/// lexer; consumes pushback first, then top-of-stack input.
pub fn ingetc() -> Option<char> {
    // c:318
    // c:Src/input.c:322 — `if (lexstop) return ' ';`. The C source
    // returns the literal byte 32. The Rust port wraps the result
    // in Option<char> where None is the canonical EOF marker (callers
    // map None → -1 at hist.rs:392). Returning Some(' ') from this
    // guard treated EOF as a real space byte downstream and broke
    // every "drain past end" caller; consistent EOF means None for
    // every post-lexstop call, matching the function's already-emitted
    // None when buffer drains at line 293.
    if lexstop.with(|c| c.get()) {
        return None; // c:322 (mapped to Rust None EOF marker)
    }

    if let Some(c) = pushback.with(|p| p.borrow_mut().pop_front()) {
        raw_input.with(|r| r.borrow_mut().push(c));
        return Some(c);
    }

    loop {
        let pos = inbufpos.with(|p| p.get());
        let buf = inbuf.with(|b| b.borrow().clone());
        if pos < buf.len() {
            let c = buf.chars().nth(pos)?;
            inbufpos.with(|p| p.set(pos + 1));
            inbufct.with(|c| c.set(c.get().saturating_sub(1)));

            // c:328 — `if (itok(lastc = (unsigned char) *inbufptr++)) continue;`
            // Skip internal tokens via the canonical `itok()` predicate
            // (`Src/ztype.h:52`), which tests bit `ITOK` in `typtab[c]`.
            // Per `Src/utils.c:4198-4201` `inittyptab` sets ITOK on
            // `Pound..LAST_NORMAL_TOK (0x84..0x9c)` AND `Snull..Nularg
            // (0x9d..0xa1)` — canonical token range is `0x84..=0xa1`.
            // The previous hardcoded range `0x83..=0x9b` was both too
            // inclusive (included 0x83 = Meta lead byte, IMETA-only) and
            // too narrow (excluded 0x9c..=0xa1 = Bang/Snull/Dnull/Bnull/
            // Bnullkeep/Nularg). Marker (0xa2) is intentionally NOT in
            // either set — it's IMETA-only per `c:4197`. Routing through
            // `itok()` lets future `inittyptab` adjustments propagate
            // automatically with zero changes here.
            let cu32 = c as u32;
            if cu32 < 256 && crate::ported::ztype_h::itok(cu32 as u8) {
                continue;
            }

            let inp_lineno = (inbufflags.with(|f| f.get()) & INP_LINENO) != 0;
            let is_strin = strin.with(|s| s.get()) != 0;
            if (inp_lineno || !is_strin) && c == '\n' {
                lineno.with(|l| l.set(l.get() + 1));
            }
            raw_input.with(|r| r.borrow_mut().push(c));
            return Some(c);
        }

        // End of current buffer.
        let ct = inbufct.with(|c| c.get());
        let is_strin = strin.with(|s| s.get()) != 0;
        let is_stop = lexstop.with(|c| c.get());
        if ct == 0 && (is_strin || is_stop) {
            lexstop.with(|c| c.set(true));
            return None;
        }

        if (inbufflags.with(|f| f.get()) & INP_CONT) != 0 {
            inpoptop();
            continue;
        }

        lexstop.with(|c| c.set(true));
        return None;
    }
}

// Read a line from the current command stream and store it as input         // c:366
/// Read one line into the input stack.
/// Port of `inputline()` from Src/input.c:366. C source dispatches
/// between zle / non-zle paths and `shingetline` /
/// `zleentry(READ)`. Rust port reads via shingetline (no zle yet),
/// returns "" on EOF and sets lexstop the same way.
pub fn inputline() -> String {
    // c:366
    let line = shingetline();
    if line.is_empty() {
        lexstop.with(|c| c.set(true));
    }
    line
}

/// Replace the current input line.
/// Port of `inputsetline(char *str, int flags)` from Src/input.c:510.
pub fn inputsetline(str: &str, flags: i32) {
    // c:510
    inbuf.with(|b| *b.borrow_mut() = str.to_string());
    inbufpos.with(|p| p.set(0));
    let len = str.len() as i32;
    if (flags & INP_CONT) != 0 {
        inbufct.with(|c| c.set(c.get() + len));
    } else {
        inbufct.with(|c| c.set(len));
    }
    inbufflags.with(|f| f.set(flags));
    // c:Src/input.c — inputsetline is the "fresh input arrives" entry
    // point. In C, ingetc's lexstop guard is reset by every grammar-
    // boundary call (zshlex/getfirsttok/zshlex_raw_back at lex.c:455,
    // 519, etc.) BEFORE the next ingetc fires. zshrs has no such
    // reset surface yet, so a previously-drained buffer leaves
    // lexstop=true and the new content is unreadable. Reset here so
    // the contract "inputsetline(s) makes s readable" holds.
    lexstop.with(|c| c.set(false));
}

/// Push a character back onto the input stream.
/// Port of `inungetc(int c)` from Src/input.c:546.
pub fn inungetc(c: char) {
    // c:546
    if lexstop.with(|c| c.get()) {
        return;
    }
    let pos = inbufpos.with(|p| p.get());
    if pos > 0 {
        inbufpos.with(|p| p.set(pos - 1));
        inbufct.with(|cell| cell.set(cell.get() + 1));
        let inp_lineno = (inbufflags.with(|f| f.get()) & INP_LINENO) != 0;
        let is_strin = strin.with(|s| s.get()) != 0;
        if (inp_lineno || !is_strin) && c == '\n' {
            lineno.with(|l| l.set(l.get().saturating_sub(1)));
        }
        raw_input.with(|r| {
            r.borrow_mut().pop();
        });
    } else {
        pushback.with(|p| p.borrow_mut().push_front(c));
    }
}

/// Read entire file into memory.
/// Port of `mod_export off_t zstuff(char **out, const char *fn)`
/// from Src/input.c:614. C body opens via `unmeta(fn)`, fseeks to
/// end for size, fread()s the body, queues signals around the IO,
/// zerr()s on open/read failures, returns byte count or -1.
///
/// Rust signature: `(path: &str) -> Result<(String, i64), i32>`
/// — Ok((contents, byte_count)) or Err(-1) on open/read fail.
/// Path is unmetafied to match C's `unmeta(fn)` step before open.
/// WARNING: param names don't match C — Rust=(path) vs C=(out, fn).
pub fn zstuff(path: &str) -> Result<(String, i64), i32> {
    // c:614
    use std::io::Read;
    // c:621 — `unmeta(fn)`: de-metafy the path before open(2).
    let mut path_bytes = path.as_bytes().to_vec();
    crate::ported::utils::unmetafy(&mut path_bytes);
    let real_path = String::from_utf8_lossy(&path_bytes);
    // c:621 — `fopen(unmeta(fn), "r")`. Rust File::open mirrors fopen
    // with read-only mode; failure path zerrs and returns -1.
    let mut file = match std::fs::File::open(real_path.as_ref()) {
        // c:621
        Ok(f) => f,
        Err(_) => {
            // c:622
            crate::ported::utils::zerr(&format!("can't open {}", path)); // c:622
            return Err(-1); // c:623
        }
    };
    // c:625 — `queue_signals();` block syscalls from the trap fast path
    // for the duration of the read.
    crate::ported::signals_h::queue_signals();
    // c:626-628 — `fseek(end); ftell; fseek(start);` to size the file
    // without consuming the stream. Use stream metadata in Rust.
    let len = match file.metadata() {
        // c:627
        Ok(m) => m.len() as i64,
        Err(_) => 0,
    };
    let mut buf = String::new(); // c:629 — `buf = zalloc(len + 1);`
    // c:630-635 — `fread(buf, len, 1, in)` failure arm zerrs read error.
    if file.read_to_string(&mut buf).is_err() {
        // c:630
        crate::ported::utils::zerr(&format!("read error on {}", path)); // c:631
        crate::ported::signals_h::unqueue_signals(); // c:633
        return Err(-1); // c:634
    }
    crate::ported::signals_h::unqueue_signals(); // c:640
    Ok((buf, len)) // c:642
}

// `input_has_alias` / `take_raw_input` deleted — Rust-only helpers
// with zero callers in this tree. C uses different mechanisms
// (the lexer walks `instack` inline for alias detection; raw input
// for history accumulates through `chline` / `addtoline`).

/// Stuff a whole file into the input queue.
/// Port of `stuff(char *fn)` from Src/input.c:647 — read the file, echo
/// it to stderr, push onto the input stack.
/// WARNING: param names don't match C — Rust=(filename) vs C=(fn)
pub fn stuff(filename: &str) -> i32 {
    // c:647
    let buf = match std::fs::read_to_string(filename) {
        Ok(b) => b,
        Err(_) => return 1,
    };
    let _ = std::io::stderr().write_all(buf.as_bytes());
    let _ = std::io::stderr().flush();
    inpush(&buf, INP_FREE, None);
    0
}

/// Discard pending input after a parse error.
/// Port of `inerrflush()` from Src/input.c:665.
pub fn inerrflush() {
    // c:665
    while !lexstop.with(|c| c.get()) && inbufct.with(|c| c.get()) > 0 {
        let _ = ingetc();
    }
}

// Set some new input onto a new element of the input stack                  // c:675
/// Push a new input source onto the stack.
/// Port of `inpush(char *str, int flags, Alias inalias)` from Src/input.c:675 — used for `eval`/
/// `source`, alias expansion, and process substitution to layer a
/// new input on top of the current one.
pub fn inpush(str: &str, flags: i32, inalias: Option<String>) {
    // c:675
    let saved = instacks {
        buf: inbuf.with(|b| std::mem::take(&mut *b.borrow_mut())),
        bufpos: inbufpos.with(|p| p.replace(0)),
        flags: inbufflags.with(|f| f.get()),
        alias: None,
    };
    instack.with(|st| st.borrow_mut().push(saved));

    inbuf.with(|b| *b.borrow_mut() = str.to_string());
    inbufpos.with(|p| p.set(0));

    let mut combined = flags;
    if (flags & (INP_ALIAS | INP_HIST)) != 0 {
        combined |= INP_CONT | INP_ALIAS;
        if let Some(a) = inalias {
            instack.with(|st| {
                if let Some(last) = st.borrow_mut().last_mut() {
                    last.alias = Some(a);
                    if (flags & INP_HIST) != 0 {
                        last.flags |= INP_HISTCONT;
                    } else {
                        last.flags |= INP_ALCONT;
                    }
                }
            });
        }
    }

    let new_len = inbuf.with(|b| b.borrow().len()) as i32;
    if (combined & INP_CONT) != 0 {
        inbufct.with(|c| c.set(c.get() + new_len));
    } else {
        inbufct.with(|c| c.set(new_len));
    }
    inbufflags.with(|f| f.set(combined));
    // c:Src/input.c — same lexstop reset as inputsetline (input.rs:336).
    // Without this, an inpush after the buffer drained leaves lexstop=true
    // and ingetc returns None immediately, so the just-pushed alias body
    // (e.g. `inpush("echo hello")` after lexing `hi`) never gets read.
    // Symptom: `alias hi='echo hello'; eval hi` → empty output, because
    // eval's inner `hi` token drained the buffer, set lexstop, then
    // exalias inpushed `echo hello` but the next ingetc still saw
    // lexstop=true and returned None → tok=ENDINPUT.
    //
    // BOTH lexstop globals must reset: input.rs's local `lexstop` gates
    // ingetc (line 244); lex.rs's `LEX_LEXSTOP` gates gettok. zshrs
    // duplicates the C single `lexstop` global across two modules.
    lexstop.with(|c| c.set(false));
    crate::ported::lex::LEX_LEXSTOP.with(|c| c.set(false));
}

// Remove the top element of the stack                                       // c:736
/// Pop one input-stack frame off the top.
/// Port of `inpoptop()` from Src/input.c:736.
pub fn inpoptop() {
    // c:736
    // c:738 — if (!lexstop) {
    if !crate::ported::lex::LEX_LEXSTOP.with(|c| c.get()) {
        // c:739 — inbufflags &= ~(INP_ALCONT|INP_HISTCONT);
        inbufflags.with(|f| f.set(f.get() & !(INP_ALCONT | INP_HISTCONT)));
        // c:740-753 — drain unread bytes of the popped frame; for alias
        // frames (without RAW_KEEP) push back the corresponding raw-lex
        // marker via zshlex_raw_back so the lexer-side cursor unwinds.
        let was_alias =
            (inbufflags.with(|f| f.get()) & (INP_ALIAS | INP_HIST | INP_RAW_KEEP)) == INP_ALIAS;
        let unread = inbuf.with(|b| {
            let blen = b.borrow().len();
            blen.saturating_sub(inbufpos.with(|p| p.get()))
        });
        if was_alias {
            for _ in 0..unread {
                crate::ported::lex::zshlex_raw_back(); // c:752
            }
        }
    }

    // c:756-757 — if (inbuf && (inbufflags & INP_FREE)) free(inbuf);
    //              Rust Drop covers the heap-string free when entry is replaced.

    // c:759-765 — pop and restore from instacktop->{buf,bufptr,bufleft,bufct,flags}
    if let Some(entry) = instack.with(|st| st.borrow_mut().pop()) {
        // c:770-778 — if (instacktop->alias) { alias->inuse = 0; if trailing
        //               space → inalmore=1; histbackword(); }
        if let Some(name) = &entry.alias {
            {
                let mut tab = crate::ported::hashtable::aliastab_lock()
                    .write()
                    .expect("aliastab poisoned");
                if let Some(a) = tab.get_mut(name) {
                    a.inuse = 0; // c:773
                }
            }
            // c:774-777 — trailing-space → trigger inalmore + histbackword.
            //              INALMORE is not yet a public Rust global; the
            //              histbackword call alone preserves the C-visible
            //              effect on the history cursor.
            if entry.buf.ends_with(' ') {
                crate::ported::hist::histbackword(); // c:776
            }
        }
        inbuf.with(|b| *b.borrow_mut() = entry.buf);
        inbufpos.with(|p| p.set(entry.bufpos));
        inbufflags.with(|f| f.set(entry.flags));
        let remaining = inbuf
            .with(|b| b.borrow().len())
            .saturating_sub(entry.bufpos) as i32;
        inbufct.with(|c| c.set(remaining));
    }
}

// Remove the top element of the stack and all its continuations.            // c:785
/// Pop the topmost input-stack frame plus any continuations.
/// Port of `inpop()` from Src/input.c:785.
pub fn inpop() {
    // c:785
    loop {
        let was_cont = (inbufflags.with(|f| f.get()) & INP_CONT) != 0;
        inpoptop();
        if !was_cont {
            break;
        }
    }
}

/// Pop the top input level only if it's an alias frame.
/// Port of `inpopalias()` from Src/input.c:804 — used to unwind
/// alias expansion without disturbing the underlying source.
pub fn inpopalias() {
    // c:804
    while (inbufflags.with(|f| f.get()) & INP_ALIAS) != 0 {
        inpoptop();
    }
}

/// Get a slice of the unread portion of the current input.
/// Port of `ingetptr()` from Src/input.c:817.
pub fn ingetptr() -> String {
    // c:817
    let pos = inbufpos.with(|p| p.get());
    inbuf.with(|b| {
        b.borrow()
            .get(pos..)
            .map(str::to_string)
            .unwrap_or_default()
    })
}

// Size of buffer for non-interactive command input                        // c:127
/// Size of the shell input buffer
const SHIN_BUF_SIZE: usize = 8192;

/// Re-export of `META` from zsh_h.rs (canonical port of `Src/zsh.h:144`).
/// Duplicate declarations of the Meta byte invite drift; keep one
/// source of truth.

/// Check if a character needs Meta-encoding in the SHIN buffer.
///
/// Port of `imeta(c)` from `Src/ztype.h:60` — `zistype(c, IMETA)`.
/// Per `Src/utils.c:4195-4201`, the IMETA typtab bits are set for:
///   - `'\0'` (0x00)
///   - `Meta` (0x83)
///   - `Pound..=LAST_NORMAL_TOK` (`Bang`) (0x84..=0x9c, ITOK+IMETA)
///   - `Snull..=Nularg` (0x9d..=0xa1, ITOK+IMETA+INULL)
///   - `Marker` (0xa2)
///
/// The previous Rust port used `b < 32 || (0x83..=0x9b).contains(&b)`
/// which was BOTH:
///   - too inclusive (0x01..=0x1f are NOT IMETA per the typtab —
///     only 0x00 is); reading control chars from stdin would have
///     been spuriously Meta-encoded, corrupting the input buffer
///     for SHIN clients that pass them through literally; and
///   - too narrow (0x9c, 0x9d..=0xa1, 0xa2 all needed Meta-encoding
///     but escaped untouched, then later token-byte readers would
///     mis-interpret them as live tokens rather than literal user
///     bytes).
/// Route through the canonical `ztype_h::imeta` typtab predicate so
/// every IMETA test in the codebase agrees.
fn imeta(c: char) -> bool {
    // c:60 (Src/ztype.h)
    let b = c as u32;
    if b > 0xff {
        return false;
    }
    crate::ported::ztype_h::imeta(b as u8)
}

// `InputBuffer` aggregate + thread_local INPUT singleton deleted.
// Every field has been split into a thread_local file-scope static
// matching the corresponding C global in `Src/input.c`. Every
// previously-method-bound fn (`ingetc`, `inungetc`, `inpush`, etc.)
// is now a free fn with the C signature. `StringInput` (Rust-only
// convenience wrapper) was deleted in a previous commit.

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

    /// Test-only reset: clear all input statics so per-test setup
    /// starts from a clean slate (tests run in the same thread by
    /// default and would otherwise leak state between them).
    fn reset_input() {
        super::inbuf.with(|b| b.borrow_mut().clear());
        super::inbufpos.with(|p| p.set(0));
        super::inbufct.with(|c| c.set(0));
        super::inbufflags.with(|f| f.set(0));
        super::lexstop.with(|c| c.set(false));
        super::lineno.with(|l| l.set(1));
        super::instack.with(|st| st.borrow_mut().clear());
        super::pushback.with(|p| p.borrow_mut().clear());
        super::raw_input.with(|r| r.borrow_mut().clear());
    }

    #[test]
    fn test_input_buffer_basic() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("hello", 0);
        assert_eq!(ingetc(), Some('h'));
        assert_eq!(ingetc(), Some('e'));
        assert_eq!(ingetc(), Some('l'));
        assert_eq!(ingetc(), Some('l'));
        assert_eq!(ingetc(), Some('o'));
        assert_eq!(ingetc(), None);
    }

    #[test]
    fn test_input_ungetc() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("abc", 0);
        assert_eq!(ingetc(), Some('a'));
        assert_eq!(ingetc(), Some('b'));
        inungetc('b');
        assert_eq!(ingetc(), Some('b'));
        assert_eq!(ingetc(), Some('c'));
    }

    #[test]
    fn test_input_stack() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("outer", 0);
        assert_eq!(ingetc(), Some('o'));
        inpush("inner", INP_CONT, None);
        assert_eq!(ingetc(), Some('i'));
        assert_eq!(ingetc(), Some('n'));
        assert_eq!(ingetc(), Some('n'));
        assert_eq!(ingetc(), Some('e'));
        assert_eq!(ingetc(), Some('r'));
        assert_eq!(ingetc(), Some('u'));
        assert_eq!(ingetc(), Some('t'));
    }

    #[test]
    fn test_line_number_tracking() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("a\nb\nc", INP_LINENO);
        assert_eq!(lineno.with(|l| l.get()), 1);
        ingetc(); // a
        ingetc(); // \n
        assert_eq!(lineno.with(|l| l.get()), 2);
        ingetc(); // b
        ingetc(); // \n
        assert_eq!(lineno.with(|l| l.get()), 3);
    }

    /// Pin: `imeta(c)` matches the canonical IMETA typtab population
    /// at `Src/utils.c:4195-4201`. IMETA is set for:
    ///   - `'\0'` (c:4195)
    ///   - `Meta` (0x83) (c:4196)
    ///   - `Marker` (0xa2) (c:4197)
    ///   - `Pound..=LAST_NORMAL_TOK` = `0x84..=0x9c` (c:4198, Bang)
    ///   - `Snull..=Nularg` = `0x9d..=0xa1` (c:4200)
    ///
    /// Non-IMETA: every ASCII letter, every ASCII digit, AND every
    /// control char EXCEPT NUL (0x01..=0x1f are NOT IMETA — the
    /// previous Rust port spuriously Meta-encoded them).
    #[test]
    fn test_meta_encoding() {
        let _g = crate::test_util::global_state_lock();
        // Tests must initialise the typtab — without `inittyptab()`
        // every byte's IMETA bit reads as 0. Serialise against other
        // typtab-mutating tests via the canonical lock.
        let _g = crate::ported::ztype_h::TYPTAB_TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        crate::ported::utils::inittyptab();

        // c:4195 — '\0' is IMETA.
        assert!(imeta('\x00'));
        // c:4196 — Meta (0x83) is IMETA.
        assert!(imeta('\u{83}'));
        // c:4197 — Marker (0xa2) is IMETA.
        assert!(imeta('\u{a2}'));
        // c:4198 — Pound (0x84) is IMETA via the NORMAL_TOK loop.
        assert!(imeta('\u{84}'));
        // c:4198 — LAST_NORMAL_TOK = Bang (0x9c) is IMETA.
        assert!(imeta('\u{9c}'));
        // c:4200 — Snull (0x9d) is IMETA via the NULL_TOK loop.
        assert!(imeta('\u{9d}'));
        // c:4200 — Nularg (0xa1) is IMETA at the top of the range.
        assert!(imeta('\u{a1}'));

        // Non-IMETA: ASCII letters / digits.
        assert!(!imeta('a'));
        assert!(!imeta('Z'));
        assert!(!imeta('0'));

        // Non-IMETA: control chars OTHER than NUL. The previous
        // Rust port hardcoded `b < 32` which erroneously included
        // these; canonical C IMETA covers only NUL among control
        // chars (c:4195 has `typtab['\0'] |= IMETA;` and nothing
        // else in the 0x01..=0x1f range).
        assert!(!imeta('\x01'));
        assert!(!imeta('\x1f'));
        // Above 0xa2 (e.g. 0xa3 onward) is NOT IMETA either.
        assert!(!imeta('\u{a3}'));

        // Verify the inlined metafy XOR (Src/utils.c:4856 c ^ 32) is
        // self-inverting — encode then decode round-trips to the input.
        let encoded = char::from_u32(('\x00' as u32) ^ 32).unwrap_or('\x00');
        let decoded = char::from_u32((encoded as u32) ^ 32).unwrap_or(encoded);
        assert_eq!(decoded, '\x00');
    }

    #[test]
    fn test_ingetptr() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("hello world", 0);
        ingetc(); // h
        ingetc(); // e
        ingetc(); // l
        ingetc(); // l
        ingetc(); // o
        assert_eq!(ingetptr(), " world");
    }

    #[test]
    fn test_inerrflush() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("remaining input", 0);
        ingetc();
        inerrflush();
        assert!(lexstop.with(|c| c.get()) || inbufct.with(|c| c.get()) == 0);
    }

    /// `Src/input.c:159-162` — `shinbufreset` body is
    /// `shinbufendptr = shinbufptr = shinbuffer;` — reset both
    /// pointers to the start of the buffer. Rust port clears
    /// `shinbuffer` (the buffer storage) and zeros `shinbufpos`.
    /// Pin both: post-condition is empty buffer + pos==0.
    #[test]
    fn shinbufreset_clears_buffer_and_zeros_pos() {
        let _g = crate::test_util::global_state_lock();
        super::shinbuffer.with(|b| {
            *b.borrow_mut() = "leftover".to_string();
        });
        super::shinbufpos.with(|p| p.set(7));
        super::shinbufreset();
        super::shinbuffer.with(|b| {
            assert!(
                b.borrow().is_empty(),
                "c:161 — shinbuffer must be empty after reset"
            );
        });
        assert_eq!(
            super::shinbufpos.with(|p| p.get()),
            0,
            "c:161 — shinbufpos must be 0 after reset"
        );
    }

    /// `Src/input.c:171-175` — `shinbufalloc` body is
    /// `shinbuffer = zalloc(SHINBUFSIZE); shinbufreset();`. The
    /// Rust port replaces the buffer with a fresh `String` of
    /// `SHIN_BUF_SIZE` capacity, then calls `shinbufreset`.
    /// Pin the post-condition: empty buffer + pos==0 + capacity
    /// hint set.
    #[test]
    fn shinbufalloc_resets_and_capacity_hints() {
        let _g = crate::test_util::global_state_lock();
        super::shinbuffer.with(|b| {
            *b.borrow_mut() = "stale".to_string();
        });
        super::shinbufpos.with(|p| p.set(3));
        super::shinbufalloc();
        super::shinbuffer.with(|b| {
            assert!(
                b.borrow().is_empty(),
                "c:173 — fresh shinbuffer must be empty"
            );
            // Capacity hint is at least 1 (default `String::with_capacity` semantics).
            // Not pinning exact value — different libstd versions may round.
            assert!(b.borrow().capacity() >= 1);
        });
        assert_eq!(super::shinbufpos.with(|p| p.get()), 0);
    }

    /// `Src/input.c:181-194` — `shinbufsave` snapshots the current
    /// buffer onto `shinsavestack` and reinitialises via
    /// `shinbufalloc`. Pin the round-trip: save with buf="abc",
    /// pos=2 → buf reset to "" + stack contains ("abc", 2). Then
    /// `shinbufrestore` restores the saved state.
    #[test]
    fn shinbufsave_restore_round_trip() {
        let _g = crate::test_util::global_state_lock();
        // Clear stack from any prior test.
        super::shinsavestack.with(|s| s.borrow_mut().clear());
        super::shinbuffer.with(|b| *b.borrow_mut() = "abc".to_string());
        super::shinbufpos.with(|p| p.set(2));
        super::shinbufsave();
        super::shinbuffer.with(|b| {
            assert!(
                b.borrow().is_empty(),
                "c:193 — shinbufsave invokes shinbufalloc (resets to empty)"
            );
        });
        assert_eq!(
            super::shinbufpos.with(|p| p.get()),
            0,
            "c:193 — pos must be 0 after save"
        );
        super::shinbufrestore();
        super::shinbuffer.with(|b| {
            assert_eq!(
                *b.borrow(),
                "abc",
                "c:200-209 — shinbufrestore restores saved buffer"
            );
        });
        assert_eq!(
            super::shinbufpos.with(|p| p.get()),
            2,
            "c:200-209 — shinbufrestore restores saved pos"
        );
    }

    /// `Src/input.c:200` — `shinbufrestore` on an empty save stack
    /// must NOT panic (C dereferences `shinsavestack` which would be
    /// NULL — UB in C; the Rust port chose to no-op for safety).
    /// Pin the no-op so a regression doesn't add a panic.
    #[test]
    fn shinbufrestore_on_empty_stack_is_noop() {
        let _g = crate::test_util::global_state_lock();
        super::shinsavestack.with(|s| s.borrow_mut().clear());
        // Pre-seed a non-empty buffer.
        super::shinbuffer.with(|b| *b.borrow_mut() = "persist".to_string());
        super::shinbufrestore();
        super::shinbuffer.with(|b| {
            assert_eq!(
                *b.borrow(),
                "persist",
                "empty-stack restore must leave buffer untouched"
            );
        });
    }

    /// `Src/input.c:328` — `ingetc` skips bytes for which `itok()`
    /// (the canonical predicate at `Src/ztype.h:52`) returns true.
    /// Per `Src/utils.c:4198-4201`, `inittyptab` sets ITOK on
    /// `Pound..LAST_NORMAL_TOK (0x84..0x9c)` and `Snull..Nularg
    /// (0x9d..0xa1)` — i.e. the canonical token range is `0x84..=0xa1`.
    /// A previous hardcoded `0x83..=0x9b` range was both too inclusive
    /// (included 0x83 = Meta lead byte) and too narrow (excluded
    /// 0x9c..=0xa1 = Bang/Snull/Dnull/Bnull/Bnullkeep/Nularg).
    /// Pin the canonical itok-driven skip via two endpoints:
    ///   * 0x9c (Bang) — ITOK, must be skipped.
    ///   * 0xa1 (Nularg) — ITOK, must be skipped.
    #[test]
    fn ingetc_skips_token_bytes_via_itok_predicate() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        // Make sure typtab is populated (without this the per-thread
        // typtab default may have ITOK bits unset).
        crate::ported::utils::inittyptab();

        let bang: char = '\u{009c}'; // Bang (LAST_NORMAL_TOK)
        let nularg: char = '\u{00a1}'; // Nularg (last ITOK byte)
        let mut s = String::new();
        s.push('a');
        s.push(bang);
        s.push('b');
        s.push(nularg);
        s.push('c');
        inputsetline(&s, 0);
        // c:328 — itok bytes must be silently skipped; visible
        // sequence is "abc".
        assert_eq!(ingetc(), Some('a'));
        assert_eq!(
            ingetc(),
            Some('b'),
            "c:328 — Bang (0x9c) must be skipped (ITOK bit set per inittyptab)"
        );
        assert_eq!(
            ingetc(),
            Some('c'),
            "c:328 — Nularg (0xa1) must be skipped (ITOK bit set per inittyptab)"
        );
    }

    /// `Src/input.c:328` — non-token bytes (e.g. Meta=0x83) must NOT
    /// be skipped by `ingetc`. Meta is IMETA-only, never ITOK; treating
    /// it as a token would corrupt every metafied character read by
    /// the lexer. Same for Marker (0xa2) which is IMETA-only per
    /// `Src/utils.c:4197` (`typtab[Marker] |= IMETA`, NOT ITOK).
    #[test]
    fn ingetc_does_not_skip_imeta_only_bytes() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        crate::ported::utils::inittyptab();
        let meta: char = '\u{0083}'; // Meta lead byte — IMETA only
        let marker: char = '\u{00a2}'; // Marker — IMETA only per c:4197
        let mut s = String::new();
        s.push('x');
        s.push(meta);
        s.push('y');
        s.push(marker);
        s.push('z');
        inputsetline(&s, 0);
        assert_eq!(ingetc(), Some('x'));
        assert_eq!(
            ingetc(),
            Some(meta),
            "c:328 — Meta (0x83) is IMETA-only, NOT ITOK; must pass through"
        );
        assert_eq!(ingetc(), Some('y'));
        assert_eq!(
            ingetc(),
            Some(marker),
            "c:328 / c:4197 — Marker (0xa2) is IMETA-only, NOT ITOK; must pass through"
        );
        assert_eq!(ingetc(), Some('z'));
    }

    // ═══════════════════════════════════════════════════════════════════
    // Input-buffer behavior — additional edge cases for ingetc / inungetc
    // / inputsetline / inpush. These pin behavior that existing tests
    // don't cover: empty input, multi-byte ungetc, stack pop sequences,
    // line-number accumulation across pushes.
    // ═══════════════════════════════════════════════════════════════════

    /// Empty input → first ingetc returns None.
    #[test]
    fn input_empty_line_yields_none_first_read() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("", 0);
        assert_eq!(ingetc(), None);
    }

    /// Reading past end keeps returning None (eventually — zshrs may
    /// append a trailing separator like space/newline before the buffer
    /// drains, then None thereafter). Pin: eventually None, no panic.
    #[test]
    fn input_repeated_reads_past_end_keep_returning_none_eventually() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("a", 0);
        assert_eq!(ingetc(), Some('a'));
        // Skip any trailing separator (zshrs's inputsetline may append).
        let mut seen_none = false;
        for _ in 0..10 {
            if ingetc().is_none() {
                seen_none = true;
                break;
            }
        }
        assert!(seen_none, "should reach None within 10 reads past end");
        // After None, subsequent reads must stay None.
        for _ in 0..3 {
            assert_eq!(ingetc(), None);
        }
    }

    /// inungetc on a fresh buffer makes the ungot char the next read.
    #[test]
    fn input_inungetc_before_any_read() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("xyz", 0);
        inungetc('Q');
        assert_eq!(ingetc(), Some('Q'));
        assert_eq!(ingetc(), Some('x'));
    }

    /// Multiple inungetc calls stack LIFO (last in first out).
    #[test]
    fn input_inungetc_lifo_order() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("z", 0);
        inungetc('A');
        inungetc('B');
        inungetc('C');
        // Last pushed comes out first.
        assert_eq!(ingetc(), Some('C'));
        assert_eq!(ingetc(), Some('B'));
        assert_eq!(ingetc(), Some('A'));
        assert_eq!(ingetc(), Some('z'));
    }

    /// inpush then inpoptop returns to the outer buffer.
    #[test]
    fn input_inpush_then_pop_returns_to_outer() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("outer", 0);
        assert_eq!(ingetc(), Some('o'));
        inpush("inner", INP_CONT, None);
        assert_eq!(ingetc(), Some('i'));
        inpoptop();
        // After popping the inner buffer, the next read continues from
        // the outer buffer where it left off.
        assert_eq!(ingetc(), Some('u'));
    }

    /// inputsetline with non-empty replaces buffer cleanly after empty.
    /// (Skip the post-empty read since zshrs leaves the empty-set buffer
    /// state opaque — just drain any residue, then set new buffer.)
    #[test]
    fn input_set_empty_then_set_nonempty_reads_new_content() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("", 0);
        // Drain whatever zshrs left in the empty-set buffer.
        for _ in 0..5 {
            if ingetc().is_none() {
                break;
            }
        }
        inputsetline("xyz", 0);
        // Now the next reads should yield 'x', 'y', 'z' in order.
        assert_eq!(ingetc(), Some('x'));
        assert_eq!(ingetc(), Some('y'));
        assert_eq!(ingetc(), Some('z'));
    }

    /// Reads return exactly the input bytes for ASCII content.
    #[test]
    fn input_ascii_passthrough_byte_for_byte() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        let src = "the quick brown fox 0123!";
        inputsetline(src, 0);
        let mut got = String::new();
        while let Some(c) = ingetc() {
            got.push(c);
        }
        assert_eq!(got, src);
    }

    /// Line-number tracking gate: per `c:Src/input.c:330` —
    /// `if (((inbufflags & INP_LINENO) || !strin) && lastc == '\n') lineno++;`
    /// The gate fires when EITHER the flag is set OR we're not in
    /// string-input mode. The "no INP_LINENO" path only suppresses
    /// the advance when `strin != 0` (string-input mode like eval).
    /// Test pins both the strin=1 suppression (this test) and the
    /// strin=0 always-advance shape — the latter is covered by
    /// input_lineno_flag_increments_on_each_newline below.
    #[test]
    fn input_no_lineno_flag_means_lineno_unchanged_on_newline_anchored() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        // c:330 gate: !strin path triggers the advance even when the
        // INP_LINENO flag is unset. Set strin=1 so the gate's `||`
        // short-circuit relies on the flag alone; with flag=0 lineno
        // must stay put.
        let saved_strin = strin.with(|s| s.get());
        strin.with(|s| s.set(1));
        let start = lineno.with(|l| l.get());
        inputsetline("a\nb\n", 0);
        while ingetc().is_some() {}
        let end = lineno.with(|l| l.get());
        strin.with(|s| s.set(saved_strin));
        assert_eq!(end, start, "c:330 — strin && !INP_LINENO → lineno stable");
    }

    /// INP_LINENO flag → lineno advances by the number of `\n`s.
    #[test]
    fn input_lineno_flag_increments_on_each_newline() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("x\ny\nz\n", INP_LINENO);
        let start = lineno.with(|l| l.get());
        while ingetc().is_some() {}
        let end = lineno.with(|l| l.get());
        assert_eq!(end - start, 3, "three `\\n`s should advance lineno by 3");
    }

    /// Pushing on top of a partially-read buffer reads inner first.
    #[test]
    fn input_inpush_priorities_inner_over_outer() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("abc", 0);
        // Don't read anything yet
        inpush("123", INP_CONT, None);
        // Inner exhausts first
        assert_eq!(ingetc(), Some('1'));
        assert_eq!(ingetc(), Some('2'));
        assert_eq!(ingetc(), Some('3'));
        // Then outer
        assert_eq!(ingetc(), Some('a'));
        assert_eq!(ingetc(), Some('b'));
        assert_eq!(ingetc(), Some('c'));
    }

    /// Multi-byte UTF-8 char passes through correctly.
    #[test]
    fn input_multibyte_utf8_char_passes_through() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("", 0);
        // The char `日` is a single Unicode codepoint; ingetc should
        // return it as a single Option<char>.
        let c = ingetc();
        assert_eq!(c, Some(''));
        assert_eq!(ingetc(), None);
    }

    // ─── zsh-corpus pins for input buffer behavior ─────────────────

    /// Reading all of "abc" returns characters in order then None.
    #[test]
    fn input_corpus_ascii_returns_chars_in_order() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("abc", 0);
        assert_eq!(ingetc(), Some('a'));
        assert_eq!(ingetc(), Some('b'));
        assert_eq!(ingetc(), Some('c'));
        assert_eq!(ingetc(), None);
    }

    /// `inungetc` when `inbufpos > 0` just rewinds position — the
    /// passed char is IGNORED in favor of the buffer content at
    /// `pos - 1`. Per `Src/input.c:546-555`, zsh assumes callers
    /// unget the char they just got. Pin this quirk.
    #[test]
    fn input_corpus_inungetc_after_read_rewinds_to_buf_char() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("xy", 0);
        let _ = ingetc(); // consume 'x' → pos=1
        inungetc('Z');     // pos→0; 'Z' silently dropped per C contract
        assert_eq!(ingetc(), Some('x'), "buf[pos-1] returned, NOT the unget char");
        assert_eq!(ingetc(), Some('y'));
    }

    /// `inungetc` of multiple chars: LIFO order.
    #[test]
    fn input_corpus_inungetc_multiple_lifo() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("end", 0);
        inungetc('1');
        inungetc('2');
        inungetc('3');
        assert_eq!(ingetc(), Some('3'), "last-pushed first");
        assert_eq!(ingetc(), Some('2'));
        assert_eq!(ingetc(), Some('1'));
        assert_eq!(ingetc(), Some('e'), "then original buffer");
    }

    /// Empty inputsetline → ingetc returns None immediately.
    #[test]
    fn input_corpus_empty_line_returns_none() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("", 0);
        assert_eq!(ingetc(), None);
    }

    /// Multi-codepoint UTF-8 string: each codepoint returned once.
    #[test]
    fn input_corpus_multibyte_two_codepoints() {
        let _g = crate::test_util::global_state_lock();
        reset_input();
        inputsetline("日本", 0);
        assert_eq!(ingetc(), Some(''));
        assert_eq!(ingetc(), Some(''));
        assert_eq!(ingetc(), None);
    }
}