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
//! Strict-dash (Debian Almquist Shell) emulation flag — a zshrs-only
//! extension with NO zsh C counterpart.
//!
//! Upstream zsh has no `dash` personality: its option system models `sh`
//! only as a set of behavior deltas and can never *reject* a zsh syntactic
//! extension the way real dash does. dash is behaviourally `sh` for every
//! option (`shwordsplit`, `ksharrays`, `posix*`, …) and only ADDS
//! rejections of zsh-only syntax. So rather than a distinct `EMULATE_DASH`
//! bit — which would force `|| EMULATION(EMULATE_DASH)` at every one of the
//! ~25 `EMULATION(EMULATE_SH)` call sites — `emulate dash` / `zshrs --dash`
//! sets `EMULATION = EMULATE_SH` and raises this orthogonal flag.
//!
//! The lexer / parser / math / echo gates keyed off [`dash_strict`] turn
//! the following zsh extensions into the same errors real `/bin/dash`
//! produces:
//! * `$'...'` ANSI-C quoting → literal `$` + ordinary single quote
//! * `<<<` here-strings → "redirection unexpected"
//! * `+=` compound assignment → command word ("not found")
//! * `name=(...)` arrays → "( unexpected" syntax error
//! * the `[[ ]]` reserved word → ordinary command ("not found")
//! * arith `**` / `,` → arithmetic parse error
//! * non-XSI `echo` → escapes interpreted by default
//!
//! This lives in `src/extensions/` (not `src/ported/`) because it has no
//! line in zsh's C source; `src/ported/` is a faithful port only.
use RefCell;
use HashMap;
use ;
/// Process-global strict-dash flag. Raised by `emulate dash` (via
/// [`set_dash_strict`]) and cleared by any `emulate` to another
/// personality. Read through [`dash_strict`] at each hot-path gate.
static DASH_STRICT: AtomicBool = new;
/// Process-global "real-shell-faithful" flag for the POSIX-family drop-in
/// modes (`zshrs --sh` / `--ksh` / `--dash`).
///
/// zsh's own `emulate sh`/`emulate ksh` only approximates the Bourne
/// shells and keeps several zsh-family behaviors that the real tools do
/// not — e.g. a trailing non-whitespace IFS separator yields a trailing
/// empty field in zsh (`IFS=:; set -- $v` on `a:b:` → 3 args) but not in
/// dash/ksh/bash (→ 2 args). When raised, zshrs matches the REAL shell
/// instead of zsh's approximation, making `zshrs --sh` strictly more
/// faithful than zsh.
///
/// Design: the bare drop-in flag (`--sh`/`--ksh`/`--dash`) raises this;
/// adding `--zsh` (`zshrs --sh --zsh`) clears it, selecting zsh-style
/// emulation instead. The runtime `emulate sh` builtin never raises it —
/// that path is zsh's feature and keeps zsh semantics. Set only from the
/// binary's CLI mode-application, so it defaults `false` in the library.
static POSIX_FAITHFUL: AtomicBool = new;
/// Process-global bash drop-in flag (`zshrs --bash`). bash is a SUPERSET of
/// POSIX sh with syntax zsh lacks: indirect `${!var}` and case-modification
/// `${v^^}` / `${v,,}` / `${v^}` / `${v,}`. These are parsed in the subst
/// layer only when this is set, so native zsh and the other modes are
/// unaffected. Set from the binary's CLI mode-application; defaults `false`.
static BASH_MODE: AtomicBool = new;
/// Process-global zsh drop-in flag (`zshrs --zsh` / `--zsh-compat`).
///
/// `--zsh` promises identical behaviour to `/bin/zsh`, which means the
/// zshrs-only SYNTAX extensions have to be off — not just the caches and
/// the daemon. A construct zsh's parser rejects must keep being rejected,
/// with zsh's own diagnostic, or the compat-test entrypoint is measuring a
/// different language than the one it claims to stand in for.
///
/// Currently gates the `intercept <kind> <pat> { … }` block body, whose
/// raw-span capture in the lexer has no zsh counterpart: real zsh dies with
/// "parse error near `}'" because `}` cannot be a bare argument, and under
/// this flag zshrs does too.
///
/// Set only from the binary's CLI mode-application, so it defaults `false`
/// in the library and in every embedder.
static ZSH_DROPIN: AtomicBool = new;
/// bash `shopt -s nocasematch` — case-insensitive `[[ == ]]` / `[[ =~ ]]` /
/// `case`. It is NOT a zsh option (opt_state can't store it), so it needs its
/// own flag. Toggled by the `shopt` builtin; read by cond.rs / case matching.
static NOCASEMATCH: AtomicBool = new;
/// Process-global "this Korn drop-in is the pdksh line, not ksh93" flag,
/// raised for `zshrs --mksh` / `--pdksh`.
///
/// `--ksh`, `--mksh` and `--pdksh` all install the same `emulate ksh`
/// option preset and are otherwise indistinguishable at run time, but the
/// two lines genuinely differ where mksh inherited pdksh behavior ksh93
/// never had. The one this currently decides is `$PIPESTATUS`:
/// mksh(1) documents it ("PIPESTATUS: An array variable holding the exit
/// statuses of the last pipeline"), ksh93 has no such parameter —
/// `mksh -c 'true|false|true; print -r -- "[${PIPESTATUS[*]}]"'` → `[0 1 0]`
/// while ksh93 prints `[]`.
static PDKSH_FAMILY: AtomicBool = new;
/// True for a bare `zshrs --mksh` / `--pdksh`. See [`PDKSH_FAMILY`].
/// Select the pdksh/mksh line of the Korn family. Called from the binary's
/// CLI mode application; cleared for `--ksh` and every other mode.
/// True when `shopt -s nocasematch` is active (bash case-insensitive matching).
/// Set/clear bash `nocasematch`.
///
/// !!! WARNING: RUST-ONLY HELPER — BASH IS THE REFERENCE, NOT zsh's C !!!
/// bash(1), The Shopt Builtin: "nocasematch — If set, bash matches patterns
/// in a case-insensitive fashion when performing matching while executing
/// case or [[ conditional commands". Three consumers, two mechanisms:
///
/// * `[[ … == … ]]` / `[[ … != … ]]` and `case` arms case-fold both sides
/// at their match sites, reading the [`NOCASEMATCH`] flag directly
/// (fusevm_bridge's BUILTIN_COND_STRMATCH and `str_match`, cond.rs:462).
/// * `[[ … =~ … ]]` goes through zsh's regex module, which already has the
/// exact knob bash wants: `Src/Modules/regex.c:74` builds its regcomp
/// flags as `REG_EXTENDED | (isset(CASEMATCH) ? 0 : REG_ICASE)`. Rather
/// than bolt a second case-folding path onto the regex engine, mirror
/// the bash flag onto zsh's CASE_MATCH with the sense inverted —
/// `nocasematch` ON means CASE_MATCH OFF means REG_ICASE. CASE_MATCH has
/// exactly one reader in the tree (`src/ported/modules/regex.rs:87/109`),
/// so the mirror cannot leak into any other construct.
///
/// Under `--zsh` nothing calls this, so zsh's own CASE_MATCH is untouched.
/// The bash shopt names whose behavior is carried by a zsh option with the
/// OPPOSITE sense: the shopt is ON exactly when the zsh option is OFF.
///
/// !!! WARNING: RUST-ONLY TABLE — BASH IS THE REFERENCE, NOT zsh's C !!!
/// [`BASH_SHOPTS`]'s middle column can only express a same-sense mapping,
/// and the name(s) below are negations of the zsh option that implements
/// them, so they are resolved here instead of there.
///
/// * `xpg_echo` — bash(1): "If set, the echo builtin expands
/// backslash-escape sequences by default." That is precisely zsh's
/// `NO_BSD_ECHO`: `Src/builtin.c:4754` picks escape processing unless
/// BSD_ECHO is set and `-e` was not given, and `--bash` boots with
/// BSD_ECHO on (so `echo 'a\tb'` prints the backslash, as bash does).
/// Verified against bash 5.3 for `\t`, `\n`, `\c`, `\\`, `\e`, `\0101`
/// and for the `-e` / `-E` overrides, which win over the shopt in both
/// shells.
/// * `nocaseglob` is NOT here — zsh spells it `NO_CASE_GLOB` in the
/// negative too, so `optlookup` resolves the bash spelling directly and
/// the same-sense column already works.
const BASH_SHOPTS_INVERTED_ZSH_OPT: & = &;
/// The `shopt` rows bash treats as READ-ONLY state, not as settable flags.
///
/// !!! WARNING: RUST-ONLY TABLE — BASH IS THE REFERENCE, NOT zsh's C !!!
/// Both report a fact about how the shell was started, so bash accepts
/// `shopt -s`/`-u` on them silently — status 0, no diagnostic — and simply
/// does not change the value:
///
/// $ bash -c 'shopt -s login_shell; echo rc=$?; shopt -p login_shell'
/// rc=0
/// shopt -u login_shell
/// $ bash -lc 'shopt -u login_shell; shopt -p login_shell'
/// shopt -s login_shell
///
/// zshrs let both be written, so `shopt -s login_shell` made `$BASHOPTS`
/// claim a login shell in a non-login one. Their VALUES come from the zsh
/// options that already carry the same state (`LOGIN_SHELL` / `RESTRICTED`,
/// `src/ported/options.rs:108` and `:1527`), which is why `zshrs --bash -l`
/// now reports `shopt -s login_shell` as bash does.
const BASH_SHOPTS_READONLY: & = &;
/// The zsh option carrying `name`'s behavior with an inverted sense, if any.
/// True when the shell is running in strict-dash mode (`emulate dash` or
/// `zshrs --dash`). Gates the zsh-extension rejections that make zshrs
/// match `/bin/dash` byte-for-byte.
/// Set (or clear) strict-dash mode. Called from `options::emulate` — set
/// for the `dash` personality, cleared for every other so a later
/// `emulate zsh` (etc.) fully leaves dash mode.
/// True when a POSIX-family drop-in mode should match the REAL shell
/// rather than zsh's approximation of it. See [`POSIX_FAITHFUL`].
/// True in bash drop-in mode (`zshrs --bash`). Enables bash-only param
/// expansion syntax (`${!var}` indirect, `${v^^}` case-mod). See [`BASH_MODE`].
/// The exit status a FATAL shell error leaves behind, when the emulated
/// shell disagrees with zsh's `1`.
///
/// zsh's `errflag` abort ends the list and the status is whatever `lastval`
/// held — `ERRFLAG_ERROR` is literally `1` (c:Src/zsh.h:2970), so
/// c:Src/exec.c:3001 `lastval = errflag ? errflag : cmdoutval` yields 1.
/// dash does not model errors that way: `sh_error()` calls
/// `exraise(EXERROR)`, whose handler sets `exitstatus = 2` before
/// `exitshell()`, so EVERY fatal expansion / assignment / arithmetic error
/// leaves 2 no matter what the previous status was. Measured on
/// dash 0.5.x and ash, all four fatal shapes:
///
/// ```text
/// dash -c '(set -u; : "$nope") 2>/dev/null; printf "%d\n" $?' → 2
/// dash -c '(: "${nope:?msg}") 2>/dev/null; printf "%d\n" $?' → 2
/// dash -c '(readonly r=1; r=2) 2>/dev/null; printf "%d\n" $?' → 2
/// dash -c '(: $((1/0))) 2>/dev/null; printf "%d\n" $?' → 2
/// ```
///
/// bash, ksh93 and mksh all answer `1` for the same four, which is what
/// zshrs already produces — so this returns `None` outside the dash family
/// and every other mode is untouched. `/bin/sh` is deliberately NOT covered:
/// on this platform it is bash 3.2, which answers `127`, while on Linux it
/// is dash and answers `2`; encoding either would be encoding the host, not
/// the shell.
///
/// Applied at the two places dash's `exitshell` would be reached — the
/// `( … )` boundary and the end of a `-c` script — rather than at each
/// individual `zerr` call, which is exactly where `exraise` unwinds to.
///
/// !!! RUST-ONLY EXTENSION — no zsh C counterpart !!!
/// True in a bare Korn drop-in — `zshrs --ksh`, `--mksh` or `--pdksh`.
///
/// Composed rather than stored: [`posix_faithful`] is raised only by a
/// BARE POSIX-family drop-in flag (cleared by `--zsh` and never set by the
/// runtime `emulate` builtin), and `EMULATION(EMULATE_KSH)` picks the Korn
/// leg out of that family. So this is false in `--zsh`, in native zshrs,
/// under `emulate ksh` typed at a zsh prompt, and in `--sh`/`--dash`/
/// `--bash`. Using the option/emulation bit ALONE would be wrong: a zsh
/// user who runs `emulate ksh` must keep zsh's behavior.
/// True when the shell being emulated has SPARSE indexed arrays — bash and
/// the whole Korn family.
///
/// bash(1), Arrays: "Arrays are assigned to using compound assignments …
/// Indexed array assignments do not require anything but *subscript*=*value*
/// … arrays are sparse, i.e. you do not have to define all the indices."
/// mksh(1) and ksh(1) match: `mksh -c 'a=(x y z); a[5]=q; print -r --
/// "${!a[@]}"'` → `0 1 2 5` and `${#a[@]}` → 4, exactly like bash.
///
/// zsh arrays are DENSE, so `a[5]=q` pads indices 3 and 4 — hence the hole
/// side-table in [`crate::bash_arrays`]. This predicate is the write-side
/// gate for that table; the read side keys off whether holes exist at all,
/// so widening this automatically widens `${#a[@]}` / `${!a[@]}` /
/// `"${a[*]}"` / `typeset -p` with no further change.
/// True when `printf` in bash mode should treat this operand to a numeric
/// conversion (`%d %i %o %u %x %X`) as an error (still prints 0, but exit
/// status 1). bash — unlike zsh/ksh/dash/sh — errors on an explicitly-supplied
/// EMPTY operand (`printf '%d' ''` → rc 1); a MISSING operand (`printf '%d'`)
/// is NOT an error, so `arg` distinguishes them: `Some("")` → true, `None` →
/// false. Non-empty junk ("abc"/"+"/" ") already errors via mathevali in every
/// mode, so only the empty-string case is handled here. Verified vs bash 5.x.
/// Set (or clear) bash drop-in mode. Called from the binary's CLI mode
/// application (raised for `--bash`, unless `--zsh` overrides).
/// True in zsh drop-in mode (`zshrs --zsh` / `--zsh-compat`). Gates OFF the
/// zshrs-only syntax extensions so the compat entrypoint parses exactly what
/// `/bin/zsh` parses. See [`ZSH_DROPIN`].
/// Set (or clear) zsh drop-in mode. Called from the binary's CLI mode
/// application (raised for `--zsh` / `--zsh-compat`).
/// Set (or clear) real-shell-faithful mode. Called from the binary's CLI
/// mode application: raised for a bare `--sh`/`--ksh`/`--dash`, cleared
/// when `--zsh` is also present (zsh-style emulation) or in any other mode.
/// The bash version zshrs advertises in `--bash` mode. Scripts gate features
/// on `${BASH_VERSINFO[0]}` (e.g. `>= 4` for assoc arrays / `${v^^}`), so a
/// modern 5.x keeps every feature path live. Not tied to any real build.
pub const BASH_VERSION_MAJOR: &str = "5";
pub const BASH_VERSION_MINOR: &str = "2";
pub const BASH_VERSION_PATCH: &str = "0";
/// `$BASH_VERSION` scalar, e.g. `5.2.0(1)-release`.
/// `${BASH_VERSINFO[@]}` — the 6-element bash version array:
/// `(major minor patch build release machtype)`.
/// Strip source-literal backslash escapes from a `${var/pat/REPL}` replacement
/// under `--bash`. bash removes a `\` before ANY char in the LITERAL
/// replacement (`\~`→`~`, `\&`→`&`, `\\`→`\`), but NOT from expanded values
/// (`${v/p/$x}` with x=`\~` stays `\~`). This runs on the tokenized replacement
/// BEFORE `singsub`, where source-literal backslashes are raw `\` (0x5c) while
/// expansion-defanging escapes (`\$`/`` \` ``/`\"`) are Bnull markers (0x9f) and
/// spliced values aren't present yet — so touching only raw `\` is exactly the
/// bash rule. A trailing lone `\` is kept.
/// Resolve a bash special ARRAY name (`PIPESTATUS`, `FUNCNAME`,
/// `BASH_VERSINFO`) to its value in `--bash` mode by aliasing the zsh-native
/// special or synthesizing it. Returns `None` for any other name (or outside
/// bash mode) so callers fall through to normal array resolution.
/// bash's `shopt` option table: `(bash name, zshrs option key, bash default)`.
///
/// The name list and the defaults are bash 5.3's own — `bash -c shopt`
/// prints exactly these 59 rows in this order, and `shopt` lists them
/// alphabetically, so no caller re-sorts. bash rejects anything outside the
/// list: `bash -c 'shopt -p zznope'` → "shopt: zznope: invalid shell option
/// name", status 1.
///
/// The middle field is where the state LIVES:
/// * `Some(opt)` — a real zsh option carries the behavior, so the flag is
/// read and written through `opt_state`. Twelve names zsh already has
/// under the same spelling (`optlookup` is underscore- and case-blind),
/// plus two renames whose behavior zsh implements under a different
/// name: bash `extglob` is zsh `kshglob` (identical `@()`/`*()`/`+()`/
/// `?()`/`!()` ksh patterns), and bash `failglob` — "if a pattern fails
/// to match, an error message is printed and the command is not
/// executed" (bash(1) The Shopt Builtin) — is zsh `nomatch`.
/// * `None` — bash-only, no zsh option behind it. zsh's option table is a
/// faithful port and must not grow non-zsh rows (they would leak into
/// `setopt` / `${#options}` under `--zsh`), so the state lives in
/// [`BASH_ONLY_SHOPTS`] keyed by the bash name, seeded from the default
/// in this table.
///
/// !!! RUST-ONLY EXTENSION — no zsh C counterpart !!!
pub const BASH_SHOPTS: & = &;
thread_local!
/// The `BASH_SHOPTS` row for `name`, or `None` when bash would reject the
/// name outright ("invalid shell option name", status 1).
/// Read one bash `shopt` flag. `None` when the name is not a bash shopt.
/// Write one bash `shopt` flag. Returns false when the name is not a bash
/// shopt (caller emits bash's "invalid shell option name" and exits 1).
/// Install bash's `shopt` defaults for every row whose state lives in a
/// REAL zsh option.
///
/// The bash-only rows default correctly on their own (`BASH_ONLY_SHOPTS`
/// falls back to the table), but the twelve zsh-backed ones inherit zsh's
/// default, which is not always bash's: zsh's `histappend`
/// (`APPEND_HISTORY`) is ON where bash's is OFF, so `shopt -p histappend`
/// reported `shopt -s histappend` / status 0 against bash's
/// `shopt -u histappend` / status 1 — and the shell really did append where
/// bash truncates.
///
/// Called once from the binary's `--bash` mode application, BEFORE any user
/// code runs, so a script's own `setopt`/`shopt` still wins.
/// `$BASHOPTS` — bash(1): the shopt options "valid as an argument for the
/// -s option to shopt", colon-separated, in the table's (alphabetical)
/// order. Only the ENABLED ones appear.
/// bash's `set -o` option table — the FIXED ~27 names bash accepts for
/// `set -o NAME` / `set +o NAME`, lists for `set -o` / `set +o`, and joins
/// into `$SHELLOPTS`. Each entry is `(bash name, zshrs option name)`; the
/// order is bash's own (already alphabetical), so no caller re-sorts.
///
/// Six bash names have NO zsh option behind them — `errtrace`, `functrace`,
/// `history`, `keyword`, `nolog`, `posix`. zsh's option table is a faithful
/// port and must not grow non-zsh entries (they would leak into `setopt`,
/// `${#options}` and `$options[…]` in `--zsh`), so their state lives in
/// [`BASH_ONLY_OPTS`] instead, keyed by the bash name. Both halves are read
/// back through [`bash_set_o_get`] so the listing, the query and `$SHELLOPTS`
/// all see one state.
///
/// !!! RUST-ONLY EXTENSION — no zsh C counterpart !!! zsh has no bash
/// personality; `emulate sh` only approximates it and rejects every bash-only
/// option name outright (`Src/options.c:640` `no such option`).
pub const BASH_SET_O: & = &;
/// The bash `set -o` names with no zsh option behind them. State-only: zshrs
/// records the flag so `set -o NAME`, the `set -o` listing and `$SHELLOPTS`
/// agree, but no behavior hangs off them yet. Kept OUT of zsh's option table
/// on purpose — see [`BASH_SET_O`].
///
/// Each defaults OFF, which is also bash's default for all six in a
/// non-interactive `bash -c` (verified: `bash -c 'set -o'`).
const BASH_ONLY_OPTS: & = &;
static BO_ERRTRACE: AtomicBool = new;
static BO_FUNCTRACE: AtomicBool = new;
static BO_HISTORY: AtomicBool = new;
static BO_KEYWORD: AtomicBool = new;
static BO_NOLOG: AtomicBool = new;
static BO_POSIX: AtomicBool = new;
/// Read one bash `set -o` option's state by its BASH name: the bash-only
/// side-table first, else the zsh option it maps to.
/// `set -o NAME` / `set +o NAME` in `--bash` mode.
///
/// Returns `None` when bash mode does not own the name, so the caller falls
/// through to zsh's faithful `optlookup` + `dosetopt` path (`Src/builtin.c:642`);
/// `Some(0)` when the assignment was applied.
///
/// Two of the names — `monitor` and `onecmd` — map to zsh options that
/// `dosetopt` refuses to change after startup (`Src/options.c:746`, the
/// INTERACTIVE / SHINSTDIN / SINGLECOMMAND gate). bash accepts both at any
/// time (`bash -c 'set -o monitor'` → status 0), so they are written straight
/// to the option state, which is what `dosetopt(…, force=1)` would do.
/// `$SHELLOPTS` in `--bash` mode: the colon-joined, alphabetically-ordered
/// list of `set -o` options currently ON (bash(1), "Shell Variables":
/// "SHELLOPTS — A colon-separated list of enabled shell options").
/// [`BASH_SET_O`] is already in bash's alphabetical order.
// ===========================================================================
// !!! WARNING: RUST-ONLY HELPERS — NO zsh C COUNTERPART !!!
//
// Output-format and bookkeeping deltas between zsh and the REAL Bourne-family
// shells that `zshrs --bash` / `--ksh` / `--mksh` / `--pdksh` / `--sh` /
// `--dash` / `--ash` stand in for. zsh's C source is NOT the spec for any of
// these — each was measured against the actual reference binary and the
// observed output is quoted at the definition.
//
// Every predicate below hangs off `posix_faithful()`, which the binary raises
// only for a BARE drop-in flag, so all of them are false in native zshrs, in
// `--zsh`, under a runtime `emulate sh`, and in the zsh-STYLE cross-emulation
// legs (`--sh --zsh` / `--ksh --zsh`). zsh's own formats cannot regress.
// ===========================================================================
/// `umask` with no arguments prints a FIXED four-octal-digit mask in the real
/// Bourne-family shells; zsh prints three digits and emits the leading `0`
/// only when the owner field is non-zero (`Src/builtin.c:7522-7524` —
/// `if (um & 0700) putchar('0'); printf("%03o\n", um);`).
///
/// Measured (`<shell> -c 'umask 022; umask'`):
///
/// ```text
/// bash 5.3 → 0022 dash → 0022 ksh93 → 0022 ash → 0022
/// /bin/sh → 0022 mksh → 022 zsh → 022
/// ```
///
/// mksh is the outlier — it uses zsh's conditional-zero form — so the pdksh
/// line is excluded. Confirmed across the range: `000`/`007`/`022`/`077` gain
/// the zero, `0700`/`0777` already have it, and `umask -S` is byte-identical
/// in every shell, so the `-S` arm is untouched.
// ---------------------------------------------------------------------------
// getopts: $OPTIND reporting, the end-of-options contract, and reset detection
// ---------------------------------------------------------------------------
/// Last value zshrs wrote to `$OPTIND`, and the internal `zoptind` it came
/// from. `bin_getopts` re-reads `$OPTIND` at entry (scripts reset it to start
/// a new parse), so a reported value carrying the emulation bias has to be
/// translated back before it is used as an argument index. Both start at -1,
/// which no report can produce, so the first call always looks like a script
/// assignment.
static GETOPTS_REPORTED: AtomicI32 = new;
/// Internal `zoptind` matching [`GETOPTS_REPORTED`].
static GETOPTS_INTERNAL: AtomicI32 = new;
/// The value the emulated shell would show in `$OPTIND`, given zsh's internal
/// parse state — and the point where the two families disagree.
///
/// zsh advances `zoptind` LAZILY: it names the argument currently being
/// scanned and is bumped only on the NEXT `getopts` call, when the cursor
/// `optcind` is found past the end of that argument
/// (`Src/builtin.c:5699-5703`). Every real Bourne shell instead reports the
/// index of the next argument as soon as the current one is finished. zsh's
/// own answer is 1 where all of them say 2 — a genuine zsh-vs-POSIX semantic
/// difference, not a port bug, so it is corrected only in the drop-in modes:
///
/// ```text
/// $ for s in bash dash ksh mksh ash zsh; do $s -c \
/// 'OPTIND=1; getopts "ab" o -b; printf "%s\n" "$OPTIND"'; done
/// 2 2 2 2 2 1
/// ```
///
/// The families split mid-CLUSTER (`-ab`). bash and ksh93 keep reporting the
/// cluster's own index until it is exhausted; dash, ash and mksh report the
/// next index as soon as any character has been consumed:
///
/// ```text
/// $ for s in bash ksh dash ash mksh; do $s -c \
/// 'OPTIND=1; getopts "ab" o -ab; printf "%s\n" "$OPTIND"'; done
/// 1 1 2 2 2
/// ```
///
/// `optcind == 0` means "positioned at an argument boundary" — nothing was
/// taken from the current word (a fresh call, an exhausted-and-advanced
/// cursor, or the post-`OPTARG` reset at `Src/builtin.c:5771-5772`) — and
/// every shell, zsh included, reports `zoptind` unchanged there.
///
/// `--sh` follows the bash rule: `/bin/sh` is bash on this platform (and on
/// the RHEL-family Linuxes), and the two rules differ only mid-cluster.
///
/// Records the pair so [`getopts_optind_internal`] can undo the bias on the
/// next call. Outside the drop-in modes it returns `zoptind` untouched and
/// records nothing.
/// Translate the `$OPTIND` a script can see back into the internal `zoptind`
/// `bin_getopts` left off at. Only the exact value zshrs itself last reported
/// is translated; anything else is a script assignment (`OPTIND=1`) and is
/// passed through so the reset still works. Identity outside the drop-in modes.
/// True when a script's own write to `$OPTIND` must ALSO rewind the
/// within-argument cursor, so the next `getopts` re-scans that argument from
/// its first character.
///
/// bash, ksh93, mksh and `/bin/sh` treat a changed `$OPTIND` as a full reset;
/// dash and ash keep their character pointer regardless; zsh rewinds only when
/// the new value is 1 AND its internal index was elsewhere:
///
/// ```text
/// $ <shell> -c 'OPTIND=1; getopts "ab" o -b; OPTIND=1; getopts "ab" o -b;
/// printf "%s/%s\n" "$o" "$OPTIND"'
/// bash/ksh/mksh//bin/sh → b/2 dash/ash → ?/2
/// ```
///
/// `raw_param` is `$OPTIND` exactly as the parameter table holds it, BEFORE
/// [`getopts_optind_internal`] removes the reporting bias; anything other than
/// the value zshrs last wrote is a script assignment. False outside the
/// drop-in modes and in the dash family, so zsh's own rule
/// (`Src/builtin.c:5681-5685`) stands alone there.
///
/// KNOWN GAP: bash hooks the ASSIGNMENT rather than comparing values, so it
/// also resets when the assigned value equals the one it last reported —
/// visible only mid-cluster (`getopts ab o -ab; OPTIND=1; getopts ab o -ab`
/// → bash `a`, here `b`). Catching that needs an `$OPTIND` assignment hook in
/// the parameter table; pinned by an ignored parity test rather than faked.
/// POSIX end-of-options bookkeeping for `getopts`, which zsh does not do.
///
/// XCU `getopts`: "When the end of options is encountered, the getopts utility
/// shall exit with a return value greater than zero; … and *name* shall be set
/// to the question-mark character." zsh leaves *name* holding whatever it held
/// before:
///
/// ```text
/// $ <shell> -c 'o=INIT; OPTIND=1; getopts "ab" o --; printf "[%s]\n" "$o"'
/// bash/ksh/mksh/dash/ash → [?] zsh → [INIT]
/// ```
///
/// bash, ksh93 and mksh also CLEAR `$OPTARG` on that return; dash and ash
/// leave the last option's argument in place, and so does zsh:
///
/// ```text
/// $ <shell> -c 'OPTIND=1; for i in 1 2 3; do getopts "a:b" o -b -a W; done;
/// printf "[%s]\n" "$OPTARG"'
/// bash/ksh/mksh → [] dash/ash → [W] zsh → [W]
/// ```
///
/// Call at every "no more options" (`return 1`) exit of `bin_getopts`. No-op
/// outside the drop-in modes.
// ---------------------------------------------------------------------------
// `trap` with no arguments — the listing format
// ---------------------------------------------------------------------------
/// One `trap -- <body> <SIG>` listing line in the emulated shell's own format,
/// or `None` when zsh's format (`Src/builtin.c:7370-7375`) applies unchanged.
///
/// Three deltas, each measured rather than derived from zsh's C:
///
/// 1. **Raw body, not a re-deparse.** zsh compiles the trap body to an Eprog
/// and renders THAT back for the listing (`getpermtext`), so the text is
/// canonicalised. Every other shell echoes the string it was given:
///
/// ```text
/// $ trap 'printf a; printf b' INT; trap
/// zsh → trap -- $'printf a\nprintf b' INT
/// bash/dash/ash/ksh/mksh → trap -- 'printf a; printf b' <SIG>
/// ```
///
/// 2. **Quoting.** zsh and the Korn pair quote only when the body needs it, so
/// `trap ':' HUP` lists as `trap -- : HUP` there and as `trap -- ':' HUP`
/// in bash, dash, ash and `/bin/sh`. The escapes differ too — measured with
/// the bodies `printf 'a b'`, `'x`, `x'`, `a'b'c` and `a\b'`:
///
/// ```text
/// body bash / /bin/sh dash / ash ksh93 mksh
/// printf 'a b' 'printf '\''a b'\''' 'printf '"'"'a b'"'" $'printf \'a b\'' 'printf '\''a b'\'
/// 'x ''\''x' ''"'"'x' $'\'x' \''x'
/// x' 'x'\''' 'x'"'" $'x\'' 'x'\'
/// a\b' 'a\b'\''' 'a\b'"'" $'a\\b\'' 'a\b'\'
/// ```
///
/// bash keeps empty runs at BOTH ends; dash and ash drop a trailing empty
/// one but keep a leading one; ksh93 switches to ANSI-C `$'…'` as soon as
/// the body holds an apostrophe; mksh is byte-identical to zsh's
/// `quotedzputs`, empty-run trimming included.
///
/// 3. **`SIG`-prefixed names in bash only.** `bash -c "trap ':' HUP; trap"`
/// prints `trap -- ':' SIGHUP`, while dash, ash, `/bin/sh`, ksh93 and mksh
/// all print the bare `HUP`. bash leaves the pseudo-signals alone —
/// `EXIT`, `DEBUG`, `ERR` and `RETURN` print unprefixed — so only names
/// resolving to a real signal number are prefixed.
///
/// An empty body is `''` in every shell including zsh, so it needs no special
/// case beyond forcing the quotes.
/// True when `name` is a real signal (1..=SIGCOUNT) rather than one of the
/// pseudo-signals zsh keeps in the same table (`EXIT` at index 0, `ZERR` and
/// `DEBUG` above `SIGCOUNT` — `Src/signals.h:34-46`). Only real signals take
/// bash's `SIG` prefix.
/// ksh93 lists `trap` entries in DESCENDING signal-number order, where zsh,
/// bash, dash, ash and mksh all walk the table upwards:
///
/// ```text
/// $ <shell> -c "trap ':' EXIT INT HUP USR1 TERM QUIT; trap"
/// ksh93 zsh / bash / dash / ash / mksh
/// trap -- : USR1 trap -- : EXIT
/// trap -- : TERM trap -- : HUP (bash: SIGHUP, …)
/// trap -- : QUIT trap -- : INT
/// trap -- : INT trap -- : QUIT
/// trap -- : HUP trap -- : TERM
/// trap -- : EXIT trap -- : USR1
/// ```
///
/// True only for a bare `--ksh`; the pdksh line (`--mksh` / `--pdksh`) matches
/// zsh's ascending walk (`Src/builtin.c:7358` — `for (sig = 0;
/// sig < TRAPCOUNT; sig++)`), and so does every other mode.
// ---------------------------------------------------------------------------
// `type` / `command -V` / `whence -v` on a shell function
// ---------------------------------------------------------------------------
/// The verbose one-line description of a shell function in the emulated
/// shell's wording, or `None` to keep zsh's.
///
/// zsh appends the file the function was loaded from
/// (`Src/hashtable.c:927-941` — `" is a shell function"` then `" from "` and
/// the filename), which for a `-c` script is the shell's own name, so
/// `zsh -fc 'f() { :; }; type f'` prints `f is a shell function from zsh`.
/// No other shell says anything of the kind:
///
/// ```text
/// bash 5.3 → f is a function (then the definition, see below)
/// /bin/sh → f is a function (then the definition)
/// ksh93 → f is a function
/// mksh → f is a function
/// dash → f is a shell function
/// ash → f is a shell function
/// ```
/// True when the emulated shell follows its `type` / `command -V` header line
/// with the function's DEFINITION. bash does; ksh93, mksh, dash and ash do not:
///
/// ```text
/// $ bash -c 'f() { :; }; type f' $ ksh -c 'f() { :; }; type f'
/// f is a function f is a function
/// f ()
/// {
/// :
/// }
/// ```
///
/// `/bin/sh` is bash on this platform and behaves the same, so it is included.
/// Re-lay a deparsed function body in bash's `type` format.
///
/// bash re-prints the parsed function from its own AST (`make_command_string`):
/// the header is `NAME () ` then `{ ` — each with ONE trailing space —
/// statements are indented four spaces per level, and every line but the last
/// carries a trailing `;`.
///
/// ```text
/// $ bash -c 'f() { echo a; echo b; }; type f' | cat -e
/// f is a function$
/// f () $
/// { $
/// echo a;$
/// echo b$
/// }$
/// ```
///
/// `body_lines` is zsh's own rendering of the body (one statement per line,
/// one leading TAB per nesting level), which agrees with bash's line split for
/// a flat list of simple commands — the shape `type` is asked about in
/// practice. It does NOT agree for COMPOUND commands: bash keeps `if true;
/// then` on one line where zsh's deparse splits `if true` / `then`, so those
/// bodies still differ in layout. That gap is pinned by an ignored parity test
/// rather than papered over here; closing it needs a bash-flavoured deparser,
/// which is separate work.
/// True when replacing the positional parameters (`set -- …`) must also
/// rewind `getopts`, and when a write to `$OPTIND` must NOT.
///
/// dash and ash key `getopts` off `shellparam.optind` / `shellparam.optoff`,
/// which `setparam()` resets and an `$OPTIND` assignment does not reach — the
/// exact opposite of bash and the Korn shells:
///
/// ```text
/// $ <shell> -c 'getopts "ab" o -a; set -- -b -a; getopts "ab" o;
/// printf "%s %s\n" "$o" "$OPTIND"'
/// dash/ash → b 2 bash/ksh/mksh → a 3 zsh → a 2
/// ```
///
/// Only the `set --` half is acted on here; the `$OPTIND`-write half stays a
/// pinned gap (see the ignored parity test) because zsh routes the parse
/// index through the parameter itself.
/// Rewind the `getopts` cursor recorded by [`getopts_optind_report`], so a
/// later `$OPTIND` read is not translated against a stale pair.