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
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
//! Port of `Src/text.c` — textual representations of wordcode (`gettext2`),
//! permanent text (`getpermtext`), job text (`getjobtext`), redirection text
//! (`getredirs`), and the shared character-buffer helpers (`tadd*`, etc.).
use std::cell::RefCell;
use std::sync::atomic::{AtomicI32, Ordering};
use crate::lex;
use crate::parse;
use crate::ported::linklist::LinkList;
use crate::ported::mem::{queue_signals, unqueue_signals};
use crate::ported::utils::{has_token, quotestring};
use crate::ported::zsh_h;
use crate::ported::zsh_h::{
redir, wordcode, estate, Eprog, EC_NODUP, COND_AND, COND_MOD, COND_MODI, COND_NOT, COND_OR,
COND_STREQ, COND_STRDEQ, COND_STRNEQ, IS_READFD, JOBTEXTSIZE, META, REDIRF_FROM_HEREDOC,
REDIR_APP, REDIR_APPNOW, REDIR_ERRAPP, REDIR_ERRAPPNOW, REDIR_ERRWRITE, REDIR_ERRWRITENOW,
REDIR_HEREDOC, REDIR_HERESTR, REDIR_INPIPE, REDIR_MERGEIN, REDIR_MERGEOUT, REDIR_OUTPIPE,
REDIR_READ, REDIR_READWRITE, REDIR_WRITE, REDIR_WRITENOW, Z_ASYNC, Z_DISOWN, Z_END, Z_SIMPLE,
WC_ARITH, WC_ASSIGN, WC_AUTOFN, WC_CASE, WC_CASE_AND, WC_CASE_OR, WC_COND, WC_COUNT, WC_CURSH, WC_END,
WC_FOR, WC_FUNCDEF, WC_IF, WC_IF_ELIF, WC_LIST, WC_PIPE, WC_PIPE_END, WC_PIPE_MID, WC_REPEAT,
WC_REDIR, WC_SELECT, WC_SELECT_LIST, WC_SIMPLE, WC_SUBLIST, WC_SUBLIST_SKIP, WC_SUBSH, WC_TIMED,
WC_TIMED_PIPE, WC_TRY, WC_TYPESET, WC_WHILE, WC_ASSIGN_ARRAY, WC_CASE_SKIP, WC_CASE_TYPE,
WC_COND_SKIP, WC_COND_TYPE, WC_CURSH_SKIP, WC_FOR_COND, WC_FOR_LIST, WC_FOR_TYPE,
WC_FUNCDEF_SKIP, WC_IF_SKIP, WC_IF_TYPE, WC_LIST_TYPE, WC_PIPE_TYPE, WC_SELECT_TYPE,
WC_SIMPLE_ARGC, WC_SUBLIST_COPROC, WC_SUBLIST_END, WC_SUBLIST_FLAGS, WC_SUBLIST_NOT,
WC_SUBLIST_OR, WC_SUBLIST_SIMPLE, WC_SUBLIST_TYPE, WC_SUBSH_SKIP, WC_TIMED_TYPE, WC_TYPESET_ARGC,
WC_WHILE_TYPE, WC_WHILE_UNTIL, wc_code,
};
/// Port of `is_cond_binary_op(const char *str)` from `Src/text.c:58`.
pub fn is_cond_binary_op(str: &str) -> i32 {
COND_BINARY_OPS.iter().any(|&op| op == str) as i32
}
/// Port of `dec_tindent` from `Src/text.c:70`.
pub fn dec_tindent() {
tindent.with(|t| {
let mut v = t.borrow_mut();
if *v > 0 {
*v -= 1;
}
});
}
/// Port of `taddpending(char *str1, char *str2)` from `Src/text.c:89`.
pub fn taddpending(str1: &str, str2: &str) {
let mut v = Vec::with_capacity(str1.len() + str2.len());
v.extend_from_slice(str1.as_bytes());
v.extend_from_slice(str2.as_bytes());
tpending.with(|p| {
let mut g = p.borrow_mut();
match &mut *g {
Some(p) => {
p.push(b'\n');
p.extend_from_slice(&v);
}
None => *g = Some(v),
}
});
}
// ---------------------------------------------------------------------------
// Internal: file-static text buffer + gettext2 (text.c:53–1015)
// ---------------------------------------------------------------------------
// File-statics from `Src/text.c:396` (`tbuf`/`tptr`/`tlim` modeled as `tbuf` Vec +
// `tlim` cap; `tpending`/`tindent`/`tnewlins`/`tjob`).
thread_local! {
static tbuf: RefCell<Vec<u8>> = RefCell::new(Vec::new());
static tlim: RefCell<Option<usize>> = RefCell::new(None);
static tpending: RefCell<Option<Vec<u8>>> = RefCell::new(None);
static tindent: RefCell<i32> = RefCell::new(0);
static tnewlins: RefCell<bool> = RefCell::new(true);
static tjob: RefCell<bool> = RefCell::new(false);
}
/// Port of `tdopending` from `Src/text.c:114`.
pub fn tdopending() {
let drained = tpending.with(|p| p.borrow_mut().take());
if let Some(p) = drained {
tpush(b'\n' as i32);
taddstr(&String::from_utf8_lossy(&p));
}
}
/// Port of `taddchr(int c)` from `Src/text.c:128`.
pub fn taddchr(c: i32) {
tpush(c);
}
/// Port of `taddstr(const char *s)` from `Src/text.c:146`.
pub fn taddstr(s: &str) {
let nl = tnewlins.with(|c| *c.borrow());
if nl {
tbuf.with(|tb| tb.borrow_mut().extend_from_slice(s.as_bytes()));
} else {
for &b in s.as_bytes() {
let ch = if b == b'\n' { b' ' } else { b };
tpush(ch as i32);
}
}
}
/// Port of `taddlist(Estate state, int num)` from `Src/text.c:170`.
fn taddlist(state: &mut estate, num: i32) {
if num == 0 {
return;
}
let mut n = num;
while n > 0 {
taddstr(&ecgetstr(state, EC_NODUP, None));
tpush(b' ' as i32);
n -= 1;
}
tbuf.with(|tb| {
let _ = tb.borrow_mut().pop();
});
}
/// Port of `taddassign(wordcode code, Estate state, int typeset)` from `Src/text.c:184`.
fn taddassign(code: wordcode, state: &mut estate, typeset: i32) {
taddstr(&ecgetstr(state, EC_NODUP, None));
if zsh_h::WC_ASSIGN_TYPE2(code) == zsh_h::WC_ASSIGN_INC {
if typeset != 0 {
let _ = ecgetstr(state, EC_NODUP, None);
tpush(b' ' as i32);
return;
}
tpush(b'+' as i32);
}
tpush(b'=' as i32);
if zsh_h::WC_ASSIGN_TYPE(code) == WC_ASSIGN_ARRAY {
tpush(b'(' as i32);
taddlist(state, zsh_h::WC_ASSIGN_NUM(code) as i32);
taddstr(") ");
} else {
taddstr(&ecgetstr(state, EC_NODUP, None));
tpush(b' ' as i32);
}
}
/// Port of `taddassignlist(Estate state, wordcode count)` from `Src/text.c:213`.
fn taddassignlist(state: &mut estate, count: wordcode) {
if count != 0 {
tpush(b' ' as i32);
}
let mut c = count;
while c > 0 {
if state.pc >= state.prog.prog.len() {
break;
}
let acode = state.prog.prog[state.pc];
state.pc += 1;
taddassign(acode, state, 1);
c -= 1;
}
}
/// Port of `taddnl(int no_semicolon)` from `Src/text.c:227`.
pub fn taddnl(no_semicolon: i32) {
let newlins = tnewlins.with(|c| *c.borrow());
let indent = tindent.with(|t| *t.borrow());
let xt = TEXT_EXPAND_TABS.load(Ordering::Relaxed);
if newlins {
tdopending();
tpush(b'\n' as i32);
for _ in 0..indent {
if xt >= 0 {
if xt > 0 {
for _ in 0..xt {
tpush(b' ' as i32);
}
} else {
tpush(b'\t' as i32);
}
}
}
} else if no_semicolon != 0 {
taddstr(" ");
} else {
taddstr("; ");
}
}
/// Port of `getpermtext(Eprog prog, Wordcode c, int start_indent)` from `Src/text.c:279`.
pub fn getpermtext(prog: Eprog, c: Option<usize>, start_indent: i32) -> String {
queue_signals();
useeprog(&prog);
let mut state = estate {
prog,
pc: c.unwrap_or(0),
strs: None,
strs_offset: 0,
};
tbuf.with(|tb| tb.borrow_mut().clear());
tlim.with(|l| *l.borrow_mut() = None);
tpending.with(|p| *p.borrow_mut() = None);
tindent.with(|t| *t.borrow_mut() = start_indent);
tnewlins.with(|n| *n.borrow_mut() = true);
tjob.with(|j| *j.borrow_mut() = false);
if state.prog.len != 0 {
gettext2(&mut state);
}
let raw = tbuf.with(|tb| {
let mut v = tb.borrow_mut();
String::from_utf8_lossy(&std::mem::take(&mut *v)).into_owned()
});
let p = state.prog;
freeeprog(&p);
unqueue_signals();
lex::untokenize(&raw)
}
/// Port of `getjobtext(Eprog prog, Wordcode c)` from `Src/text.c:315`.
pub fn getjobtext(prog: Eprog, c: Option<usize>) -> String {
queue_signals();
useeprog(&prog);
let mut state = estate {
prog,
pc: c.unwrap_or(0),
strs: None,
strs_offset: 0,
};
tbuf.with(|tb| tb.borrow_mut().clear());
tlim.with(|l| *l.borrow_mut() = Some(JOBTEXTSIZE));
tpending.with(|p| *p.borrow_mut() = None);
tindent.with(|t| *t.borrow_mut() = 0);
tnewlins.with(|n| *n.borrow_mut() = true);
tjob.with(|j| *j.borrow_mut() = true);
if state.prog.len != 0 {
gettext2(&mut state);
}
let mut raw = tbuf.with(|tb| {
let mut v = tb.borrow_mut();
String::from_utf8_lossy(&std::mem::take(&mut *v)).into_owned()
});
if raw.ends_with(META) {
raw.pop();
}
let p = state.prog;
freeeprog(&p);
unqueue_signals();
lex::untokenize(&raw)
}
#[allow(non_camel_case_types)]
struct tstack {
code: wordcode,
pop: i32,
u: tstack_u,
}
/// Port of `tpush(wordcode code, int pop)` from `Src/text.c:396` (append byte to `tbuf`, honour `tlim`).
fn tpush(c: i32) {
let b = c as u8;
tbuf.with(|tb| {
let mut v = tb.borrow_mut();
if let Some(max) = tlim.with(|l| *l.borrow()) {
if v.len() >= max {
return;
}
}
v.push(b);
});
}
/// Port of `gettext2(Estate state)` from `Src/text.c:415`.
pub fn gettext2(state: &mut estate) {
let mut tstack: Vec<tstack> = Vec::new();
let mut stack: i32 = 0;
loop {
let (code, mut spopped, mut s_live): (wordcode, Option<tstack>, Option<usize>) =
if stack != 0 {
if tstack.is_empty() {
break;
}
let should_pop = tstack.last().unwrap().pop != 0;
let code = tstack.last().unwrap().code;
if should_pop {
let fr = tstack.pop().unwrap();
stack = 0;
(code, Some(fr), None)
} else {
stack = 0;
let idx = tstack.len() - 1;
(code, None, Some(idx))
}
} else {
if state.pc >= state.prog.prog.len() {
break;
}
let code = state.prog.prog[state.pc];
state.pc += 1;
(code, None, None)
};
let s_active = s_live.is_some();
let mut s_idx = s_live;
macro_rules! s_mut {
() => {
match (&mut s_idx, &mut spopped) {
(Some(i), None) => Some(&mut tstack[*i]),
(None, Some(p)) => Some(p),
_ => None,
}
};
}
match wc_code(code) {
WC_LIST => {
if !s_active && spopped.is_none() {
tstack.push(tstack {
code,
pop: ((WC_LIST_TYPE(code) as i32) & Z_END) as i32,
u: tstack_u::None,
});
stack = 0;
} else if let Some(fr) = s_mut!() {
let lty = WC_LIST_TYPE(code) as i32;
if (lty & Z_ASYNC) != 0 {
taddstr(" &");
if (lty & Z_DISOWN) != 0 {
taddstr("|");
}
}
let end_here = (lty & Z_END) != 0;
if !end_here {
if tnewlins.with(|c| *c.borrow()) {
taddnl(0);
} else {
taddstr(if (lty & Z_ASYNC) != 0 { " " } else { "; " });
}
if state.pc >= state.prog.prog.len() {
break;
}
fr.code = state.prog.prog[state.pc];
state.pc += 1;
fr.pop = ((WC_LIST_TYPE(fr.code) as i32) & Z_END) as i32;
stack = 0;
} else {
stack = 1;
}
}
if stack == 0 {
let sc = if let Some(fr) = s_mut!() {
fr.code
} else if let Some(fr) = &spopped {
fr.code
} else {
tstack.last().map(|t| t.code).unwrap_or(code)
};
if (WC_LIST_TYPE(sc) as i32 & Z_SIMPLE) != 0 {
state.pc = state.pc.saturating_add(1);
}
}
}
WC_SUBLIST => {
if !s_active && spopped.is_none() {
let p = state.pc;
let mut pre = 0;
if (WC_SUBLIST_FLAGS(code) as i32 & WC_SUBLIST_SIMPLE as i32) == 0
&& p < state.prog.prog.len()
&& wc_code(state.prog.prog[p]) != WC_PIPE
{
pre = -1;
}
if (WC_SUBLIST_FLAGS(code) as i32 & WC_SUBLIST_NOT as i32) != 0 {
taddstr(if pre != 0 { "!" } else { "! " });
}
if (WC_SUBLIST_FLAGS(code) as i32 & WC_SUBLIST_COPROC as i32) != 0 {
taddstr(if pre != 0 { "coproc" } else { "coproc " });
}
tstack.push(tstack {
code,
pop: if WC_SUBLIST_TYPE(code) == WC_SUBLIST_END { 1 } else { 0 },
u: tstack_u::None,
});
stack = pre;
} else if let Some(fr) = s_mut!() {
let end_ty = WC_SUBLIST_TYPE(code) == WC_SUBLIST_END;
if !end_ty {
taddstr(if WC_SUBLIST_TYPE(code) == WC_SUBLIST_OR {
" || "
} else {
" && "
});
if state.pc >= state.prog.prog.len() {
break;
}
fr.code = state.prog.prog[state.pc];
state.pc += 1;
fr.pop = if WC_SUBLIST_TYPE(fr.code) == WC_SUBLIST_END {
1
} else {
0
};
if (WC_SUBLIST_FLAGS(fr.code) as i32 & WC_SUBLIST_NOT as i32) != 0 {
let sk = if WC_SUBLIST_SKIP(fr.code) == 0 {
1
} else {
0
};
let p = state.pc;
let pipe_chk = if p < state.prog.prog.len() {
wc_code(state.prog.prog[p])
} else {
WC_COUNT
};
let not_simple_pipe =
(WC_SUBLIST_FLAGS(fr.code) as i32 & WC_SUBLIST_SIMPLE as i32)
== 0
&& pipe_chk != WC_PIPE;
taddstr(if sk != 0 || not_simple_pipe { "!" } else { "! " });
stack = sk;
}
if (WC_SUBLIST_FLAGS(fr.code) as i32 & WC_SUBLIST_COPROC as i32) != 0
{
taddstr("coproc ");
}
} else {
stack = 1;
}
}
if stack < 1 {
let scode = if let Some(fr) = s_mut!() {
fr.code
} else if let Some(fr) = &spopped {
fr.code
} else {
tstack.last().map(|x| x.code).unwrap_or(code)
};
if (WC_SUBLIST_FLAGS(scode) as i32 & WC_SUBLIST_SIMPLE as i32) != 0 {
state.pc = state.pc.saturating_add(1);
}
}
}
WC_PIPE => {
if !s_active && spopped.is_none() {
tstack.push(tstack {
code,
pop: if WC_PIPE_TYPE(code) == WC_PIPE_END { 1 } else { 0 },
u: tstack_u::None,
});
if WC_PIPE_TYPE(code) == WC_PIPE_MID {
state.pc = state.pc.saturating_add(1);
}
} else if let Some(fr) = s_mut!() {
if !(WC_PIPE_TYPE(code) == WC_PIPE_END) {
taddstr(" | ");
if state.pc >= state.prog.prog.len() {
break;
}
fr.code = state.prog.prog[state.pc];
state.pc += 1;
let end_next = WC_PIPE_TYPE(fr.code) == WC_PIPE_END;
fr.pop = if end_next { 1 } else { 0 };
if !end_next {
state.pc += 1;
}
stack = 0;
} else {
stack = 1;
}
}
}
WC_REDIR => {
if !s_active && spopped.is_none() {
state.pc = state.pc.saturating_sub(1); // c:505
let rows = parse::ecgetredirs(state); // c:507
let mut lst = LinkList::new();
for pr in rows {
lst.push_back(redir {
typ: pr.typ,
flags: pr.flags,
fd1: pr.fd1,
fd2: pr.fd2,
name: pr.name,
varid: pr.varid,
here_terminator: pr.here_terminator,
munged_here_terminator: pr.munged_here_terminator,
});
}
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Redir(lst),
});
} else if let Some(fr) = s_mut!() {
if let tstack_u::Redir(ref ll) = fr.u {
getredirs(ll); // c:509
}
stack = 1; // c:510
}
}
WC_ASSIGN => {
taddassign(code, state, 0);
}
WC_SIMPLE => {
taddlist(state, WC_SIMPLE_ARGC(code) as i32);
stack = 1;
}
WC_TYPESET => {
taddlist(state, WC_TYPESET_ARGC(code) as i32);
if state.pc < state.prog.prog.len() {
let cnt = state.prog.prog[state.pc];
state.pc += 1;
taddassignlist(state, cnt);
}
stack = 1;
}
WC_SUBSH => {
if !s_active && spopped.is_none() {
taddstr("(");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(1);
let end_pc = state.pc + WC_SUBSH_SKIP(code) as usize;
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Subsh { end_pc },
});
state.pc += 1;
} else if let Some(fr) = s_mut!() {
if let tstack_u::Subsh { end_pc } = fr.u {
state.pc = end_pc;
}
dec_tindent();
taddnl(0);
taddstr(")");
stack = 1;
}
}
WC_CURSH => {
if !s_active && spopped.is_none() {
taddstr("{");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(1);
let end_pc = state.pc + WC_CURSH_SKIP(code) as usize;
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Subsh { end_pc },
});
state.pc += 1;
} else if let Some(fr) = s_mut!() {
if let tstack_u::Subsh { end_pc } = fr.u {
state.pc = end_pc;
}
dec_tindent();
taddnl(0);
taddstr("}");
stack = 1;
}
}
WC_TIMED => {
if !s_active && spopped.is_none() {
taddstr("time");
if WC_TIMED_TYPE(code) == WC_TIMED_PIPE {
tpush(b' ' as i32);
tindent.with(|t| *t.borrow_mut() += 1);
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::None,
});
} else {
stack = 1;
}
} else {
dec_tindent();
stack = 1;
}
}
WC_FUNCDEF => {
if !s_active && spopped.is_none() {
let p = state.pc;
let end_pc = p + WC_FUNCDEF_SKIP(code) as usize;
let nargs = if p < state.prog.prog.len() {
let n = state.prog.prog[p] as i32;
state.pc += 1;
n
} else {
0
};
if nargs > 1 {
taddstr("function ");
}
taddlist(state, nargs);
if nargs > 0 {
taddstr(" ");
}
if tjob.with(|c| *c.borrow()) {
if nargs > 1 {
taddstr("{ ... }");
} else {
taddstr("() { ... }");
}
state.pc = end_pc;
if nargs == 0 && end_pc < state.prog.prog.len() {
state.pc += state.prog.prog[end_pc] as usize;
}
stack = 1;
} else {
if nargs > 1 {
taddstr("{");
} else {
taddstr("() {");
}
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(1);
let soff = state.strs_offset;
if state.pc < state.prog.prog.len() {
let bump = state.prog.prog[state.pc] as usize;
state.strs_offset += bump;
state.pc += 4;
}
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Funcdef {
strs_off: soff,
end_pc,
nargs,
},
});
}
} else if let Some(fr) = s_mut!() {
if let tstack_u::Funcdef {
strs_off,
end_pc,
nargs,
} = &mut fr.u
{
state.strs_offset = *strs_off;
state.pc = *end_pc;
let nargs_copy = *nargs;
let end_copy = *end_pc;
dec_tindent();
taddnl(0);
taddstr("}");
if nargs_copy == 0 {
let mut epc = end_copy;
if state.pc < state.prog.prog.len() {
epc += state.prog.prog[state.pc] as usize;
state.pc += 1;
}
let n2 = if state.pc < state.prog.prog.len() {
let v = state.prog.prog[state.pc] as i32;
state.pc += 1;
v
} else {
0
};
if n2 != 0 {
tpush(b' ' as i32);
taddlist(state, n2);
}
state.pc = epc;
}
}
stack = 1;
}
}
WC_FOR => {
if !s_active && spopped.is_none() {
taddstr("for ");
if WC_FOR_TYPE(code) == WC_FOR_COND {
taddstr("((");
taddstr(&ecgetstr(state, EC_NODUP, None));
taddstr("; ");
taddstr(&ecgetstr(state, EC_NODUP, None));
taddstr("; ");
taddstr(&ecgetstr(state, EC_NODUP, None));
taddstr(")) do");
} else {
if state.pc < state.prog.prog.len() {
let a = state.prog.prog[state.pc];
state.pc += 1;
taddlist(state, a as i32);
}
if WC_FOR_TYPE(code) == WC_FOR_LIST {
taddstr(" in ");
if state.pc < state.prog.prog.len() {
let a = state.prog.prog[state.pc];
state.pc += 1;
taddlist(state, a as i32);
}
}
taddnl(0);
taddstr("do");
}
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::None,
});
} else {
dec_tindent();
taddnl(0);
taddstr("done");
stack = 1;
}
}
WC_SELECT => {
if !s_active && spopped.is_none() {
taddstr("select ");
taddstr(&ecgetstr(state, EC_NODUP, None));
if WC_SELECT_TYPE(code) == WC_SELECT_LIST {
taddstr(" in ");
if state.pc < state.prog.prog.len() {
let a = state.prog.prog[state.pc];
state.pc += 1;
taddlist(state, a as i32);
}
}
taddnl(0);
taddstr("do");
taddnl(0);
tindent.with(|t| *t.borrow_mut() += 1);
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::None,
});
} else {
dec_tindent();
taddnl(0);
taddstr("done");
stack = 1;
}
}
WC_WHILE => {
if !s_active && spopped.is_none() {
taddstr(if WC_WHILE_TYPE(code) == WC_WHILE_UNTIL {
"until "
} else {
"while "
});
tindent.with(|t| *t.borrow_mut() += 1);
tstack.push(tstack {
code,
pop: 0,
u: tstack_u::None,
});
} else if let Some(fr) = s_mut!() {
if fr.pop == 0 {
dec_tindent();
taddnl(0);
taddstr("do");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
fr.pop = 1;
} else {
dec_tindent();
taddnl(0);
taddstr("done");
stack = 1;
}
}
}
WC_REPEAT => {
if !s_active && spopped.is_none() {
taddstr("repeat ");
taddstr(&ecgetstr(state, EC_NODUP, None));
taddnl(0);
taddstr("do");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::None,
});
} else {
dec_tindent();
taddnl(0);
taddstr("done");
stack = 1;
}
}
WC_CASE => {
if !s_active && spopped.is_none() {
let end_pc = state.pc + WC_CASE_SKIP(code) as usize;
taddstr("case ");
taddstr(&ecgetstr(state, EC_NODUP, None));
taddstr(" in");
if state.pc >= end_pc {
if tnewlins.with(|c| *c.borrow()) {
taddnl(0);
} else {
tpush(b' ' as i32);
}
taddstr("esac");
stack = 1;
} else {
tindent.with(|t| *t.borrow_mut() += 1);
if tnewlins.with(|c| *c.borrow()) {
taddnl(0);
} else {
tpush(b' ' as i32);
}
taddstr("(");
if state.pc >= state.prog.prog.len() {
break;
}
let c2 = state.prog.prog[state.pc];
state.pc += 1;
if state.pc >= state.prog.prog.len() {
break;
}
let prev_pc = state.pc;
let ialts = state.prog.prog[state.pc];
state.pc += 1;
let mut ial = ialts;
while ial > 0 {
taddstr(&ecgetstr(state, EC_NODUP, None));
state.pc = state.pc.saturating_add(1);
ial -= 1;
if ial > 0 {
taddstr(" | ");
}
}
taddstr(") ");
tindent.with(|t| *t.borrow_mut() += 1);
let pop_v = if prev_pc + WC_CASE_SKIP(c2) as usize >= end_pc {
1
} else {
0
};
tstack.push(tstack {
code: c2,
pop: pop_v,
u: tstack_u::Case { end_pc },
});
}
} else if let Some(fr) = s_mut!() {
if let tstack_u::Case { end_pc } = fr.u {
if state.pc < end_pc {
dec_tindent();
match WC_CASE_TYPE(code) {
x if x == WC_CASE_OR => taddstr(" ;;"),
x if x == WC_CASE_AND => taddstr(" ;&"),
_ => taddstr(" ;|"),
}
if tnewlins.with(|c| *c.borrow()) {
taddnl(0);
} else {
tpush(b' ' as i32);
}
taddstr("(");
if state.pc >= state.prog.prog.len() {
break;
}
let c2 = state.prog.prog[state.pc];
state.pc += 1;
if state.pc >= state.prog.prog.len() {
break;
}
let prev_pc = state.pc;
let ialts = state.prog.prog[state.pc];
state.pc += 1;
let mut ial = ialts;
while ial > 0 {
taddstr(&ecgetstr(state, EC_NODUP, None));
state.pc = state.pc.saturating_add(1);
ial -= 1;
if ial > 0 {
taddstr(" | ");
}
}
taddstr(") ");
tindent.with(|t| *t.borrow_mut() += 1);
fr.code = c2;
fr.pop = if prev_pc + WC_CASE_SKIP(c2) as usize >= end_pc {
1
} else {
0
};
} else {
dec_tindent();
match WC_CASE_TYPE(code) {
x if x == WC_CASE_OR => taddstr(" ;;"),
x if x == WC_CASE_AND => taddstr(" ;&"),
_ => taddstr(" ;|"),
}
dec_tindent();
if tnewlins.with(|c| *c.borrow()) {
taddnl(0);
} else {
tpush(b' ' as i32);
}
taddstr("esac");
stack = 1;
}
}
}
}
WC_IF => {
if !s_active && spopped.is_none() {
let end_pc = state.pc + WC_IF_SKIP(code) as usize;
taddstr("if ");
tindent.with(|t| *t.borrow_mut() += 1);
state.pc += 1;
tstack.push(tstack {
code,
pop: 0,
u: tstack_u::If { end_pc, cond: 1 },
});
} else if let Some(fr) = s_mut!() {
if let tstack_u::If {
end_pc,
ref mut cond,
} = fr.u
{
if fr.pop != 0 {
stack = 1;
} else if *cond != 0 {
dec_tindent();
taddnl(0);
taddstr("then");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
*cond = 0;
} else if state.pc < end_pc {
dec_tindent();
taddnl(0);
if state.pc >= state.prog.prog.len() {
break;
}
let c2 = state.prog.prog[state.pc];
state.pc += 1;
if WC_IF_TYPE(c2) == WC_IF_ELIF {
taddstr("elif ");
tindent.with(|t| *t.borrow_mut() += 1);
*cond = 1;
} else {
taddstr("else");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
}
} else {
fr.pop = 1;
dec_tindent();
taddnl(0);
taddstr("fi");
stack = 1;
}
}
}
}
WC_COND => {
let entry = if !s_active && spopped.is_none() {
None
} else if let Some(ref fr) = spopped {
if let tstack_u::Cond { par } = &fr.u {
Some((*par, fr.code))
} else {
None
}
} else if let Some(i) = s_idx {
match &tstack[i].u {
tstack_u::Cond { par } => Some((*par, tstack[i].code)),
_ => None,
}
} else {
None
};
// Rust-port: closure result → `stack`; C is `while (!stack)` (c:861-970).
stack = (|| -> i32 {
let mut code = code;
let mut stack_out = 0i32;
if entry.is_none() {
taddstr("[[ "); // c:866
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 2 },
}); // c:867-868
} else {
let (par, scode) = entry.unwrap();
if par == 2 {
taddstr(" ]]"); // c:870
return 1; // c:871-872
}
if par == 1 {
taddstr(" )"); // c:874
return 1; // c:875-876
}
let oct = WC_COND_TYPE(scode);
if oct == COND_AND as wordcode {
taddstr(" && "); // c:878
if state.pc >= state.prog.prog.len() {
return 1;
}
code = state.prog.prog[state.pc];
state.pc += 1; // c:879
if WC_COND_TYPE(code) == COND_OR as wordcode {
taddstr("( "); // c:881
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 1 },
}); // c:882-883
}
} else if oct == COND_OR as wordcode {
taddstr(" || "); // c:886
if state.pc >= state.prog.prog.len() {
return 1;
}
code = state.prog.prog[state.pc];
state.pc += 1; // c:887
if WC_COND_TYPE(code) == COND_AND as wordcode {
taddstr("( "); // c:889
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 1 },
}); // c:890-891
}
}
}
while stack_out == 0 {
// c:894
let ctype = WC_COND_TYPE(code) as i32; // c:895
match ctype {
c if c == COND_NOT => {
taddstr("! "); // c:897
if state.pc >= state.prog.prog.len() {
stack_out = 1;
continue;
}
code = state.prog.prog[state.pc];
state.pc += 1; // c:898
if WC_COND_TYPE(code) <= COND_OR as wordcode {
taddstr("( "); // c:900
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 1 },
}); // c:901-902
}
}
c if c == COND_AND => {
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 0 },
}); // c:906-907
if state.pc >= state.prog.prog.len() {
stack_out = 1;
continue;
}
code = state.prog.prog[state.pc];
state.pc += 1; // c:908
if WC_COND_TYPE(code) == COND_OR as wordcode {
taddstr("( "); // c:910
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 1 },
}); // c:911-912
}
}
c if c == COND_OR => {
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 0 },
}); // c:916-917
if state.pc >= state.prog.prog.len() {
stack_out = 1;
continue;
}
code = state.prog.prog[state.pc];
state.pc += 1; // c:918
if WC_COND_TYPE(code) == COND_AND as wordcode {
taddstr("( "); // c:920
tstack.push(tstack {
code,
pop: 1,
u: tstack_u::Cond { par: 1 },
}); // c:921-922
}
}
c if c == COND_MOD => {
taddstr(&ecgetstr(state, EC_NODUP, None)); // c:926
tpush(b' ' as i32); // c:927
taddlist(state, WC_COND_SKIP(code) as i32); // c:928
stack_out = 1; // c:929
}
c if c == COND_MODI => {
let n = ecgetstr(state, EC_NODUP, None); // c:933
taddstr(&ecgetstr(state, EC_NODUP, None)); // c:935
tpush(b' ' as i32); // c:936
taddstr(&n); // c:937
tpush(b' ' as i32); // c:938
taddstr(&ecgetstr(state, EC_NODUP, None)); // c:939
stack_out = 1; // c:940
}
_ => {
if ctype < COND_MOD {
// c:944-954 binary test branch
taddstr(&ecgetstr(state, EC_NODUP, None)); // c:946
taddstr(" "); // c:947
let op_i = (ctype - COND_STREQ) as usize;
if op_i < COND_BINARY_OPS.len() {
taddstr(COND_BINARY_OPS[op_i]); // c:948 `cond_binary_ops[...]`
}
taddstr(" "); // c:949
taddstr(&ecgetstr(state, EC_NODUP, None)); // c:950
if ctype == COND_STREQ || ctype == COND_STRDEQ || ctype == COND_STRNEQ {
state.pc += 1; // c:951-954
}
} else {
// c:956-965 unary `-X` tests
let mut c2 = [0u8; 4];
c2[0] = b'-'; // c:959
c2[1] = ctype as u8; // c:960
c2[2] = b' '; // c:961
taddstr(&String::from_utf8_lossy(&c2[..3])); // c:963 `taddstr(c2)`
taddstr(&ecgetstr(state, EC_NODUP, None)); // c:964
}
stack_out = 1; // c:966
}
}
}
stack_out
})();
}
WC_ARITH => {
taddstr("((");
taddstr(&ecgetstr(state, EC_NODUP, None));
taddstr("))");
stack = 1;
}
WC_AUTOFN => {
taddstr("builtin autoload -X");
stack = 1;
}
WC_TRY => {
if !s_active && spopped.is_none() {
taddstr("{");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
if state.pc < state.prog.prog.len() {
state.pc += 1;
let w = if state.pc > 0 {
state.prog.prog[state.pc - 1]
} else {
0
};
let end_pc = state.pc + WC_CURSH_SKIP(w) as usize;
tstack.push(tstack {
code,
pop: 0,
u: tstack_u::Subsh { end_pc },
});
}
} else if let Some(fr) = s_mut!() {
if fr.pop == 0 {
if let tstack_u::Subsh { end_pc } = fr.u {
state.pc = end_pc;
}
dec_tindent();
taddnl(0);
taddstr("} always {");
tindent.with(|t| *t.borrow_mut() += 1);
taddnl(0);
fr.pop = 1;
} else {
dec_tindent();
taddnl(0);
taddstr("}");
stack = 1;
}
}
}
WC_END => {
stack = 1;
}
_ => {
return;
}
}
}
tdopending();
}
/// Port of `getredirs(LinkList redirs)` from `Src/text.c:1019`.
pub fn getredirs(redirs: &LinkList<redir>) {
queue_signals(); // c:1019
tpush(b' ' as i32); // c:1030
for f in redirs.nodes.iter() {
match f.typ {
REDIR_WRITE | REDIR_WRITENOW | REDIR_APP | REDIR_APPNOW | REDIR_ERRWRITE
| REDIR_ERRWRITENOW | REDIR_ERRAPP | REDIR_ERRAPPNOW | REDIR_READ | REDIR_READWRITE
| REDIR_HERESTR | REDIR_MERGEIN | REDIR_MERGEOUT | REDIR_INPIPE | REDIR_OUTPIPE => {
if let Some(ref vid) = f.varid {
tpush(b'{' as i32);
taddstr(vid);
tpush(b'}' as i32);
} else if f.fd1 != (if IS_READFD(f.typ) { 0 } else { 1 }) {
// c:1054 — `taddchr('0' + f->fd1);`. Single
// char per the C body — no modulo, no
// truncation. fds >= 10 produce non-digit
// bytes (e.g. fd 10 → ':' 0x3A), matching C
// verbatim. The previous Rust port applied
// `% 10` which silently mapped fd 10 → '0',
// fd 11 → '1', etc., diverging from the C
// representation that callers rely on.
taddchr(b'0' as i32 + f.fd1); // c:1054
}
if f.typ == REDIR_HERESTR && (f.flags & REDIRF_FROM_HEREDOC) != 0 {
if tnewlins.with(|c| *c.borrow()) {
taddstr(FSTR[REDIR_HEREDOC as usize]);
if let Some(ref term) = f.here_terminator {
taddstr(term);
}
let n = f.name.clone().unwrap_or_default();
let m = f.munged_here_terminator.clone().unwrap_or_default();
taddpending(&n, &m);
} else {
taddstr(FSTR[REDIR_HERESTR as usize]);
let mut n = f.name.clone().unwrap_or_default();
let sav = n.ends_with('\n');
if sav {
n.pop();
}
if !has_token(&n) {
tpush(b'\'' as i32);
taddstr("estring(&n, crate::ported::zsh_h::QT_SINGLE));
tpush(b'\'' as i32);
} else {
tpush(b'"' as i32);
taddstr("estring(&n, crate::ported::zsh_h::QT_DOUBLE));
tpush(b'"' as i32);
}
let _ = sav;
}
} else {
let fi = usize::try_from(f.typ).unwrap_or(0);
if fi < FSTR.len() {
taddstr(FSTR[fi]);
}
if f.typ != REDIR_MERGEIN && f.typ != REDIR_MERGEOUT {
tpush(b' ' as i32);
}
if let Some(ref nm) = f.name {
taddstr(nm);
}
}
tpush(b' ' as i32);
}
_ => {}
}
}
tbuf.with(|tb| {
let _ = tb.borrow_mut().pop();
}); // c:1116
unqueue_signals(); // c:1118
}
// ---------------------------------------------------------------------------
// Globals from text.c:40 / 48–54
// ---------------------------------------------------------------------------
/// Port of `int text_expand_tabs` from `Src/text.c:58`.
pub static TEXT_EXPAND_TABS: AtomicI32 = AtomicI32::new(0);
static COND_BINARY_OPS: &[&str] = &[
"=", "==", "!=", "<", ">", "-nt", "-ot", "-ef", "-eq", "-ne", "-lt", "-gt", "-le", "-ge", "=~",
];
#[allow(non_camel_case_types)]
enum tstack_u {
None,
Redir(LinkList<redir>),
Funcdef {
strs_off: usize,
end_pc: usize,
nargs: i32,
},
Case {
end_pc: usize,
},
If {
end_pc: usize,
cond: i32,
},
Cond {
par: i32,
},
Subsh {
end_pc: usize,
},
}
// c:1022-1026 — `static char *fstr[]` from `Src/text.c:1022`.
// Indexed by `f->type` (the REDIR_* enum in `Src/zsh.h:377-397`).
// Position 12 = `REDIR_HERESTR` = `"<<<"` — previously typo'd as `"<<"`,
// which would silently misrender `cmd <<<word` as `cmd <<word`.
// Position 15 = `REDIR_CLOSE` is NULL in C (the dispatch routes via
// the `#ifdef DEBUG` branch only); Rust keeps `">&-"` here so an
// out-of-band index lookup doesn't panic, but the real REDIR_CLOSE
// case is filtered out of the match in `getredirs` (matches C
// release-build semantics).
const FSTR: [&str; 18] = [
">", ">|", ">>", ">>|", "&>", "&>|", "&>>", "&>>|", "<>", "<", "<<", "<<-", "<<<", "<&", ">&",
">&-",
"<", ">",
];
/// WARNING: NOT IN `text.c` — `ecgetstr(Estate, …)` is defined in `Src/parse.c`.
/// Local shim renamed to avoid name-clashing with the canonical
/// `parse::ecgetstr(&mut estate, ...)`; the body delegates directly.
fn ecgetstr(st: &mut estate, dup: i32, tok: Option<&mut i32>) -> String {
parse::ecgetstr(st, dup, tok)
}
#[inline]
fn useeprog(_p: &Eprog) {}
#[inline]
fn freeeprog(_p: &Eprog) {}
/// Port of `zoutputtab(FILE *outf)` from `Src/text.c:263`.
pub fn zoutputtab<W: std::io::Write>(outf: &mut W) -> std::io::Result<()> {
let expand_tabs = TEXT_EXPAND_TABS.load(Ordering::Relaxed);
if expand_tabs < 0 {
return Ok(());
}
if expand_tabs > 0 {
let spaces = vec![b' '; expand_tabs as usize];
outf.write_all(&spaces)
} else {
outf.write_all(b"\t")
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn is_cond_binary_matches_zsh_set() {
assert_eq!(is_cond_binary_op("="), 1);
assert_eq!(is_cond_binary_op("-eq"), 1);
assert_eq!(is_cond_binary_op("-nt"), 1);
assert_eq!(is_cond_binary_op("-f"), 0);
assert_eq!(is_cond_binary_op("foo"), 0);
}
#[test]
fn zoutputtab_honours_text_expand_tabs() {
TEXT_EXPAND_TABS.store(0, Ordering::Relaxed);
let mut c = Cursor::new(Vec::new());
zoutputtab(&mut c).unwrap();
assert_eq!(c.into_inner(), b"\t");
TEXT_EXPAND_TABS.store(4, Ordering::Relaxed);
let mut c = Cursor::new(Vec::new());
zoutputtab(&mut c).unwrap();
assert_eq!(c.into_inner(), b" ");
TEXT_EXPAND_TABS.store(-1, Ordering::Relaxed);
let mut c = Cursor::new(Vec::new());
zoutputtab(&mut c).unwrap();
assert_eq!(c.into_inner(), b"");
TEXT_EXPAND_TABS.store(0, Ordering::Relaxed);
}
/// is_cond_binary_op accepts every documented binary test operator
/// from the conditional dispatch table.
#[test]
fn is_cond_binary_op_recognises_canonical_operators() {
for op in ["=", "==", "!=", "<", ">", "-eq", "-ne", "-lt", "-le", "-gt", "-ge"] {
assert_eq!(is_cond_binary_op(op), 1, "{op:?} must be recognised");
}
}
/// Unknown / unary / nonsense operators return 0.
#[test]
fn is_cond_binary_op_rejects_unknown_operators() {
for op in ["?", "@", "", " ", "==="] {
assert_eq!(is_cond_binary_op(op), 0, "{op:?} must NOT be recognised as binary");
}
}
/// `Src/text.c:48-51` — the `cond_binary_ops` table is order-
/// dependent: the comment at c:45-46 states "Their order is tied
/// to the order of the definitions COND_STREQ et seq. in zsh.h."
/// A regression that reorders this array silently misroutes
/// every `[[ $a -eq $b ]]` dispatch in `Src/cond.c` because the
/// caller indexes into the array with `(ctype - COND_STREQ)`.
/// Pin the exact array contents AND the exact length.
#[test]
fn cond_binary_ops_table_matches_c_source_exactly() {
// c:48-51 — verbatim list. Order is the contract.
let expected = [
"=", "==", "!=", "<", ">",
"-nt", "-ot", "-ef",
"-eq", "-ne", "-lt", "-gt", "-le", "-ge",
"=~",
];
assert_eq!(COND_BINARY_OPS.len(), expected.len(),
"c:48-51 — table must have exactly 15 ops (excluding the NULL sentinel)");
for (i, &op) in expected.iter().enumerate() {
assert_eq!(COND_BINARY_OPS[i], op,
"c:48-51 — position {} must be {:?}, got {:?}",
i, op, COND_BINARY_OPS[i]);
}
}
/// `Src/text.c:58-67` — `is_cond_binary_op` returns 1 for the
/// file-test ops `-nt`, `-ot`, `-ef` and the regex match `=~`.
/// The existing canonical-ops test misses these four.
#[test]
fn is_cond_binary_op_accepts_file_test_and_regex_ops() {
for op in ["-nt", "-ot", "-ef", "=~"] {
assert_eq!(is_cond_binary_op(op), 1,
"c:63 — strcmp match must accept {:?}", op);
}
}
/// `taddchr` + `taddstr` smoke — no panic, sanitises pending buffer.
#[test]
fn taddchr_taddstr_smoke_no_panic() {
taddchr(b'x' as i32);
taddstr("hello");
tdopending();
}
/// `taddpending` queues a deferred pair flushed via `tdopending`.
#[test]
fn taddpending_then_tdopending_no_panic() {
taddpending("foo", "bar");
tdopending();
}
/// `taddnl(no_semicolon)` two-mode path: 0 = `; \n`, 1 = `\n` only.
#[test]
fn taddnl_two_modes_no_panic() {
taddnl(0);
taddnl(1);
tdopending();
}
/// `Src/text.c:1022-1026` — `static char *fstr[]` is indexed by
/// `f->type` (the REDIR_* enum at `Src/zsh.h:377-397`). The order
/// is the contract: a regression that swaps positions silently
/// misrenders every `getredirs` output. Pin every slot in the
/// table by C-source comment. Position 12 (REDIR_HERESTR) was
/// previously typo'd as `"<<"` instead of `"<<<"`, dropping the
/// third `<` from herestring round-trips.
#[test]
fn fstr_table_matches_c_source_position_by_position() {
// c:1024-1026 — verbatim list (NULL at position 15 → ">&-" placeholder).
let expected = [
">", // REDIR_WRITE = 0
">|", // REDIR_WRITENOW = 1
">>", // REDIR_APP = 2
">>|", // REDIR_APPNOW = 3
"&>", // REDIR_ERRWRITE = 4
"&>|", // REDIR_ERRWRITENOW = 5
"&>>", // REDIR_ERRAPP = 6
"&>>|",// REDIR_ERRAPPNOW = 7
"<>", // REDIR_READWRITE = 8
"<", // REDIR_READ = 9
"<<", // REDIR_HEREDOC = 10
"<<-", // REDIR_HEREDOCDASH = 11
"<<<", // REDIR_HERESTR = 12 — c:1025 third `<` is load-bearing
"<&", // REDIR_MERGEIN = 13
">&", // REDIR_MERGEOUT = 14
">&-", // REDIR_CLOSE = 15 — NULL in C; placeholder here
"<", // REDIR_INPIPE = 16
">", // REDIR_OUTPIPE = 17
];
assert_eq!(FSTR.len(), expected.len(),
"c:1022 — fstr[] must have exactly 18 slots");
for (i, &want) in expected.iter().enumerate() {
assert_eq!(FSTR[i], want,
"c:1024-1026 — FSTR[{}] must be {:?}, got {:?}",
i, want, FSTR[i]);
}
// Pin the herestring slot specifically — that was the
// typo'd cell.
assert_eq!(FSTR[REDIR_HERESTR as usize], "<<<",
"c:1025 — REDIR_HERESTR (12) must render as `<<<`");
// Pin the heredoc slot too — it shares fstr's 10 cell.
assert_eq!(FSTR[REDIR_HEREDOC as usize], "<<",
"c:1024 — REDIR_HEREDOC (10) must render as `<<`");
}
/// Pin: `Src/text.c:1054` — `taddchr('0' + f->fd1);` adds a
/// SINGLE byte to the text buffer. No modulo, no truncation.
/// fds 0..=9 render as ASCII digits `'0'..='9'`; fds >= 10
/// render as the corresponding 0x3A onward bytes (':' for 10,
/// ';' for 11, etc.) — matching C byte-for-byte even though
/// the result is not a usable shell representation. Test the
/// arithmetic via `taddchr` directly so we don't have to
/// construct a full Redir list.
///
/// The previous Rust port applied `% 10` which mapped fd 10
/// to '0' (corrupting the 1/2 fd-prefix detection in callers
/// that re-parse the text). Pin the byte that `taddchr`
/// receives for the four boundary fds.
#[test]
fn getredirs_fd1_emits_single_byte_no_modulo() {
// The arithmetic the function performs: `'0' + fd1`.
// For fd1 in 0..=9 it produces an ASCII digit.
for fd in 0..=9i32 {
let expected = (b'0' as i32 + fd) as u8;
assert_eq!(expected, b'0' + fd as u8,
"c:1054 — fd {} must produce byte {}", fd, expected);
}
// For fd1 == 10, C emits ':' (0x3A). The previous Rust
// port produced '0' (0x30) — divergent.
assert_eq!((b'0' as i32 + 10) as u8, b':',
"c:1054 — fd 10 emits ':' (0x3A) byte verbatim, not '0' (modulo)");
// For fd1 == 11, C emits ';' (0x3B).
assert_eq!((b'0' as i32 + 11) as u8, b';',
"c:1054 — fd 11 emits ';' (0x3B), not '1'");
}
/// c:48-51 — `cond_binary_ops` table MUST NOT contain duplicates.
/// The C source uses linear search; duplicates would silently
/// route to the FIRST entry's COND_* dispatch index, making
/// the second entry unreachable.
#[test]
fn cond_binary_ops_has_no_duplicates() {
let unique: std::collections::HashSet<_> = COND_BINARY_OPS.iter().copied().collect();
assert_eq!(unique.len(), COND_BINARY_OPS.len(),
"duplicate entry in COND_BINARY_OPS");
}
/// c:48-51 — Every op in `cond_binary_ops` must be a recognised
/// binary operator (round-trip). Pin the table-walk-vs-lookup
/// consistency: anything in the table → `is_cond_binary_op == 1`.
#[test]
fn every_cond_binary_op_round_trips() {
for &op in COND_BINARY_OPS {
assert_eq!(is_cond_binary_op(op), 1,
"{:?} is in COND_BINARY_OPS but is_cond_binary_op rejects it", op);
}
}
/// c:88 — `taddchr` appends a single byte. Test smoke + state
/// query via `tdopending` (which drains the buffer).
#[test]
fn taddchr_appends_single_byte() {
// Smoke: must not panic with any byte value
for c in [0i32, 32, 65, 127, 200, 255] {
taddchr(c);
}
}
/// c:93 — `taddstr` appends a string slice. Smoke test
/// no-panic over a variety of inputs.
#[test]
fn taddstr_appends_string_safely() {
taddstr("");
taddstr("a");
taddstr("hello world");
// Multibyte UTF-8 must not panic
taddstr("café — résumé");
}
/// c:1273 — `TEXT_EXPAND_TABS` defaults to 0. Pin the
/// initial value so a regen flipping to 4 silently doubles
/// every prompt's tab width.
#[test]
fn text_expand_tabs_default_is_zero() {
// Reset to default
TEXT_EXPAND_TABS.store(0, Ordering::Relaxed);
let v = TEXT_EXPAND_TABS.load(Ordering::Relaxed);
assert_eq!(v, 0,
"TEXT_EXPAND_TABS default must be 0 (literal tabs)");
}
/// c:1332 — `zoutputtab` with `TEXT_EXPAND_TABS = 8` emits 8
/// spaces. Pin the canonical "1 tab = 8 spaces" width because
/// it matters for `getjobtext` indentation.
#[test]
fn zoutputtab_emits_n_spaces_for_n_value() {
let saved = TEXT_EXPAND_TABS.load(Ordering::Relaxed);
TEXT_EXPAND_TABS.store(8, Ordering::Relaxed);
let mut c = Cursor::new(Vec::new());
zoutputtab(&mut c).unwrap();
assert_eq!(c.into_inner(), b" ",
"TEXT_EXPAND_TABS=8 must emit 8 spaces");
TEXT_EXPAND_TABS.store(saved, Ordering::Relaxed);
}
/// c:1332 — `zoutputtab` with `TEXT_EXPAND_TABS = 0` emits a
/// literal tab. Pin the no-expand path.
#[test]
fn zoutputtab_zero_emits_literal_tab() {
let saved = TEXT_EXPAND_TABS.load(Ordering::Relaxed);
TEXT_EXPAND_TABS.store(0, Ordering::Relaxed);
let mut c = Cursor::new(Vec::new());
zoutputtab(&mut c).unwrap();
assert_eq!(c.into_inner(), b"\t");
TEXT_EXPAND_TABS.store(saved, Ordering::Relaxed);
}
/// c:1332 — `zoutputtab` with negative value emits NOTHING
/// (the "suppress" sentinel). Pin so a regen that treats
/// negative as 0 silently breaks `getpermtext` indent.
#[test]
fn zoutputtab_negative_emits_nothing() {
let saved = TEXT_EXPAND_TABS.load(Ordering::Relaxed);
TEXT_EXPAND_TABS.store(-1, Ordering::Relaxed);
let mut c = Cursor::new(Vec::new());
zoutputtab(&mut c).unwrap();
assert!(c.into_inner().is_empty(),
"negative TEXT_EXPAND_TABS must emit nothing");
TEXT_EXPAND_TABS.store(saved, Ordering::Relaxed);
}
}