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
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
//! Lexer for bash scripts
//!
//! Tokenizes input into a stream of tokens with source position tracking.
use std::collections::VecDeque;
use super::span::{Position, Span};
use super::tokens::Token;
/// A token with its source location span.
#[derive(Debug, Clone, PartialEq)]
pub struct SpannedToken {
pub token: Token,
pub span: Span,
}
/// Maximum nesting depth for command substitution in the lexer.
/// THREAT[TM-DOS-044]: Prevents stack overflow from deeply nested $() patterns.
const DEFAULT_MAX_SUBST_DEPTH: usize = 50;
/// Lexer for bash scripts.
pub struct Lexer<'a> {
#[allow(dead_code)] // Stored for error reporting in future
input: &'a str,
/// Current position in the input
position: Position,
chars: std::iter::Peekable<std::str::Chars<'a>>,
/// Buffer for re-injected characters (e.g., rest-of-line after heredoc delimiter).
/// Consumed before `chars`.
reinject_buf: VecDeque<char>,
/// Maximum allowed nesting depth for command substitution
max_subst_depth: usize,
}
impl<'a> Lexer<'a> {
/// Create a new lexer for the given input.
pub fn new(input: &'a str) -> Self {
Self::with_max_subst_depth(input, DEFAULT_MAX_SUBST_DEPTH)
}
/// Create a new lexer with a custom max substitution nesting depth.
/// THREAT[TM-DOS-044]: Limits recursion in read_command_subst_into().
pub fn with_max_subst_depth(input: &'a str, max_depth: usize) -> Self {
Self {
input,
position: Position::new(),
chars: input.chars().peekable(),
reinject_buf: VecDeque::new(),
max_subst_depth: max_depth,
}
}
/// Get the current position in the input.
pub fn position(&self) -> Position {
self.position
}
/// Get the next token from the input (without span info).
pub fn next_token(&mut self) -> Option<Token> {
self.skip_whitespace();
self.next_token_inner()
}
fn peek_char(&mut self) -> Option<char> {
if let Some(&ch) = self.reinject_buf.front() {
Some(ch)
} else {
self.chars.peek().copied()
}
}
fn advance(&mut self) -> Option<char> {
let ch = if !self.reinject_buf.is_empty() {
self.reinject_buf.pop_front()
} else {
self.chars.next()
};
if let Some(c) = ch {
self.position.advance(c);
}
ch
}
/// Get the next token with its source span.
pub fn next_spanned_token(&mut self) -> Option<SpannedToken> {
self.skip_whitespace();
let start = self.position;
let token = self.next_token_inner()?;
let end = self.position;
Some(SpannedToken {
token,
span: Span::from_positions(start, end),
})
}
/// Internal: get next token without recording position (called after whitespace skip)
fn next_token_inner(&mut self) -> Option<Token> {
let ch = self.peek_char()?;
match ch {
'\n' => {
self.advance();
Some(Token::Newline)
}
';' => {
self.advance();
if self.peek_char() == Some(';') {
self.advance();
if self.peek_char() == Some('&') {
self.advance();
Some(Token::DoubleSemiAmp) // ;;&
} else {
Some(Token::DoubleSemicolon) // ;;
}
} else if self.peek_char() == Some('&') {
self.advance();
Some(Token::SemiAmp) // ;&
} else {
Some(Token::Semicolon)
}
}
'|' => {
self.advance();
if self.peek_char() == Some('|') {
self.advance();
Some(Token::Or)
} else {
Some(Token::Pipe)
}
}
'&' => {
self.advance();
if self.peek_char() == Some('&') {
self.advance();
Some(Token::And)
} else if self.peek_char() == Some('>') {
self.advance();
Some(Token::RedirectBoth)
} else {
Some(Token::Background)
}
}
'>' => {
self.advance();
if self.peek_char() == Some('>') {
self.advance();
Some(Token::RedirectAppend)
} else if self.peek_char() == Some('|') {
self.advance();
Some(Token::Clobber)
} else if self.peek_char() == Some('(') {
self.advance();
Some(Token::ProcessSubOut)
} else if self.peek_char() == Some('&') {
self.advance();
Some(Token::DupOutput)
} else {
Some(Token::RedirectOut)
}
}
'<' => {
self.advance();
if self.peek_char() == Some('<') {
self.advance();
if self.peek_char() == Some('<') {
self.advance();
Some(Token::HereString)
} else if self.peek_char() == Some('-') {
self.advance();
Some(Token::HereDocStrip)
} else {
Some(Token::HereDoc)
}
} else if self.peek_char() == Some('(') {
self.advance();
Some(Token::ProcessSubIn)
} else if self.peek_char() == Some('&') {
self.advance();
Some(Token::DupInput)
} else {
Some(Token::RedirectIn)
}
}
'(' => {
self.advance();
if self.peek_char() == Some('(') {
self.advance();
Some(Token::DoubleLeftParen)
} else {
Some(Token::LeftParen)
}
}
')' => {
self.advance();
if self.peek_char() == Some(')') {
self.advance();
Some(Token::DoubleRightParen)
} else {
Some(Token::RightParen)
}
}
'{' => {
// Look ahead to see if this is a brace expansion like {a,b,c} or {1..5}
// vs a brace group like { cmd; }
// Note: { must be followed by space/newline to be a brace group
if self.looks_like_brace_expansion() {
self.read_brace_expansion_word()
} else if self.is_brace_group_start() {
self.advance();
Some(Token::LeftBrace)
} else {
// {single} without comma/dot-dot is kept as literal word
self.read_brace_literal_word()
}
}
'}' => {
self.advance();
Some(Token::RightBrace)
}
'[' => {
self.advance();
if self.peek_char() == Some('[') {
self.advance();
Some(Token::DoubleLeftBracket)
} else {
// [ could be the test command OR a glob bracket expression
// If followed by non-whitespace, treat as start of bracket expression
// e.g., [abc] is a glob pattern, [ -f file ] is test command
// But ["$*"] or ['text'] are NOT glob — they are literal [ + quoted word
match self.peek_char() {
Some(' ') | Some('\t') | Some('\n') | None => {
// Followed by whitespace or EOF - it's the test command
Some(Token::Word("[".to_string()))
}
Some('"') | Some('\'') | Some('$') => {
// [ followed by quote/expansion — treat as part of a regular word.
// Push [ back and read the entire word normally.
self.read_word_starting_with("[")
}
_ => {
// Part of a glob bracket expression [abc], read the whole thing
self.read_bracket_word()
}
}
}
}
']' => {
self.advance();
if self.peek_char() == Some(']') {
self.advance();
Some(Token::DoubleRightBracket)
} else {
Some(Token::Word("]".to_string()))
}
}
'\'' => self.read_single_quoted_string(),
'"' => self.read_double_quoted_string(),
'#' => {
// Comment - skip to end of line
self.skip_comment();
self.next_token_inner()
}
// Handle file descriptor redirects like 2> or 2>&1
'0'..='9' => self.read_word_or_fd_redirect(),
_ => self.read_word(),
}
}
fn skip_whitespace(&mut self) {
while let Some(ch) = self.peek_char() {
if ch == ' ' || ch == '\t' {
self.advance();
} else if ch == '\\' {
// Check for backslash-newline (line continuation) between tokens
let mut lookahead = self.chars.clone();
lookahead.next(); // skip backslash
if lookahead.next() == Some('\n') {
self.advance(); // consume backslash
self.advance(); // consume newline
} else {
break;
}
} else {
break;
}
}
}
fn skip_comment(&mut self) {
while let Some(ch) = self.peek_char() {
if ch == '\n' {
break;
}
self.advance();
}
}
/// Check if this is a file descriptor redirect (e.g., 2>, 2>>, 2>&1)
/// or just a regular word starting with a digit
fn read_word_or_fd_redirect(&mut self) -> Option<Token> {
// We need to look ahead to see if this is a fd redirect pattern
// Collect the leading digits
let mut fd_str = String::new();
// Peek at the first digit - we know it's a digit from the match
if let Some(ch) = self.peek_char()
&& ch.is_ascii_digit()
{
fd_str.push(ch);
}
// Check if it's a single digit followed by > or <
// We need to peek further without consuming
let input_remaining: String = self.chars.clone().collect();
// Check patterns: "N>" "N>>" "N>&" "N<" "N<&"
if fd_str.len() == 1
&& let Some(first_digit) = fd_str.chars().next()
{
let rest = input_remaining.get(1..).unwrap_or(""); // Skip the digit we already matched
if rest.starts_with(">>") {
// N>> - append redirect with fd
let fd: i32 = first_digit.to_digit(10).unwrap() as i32;
self.advance(); // consume digit
self.advance(); // consume >
self.advance(); // consume >
return Some(Token::RedirectFdAppend(fd));
} else if rest.starts_with(">&") {
// N>&M - duplicate fd
let fd: i32 = first_digit.to_digit(10).unwrap() as i32;
self.advance(); // consume digit
self.advance(); // consume >
self.advance(); // consume &
// Read the target fd number
let mut target_str = String::new();
while let Some(c) = self.peek_char() {
if c.is_ascii_digit() {
target_str.push(c);
self.advance();
} else {
break;
}
}
if target_str.is_empty() {
// Just N>& without target - treat as DupOutput with fd
return Some(Token::RedirectFd(fd));
}
let target_fd: i32 = target_str.parse().unwrap_or(1);
return Some(Token::DupFd(fd, target_fd));
} else if rest.starts_with('>') {
// N> - redirect with fd
let fd: i32 = first_digit.to_digit(10).unwrap() as i32;
self.advance(); // consume digit
self.advance(); // consume >
return Some(Token::RedirectFd(fd));
} else if rest.starts_with("<&") {
// N<&M or N<&- - duplicate input fd
let fd: i32 = first_digit.to_digit(10).unwrap() as i32;
self.advance(); // consume digit
self.advance(); // consume <
self.advance(); // consume &
// Read the target fd number or '-'
let mut target_str = String::new();
while let Some(c) = self.peek_char() {
if c.is_ascii_digit() || c == '-' {
target_str.push(c);
self.advance();
if c == '-' {
break;
}
} else {
break;
}
}
if target_str == "-" {
return Some(Token::DupFdClose(fd));
}
let target_fd: i32 = target_str.parse().unwrap_or(0);
return Some(Token::DupFdIn(fd, target_fd));
} else if rest.starts_with('<') && !rest.starts_with("<<") {
// N< - input redirect with fd
let fd: i32 = first_digit.to_digit(10).unwrap() as i32;
self.advance(); // consume digit
self.advance(); // consume <
return Some(Token::RedirectFdIn(fd));
}
}
// Not a fd redirect pattern, read as regular word
self.read_word()
}
fn read_word_starting_with(&mut self, prefix: &str) -> Option<Token> {
let mut word = prefix.to_string();
// Use the same logic as read_word but with pre-seeded content
while let Some(ch) = self.peek_char() {
if ch == '"' || ch == '\'' {
// Word already has content (the prefix) — concatenate the quoted segment
let quote_char = ch;
self.advance();
while let Some(c) = self.peek_char() {
if c == quote_char {
self.advance();
break;
}
if c == '\\' && quote_char == '"' {
self.advance();
if let Some(next) = self.peek_char() {
match next {
'\n' => {
self.advance();
}
'"' | '\\' | '$' | '`' => {
word.push(next);
self.advance();
}
_ => {
word.push('\\');
word.push(next);
self.advance();
}
}
continue;
}
}
word.push(c);
self.advance();
}
continue;
} else if ch == '$' {
word.push(ch);
self.advance();
// Read variable/expansion following $
if let Some(nc) = self.peek_char() {
if nc == '{' || nc == '(' {
word.push(nc);
self.advance();
let (open, close) = if nc == '{' { ('{', '}') } else { ('(', ')') };
let mut depth = 1;
while let Some(bc) = self.peek_char() {
word.push(bc);
self.advance();
if bc == open {
depth += 1;
} else if bc == close {
depth -= 1;
if depth == 0 {
break;
}
}
}
} else if nc.is_ascii_alphanumeric()
|| nc == '_'
|| matches!(nc, '?' | '#' | '@' | '*' | '!' | '$' | '-')
{
word.push(nc);
self.advance();
if nc.is_ascii_alphabetic() || nc == '_' {
while let Some(vc) = self.peek_char() {
if vc.is_ascii_alphanumeric() || vc == '_' {
word.push(vc);
self.advance();
} else {
break;
}
}
}
}
}
continue;
} else if self.is_word_char(ch) || ch == ']' {
word.push(ch);
self.advance();
} else {
break;
}
}
Some(Token::Word(word))
}
fn read_word(&mut self) -> Option<Token> {
let mut word = String::new();
while let Some(ch) = self.peek_char() {
// Handle quoted strings within words (e.g., a="Hello" or VAR="value")
// This handles the case where a word like `a=` is followed by a quoted string
if ch == '"' || ch == '\'' {
if word.is_empty() {
// Start of a new token — let the main tokenizer handle quotes
break;
}
// Word already has content — concatenate the quoted segment
// This handles: VAR="val", date +"%Y", echo foo"bar"
let quote_char = ch;
self.advance(); // consume opening quote
while let Some(c) = self.peek_char() {
if c == quote_char {
self.advance(); // consume closing quote
break;
}
if c == '\\' && quote_char == '"' {
self.advance();
if let Some(next) = self.peek_char() {
match next {
'\n' => {
// \<newline> is line continuation: discard both
self.advance();
}
'"' | '\\' | '$' | '`' => {
word.push(next);
self.advance();
}
_ => {
word.push('\\');
word.push(next);
self.advance();
}
}
continue;
}
}
// Handle $(...) inside double-quoted word segments
// to preserve single-quoted strings within command substitutions
if c == '$' && quote_char == '"' {
word.push(c);
self.advance();
if self.peek_char() == Some('(') {
word.push('(');
self.advance();
self.read_command_subst_into(&mut word);
continue;
}
continue;
}
word.push(c);
self.advance();
}
continue;
} else if ch == '$' {
// Handle variable references and command substitution
self.advance();
// $'...' — ANSI-C quoting: resolve escapes at parse time
if self.peek_char() == Some('\'') {
self.advance(); // consume opening '
word.push_str(&self.read_dollar_single_quoted_content());
continue;
}
// $"..." — locale translation synonym, treated like "..."
if self.peek_char() == Some('"') {
self.advance(); // consume opening "
while let Some(c) = self.peek_char() {
if c == '"' {
self.advance();
break;
}
if c == '\\' {
self.advance();
if let Some(next) = self.peek_char() {
match next {
'\n' => {
self.advance();
}
'"' | '\\' | '$' | '`' => {
word.push(next);
self.advance();
}
_ => {
word.push('\\');
word.push(next);
self.advance();
}
}
continue;
}
}
if c == '$' {
word.push(c);
self.advance();
if let Some(nc) = self.peek_char() {
if nc == '{' {
word.push(nc);
self.advance();
while let Some(bc) = self.peek_char() {
word.push(bc);
self.advance();
if bc == '}' {
break;
}
}
} else if nc == '(' {
word.push(nc);
self.advance();
let mut depth = 1;
while let Some(pc) = self.peek_char() {
word.push(pc);
self.advance();
if pc == '(' {
depth += 1;
} else if pc == ')' {
depth -= 1;
if depth == 0 {
break;
}
}
}
} else if nc.is_ascii_alphanumeric()
|| nc == '_'
|| matches!(nc, '?' | '#' | '@' | '*' | '!' | '$' | '-')
{
word.push(nc);
self.advance();
if nc.is_ascii_alphabetic() || nc == '_' {
while let Some(vc) = self.peek_char() {
if vc.is_ascii_alphanumeric() || vc == '_' {
word.push(vc);
self.advance();
} else {
break;
}
}
}
}
}
continue;
}
word.push(c);
self.advance();
}
continue;
}
word.push(ch); // push the '$'
// Check for $( - command substitution or arithmetic
if self.peek_char() == Some('(') {
word.push('(');
self.advance();
// Check for $(( - arithmetic expansion
if self.peek_char() == Some('(') {
word.push('(');
self.advance();
// Read until ))
let mut depth = 2;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
if c == '(' {
depth += 1;
} else if c == ')' {
depth -= 1;
if depth == 0 {
break;
}
}
}
} else {
// Command substitution $(...) - track nested parens
let mut depth = 1;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
if c == '(' {
depth += 1;
} else if c == ')' {
depth -= 1;
if depth == 0 {
break;
}
}
}
if depth > 0 {
return Some(Token::Error(
"unterminated command substitution".to_string(),
));
}
}
} else if self.peek_char() == Some('{') {
// ${VAR} format — track nested braces so ${a[${#b[@]}]}
// doesn't stop at the inner }.
word.push('{');
self.advance();
let mut brace_depth = 1i32;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
if c == '$' && self.peek_char() == Some('{') {
// Nested ${...}
word.push('{');
self.advance();
brace_depth += 1;
} else if c == '}' {
brace_depth -= 1;
if brace_depth == 0 {
break;
}
}
}
} else {
// Check for special single-character variables ($?, $#, $@, $*, $!, $$, $-, $0-$9)
if let Some(c) = self.peek_char() {
if matches!(c, '?' | '#' | '@' | '*' | '!' | '$' | '-')
|| c.is_ascii_digit()
{
word.push(c);
self.advance();
} else {
// Read variable name (alphanumeric + _)
while let Some(c) = self.peek_char() {
if c.is_ascii_alphanumeric() || c == '_' {
word.push(c);
self.advance();
} else {
break;
}
}
}
}
}
} else if ch == '{' {
// Brace expansion pattern - include entire {...} in word
word.push(ch);
self.advance();
let mut depth = 1;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
if c == '{' {
depth += 1;
} else if c == '}' {
depth -= 1;
if depth == 0 {
break;
}
}
}
} else if ch == '`' {
// Backtick command substitution: convert `cmd` to $(cmd)
self.advance(); // consume opening `
word.push_str("$(");
let mut closed = false;
while let Some(c) = self.peek_char() {
if c == '`' {
self.advance(); // consume closing `
closed = true;
break;
}
if c == '\\' {
// In backticks, backslash only escapes $, `, \, newline
self.advance();
if let Some(next) = self.peek_char() {
if matches!(next, '$' | '`' | '\\' | '\n') {
word.push(next);
self.advance();
} else {
word.push('\\');
word.push(next);
self.advance();
}
}
} else {
word.push(c);
self.advance();
}
}
if !closed {
return Some(Token::Error(
"unterminated backtick substitution".to_string(),
));
}
word.push(')');
} else if ch == '\\' {
self.advance();
if let Some(next) = self.peek_char() {
if next == '\n' {
// Line continuation: skip backslash + newline
self.advance();
} else {
// Escaped character: backslash quotes the next char
// (quote removal — only the literal char survives)
word.push(next);
self.advance();
}
} else {
word.push('\\');
}
} else if ch == '(' && word.ends_with('=') && self.looks_like_assoc_assign() {
// Associative compound assignment: var=([k]="v" ...) — keep entire
// (...) as part of word so declare -A m=([k]="v") stays one token.
word.push(ch);
self.advance();
let mut depth = 1;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
break;
}
}
'"' => {
while let Some(qc) = self.peek_char() {
word.push(qc);
self.advance();
if qc == '"' {
break;
}
if qc == '\\'
&& let Some(esc) = self.peek_char()
{
word.push(esc);
self.advance();
}
}
}
'\'' => {
while let Some(qc) = self.peek_char() {
word.push(qc);
self.advance();
if qc == '\'' {
break;
}
}
}
'\\' => {
if let Some(esc) = self.peek_char() {
word.push(esc);
self.advance();
}
}
_ => {}
}
}
} else if ch == '(' && word.ends_with(['@', '?', '*', '+', '!']) {
// Extglob: @(...), ?(...), *(...), +(...), !(...)
// Consume through matching ) including nested parens
word.push(ch);
self.advance();
let mut depth = 1;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
break;
}
}
'\\' => {
if let Some(esc) = self.peek_char() {
word.push(esc);
self.advance();
}
}
_ => {}
}
}
} else if self.is_word_char(ch) {
word.push(ch);
self.advance();
} else {
break;
}
}
if word.is_empty() {
None
} else {
Some(Token::Word(word))
}
}
fn read_single_quoted_string(&mut self) -> Option<Token> {
self.advance(); // consume opening '
let mut content = String::new();
let mut closed = false;
while let Some(ch) = self.peek_char() {
if ch == '\'' {
self.advance(); // consume closing '
closed = true;
break;
}
content.push(ch);
self.advance();
}
if !closed {
return Some(Token::Error("unterminated single quote".to_string()));
}
// If next char is another quote or word char, concatenate (e.g., 'EOF'"2" -> EOF2).
// Any quoting makes the whole token literal.
self.read_continuation_into(&mut content);
// Single-quoted strings are literal - no variable expansion
Some(Token::LiteralWord(content))
}
/// After a closing quote, read any adjacent quoted or unquoted word chars
/// into `content`. Handles concatenation like `'foo'"bar"baz` -> `foobarbaz`.
fn read_continuation_into(&mut self, content: &mut String) {
loop {
match self.peek_char() {
Some('\'') => {
self.advance(); // opening '
while let Some(ch) = self.peek_char() {
if ch == '\'' {
self.advance(); // closing '
break;
}
content.push(ch);
self.advance();
}
}
Some('"') => {
self.advance(); // opening "
while let Some(ch) = self.peek_char() {
if ch == '"' {
self.advance(); // closing "
break;
}
if ch == '\\' {
self.advance();
if let Some(next) = self.peek_char() {
match next {
'"' | '\\' | '$' | '`' => {
content.push(next);
self.advance();
}
_ => {
content.push('\\');
content.push(next);
self.advance();
}
}
continue;
}
}
content.push(ch);
self.advance();
}
}
Some('$') => {
// Check for $'...' ANSI-C quoting in continuation
let mut lookahead = self.chars.clone();
lookahead.next(); // skip $
if lookahead.next() == Some('\'') {
self.advance(); // consume $
self.advance(); // consume opening '
content.push_str(&self.read_dollar_single_quoted_content());
} else {
content.push('$');
self.advance();
}
}
Some(ch) if self.is_word_char(ch) => {
content.push(ch);
self.advance();
}
_ => break,
}
}
}
/// Read ANSI-C quoted content ($'...').
/// Opening $' already consumed. Returns the resolved string.
fn read_dollar_single_quoted_content(&mut self) -> String {
let mut out = String::new();
while let Some(ch) = self.peek_char() {
if ch == '\'' {
self.advance();
break;
}
if ch == '\\' {
self.advance();
if let Some(esc) = self.peek_char() {
self.advance();
match esc {
'n' => out.push('\n'),
't' => out.push('\t'),
'r' => out.push('\r'),
'a' => out.push('\x07'),
'b' => out.push('\x08'),
'f' => out.push('\x0C'),
'v' => out.push('\x0B'),
'e' | 'E' => out.push('\x1B'),
'\\' => out.push('\\'),
'\'' => out.push('\''),
'"' => out.push('"'),
'?' => out.push('?'),
'x' => {
let mut hex = String::new();
for _ in 0..2 {
if let Some(h) = self.peek_char() {
if h.is_ascii_hexdigit() {
hex.push(h);
self.advance();
} else {
break;
}
}
}
if let Ok(val) = u8::from_str_radix(&hex, 16) {
out.push(val as char);
}
}
'u' => {
let mut hex = String::new();
for _ in 0..4 {
if let Some(h) = self.peek_char() {
if h.is_ascii_hexdigit() {
hex.push(h);
self.advance();
} else {
break;
}
}
}
if let Ok(val) = u32::from_str_radix(&hex, 16)
&& let Some(c) = char::from_u32(val)
{
out.push(c);
}
}
'U' => {
let mut hex = String::new();
for _ in 0..8 {
if let Some(h) = self.peek_char() {
if h.is_ascii_hexdigit() {
hex.push(h);
self.advance();
} else {
break;
}
}
}
if let Ok(val) = u32::from_str_radix(&hex, 16)
&& let Some(c) = char::from_u32(val)
{
out.push(c);
}
}
'0'..='7' => {
let mut oct = String::new();
oct.push(esc);
for _ in 0..2 {
if let Some(o) = self.peek_char() {
if o.is_ascii_digit() && o < '8' {
oct.push(o);
self.advance();
} else {
break;
}
}
}
if let Ok(val) = u8::from_str_radix(&oct, 8) {
out.push(val as char);
}
}
_ => {
out.push('\\');
out.push(esc);
}
}
} else {
out.push('\\');
}
continue;
}
out.push(ch);
self.advance();
}
out
}
fn read_double_quoted_string(&mut self) -> Option<Token> {
self.advance(); // consume opening "
let mut content = String::new();
let mut closed = false;
while let Some(ch) = self.peek_char() {
match ch {
'"' => {
self.advance(); // consume closing "
closed = true;
break;
}
'\\' => {
self.advance();
if let Some(next) = self.peek_char() {
// Handle escape sequences
match next {
'\n' => {
// \<newline> is line continuation: discard both
self.advance();
}
'"' | '\\' | '$' | '`' => {
content.push(next);
self.advance();
}
_ => {
content.push('\\');
content.push(next);
self.advance();
}
}
}
}
'$' => {
content.push('$');
self.advance();
if self.peek_char() == Some('(') {
// $(...) command substitution — track paren depth
content.push('(');
self.advance();
self.read_command_subst_into(&mut content);
} else if self.peek_char() == Some('{') {
// ${...} parameter expansion — track brace depth so
// inner quotes (e.g. ${arr["key"]}) don't end the string
content.push('{');
self.advance();
self.read_param_expansion_into(&mut content);
}
}
'`' => {
// Backtick command substitution inside double quotes
self.advance(); // consume opening `
content.push_str("$(");
while let Some(c) = self.peek_char() {
if c == '`' {
self.advance();
break;
}
if c == '\\' {
self.advance();
if let Some(next) = self.peek_char() {
if matches!(next, '$' | '`' | '\\' | '"') {
content.push(next);
self.advance();
} else {
content.push('\\');
content.push(next);
self.advance();
}
}
} else {
content.push(c);
self.advance();
}
}
content.push(')');
}
_ => {
content.push(ch);
self.advance();
}
}
}
if !closed {
return Some(Token::Error("unterminated double quote".to_string()));
}
// Check for continuation after closing quote: "foo"bar or "foo"/* etc.
// If there's adjacent unquoted content (word chars, globs, more quotes),
// concatenate and return as Word (not QuotedWord) so glob expansion works
// on the unquoted portion.
if let Some(ch) = self.peek_char()
&& (self.is_word_char(ch) || ch == '\'' || ch == '"' || ch == '$')
{
self.read_continuation_into(&mut content);
return Some(Token::Word(content));
}
Some(Token::QuotedWord(content))
}
/// Read command substitution content after `$(`, handling nested parens and quotes.
/// Appends chars to `content` and adds the closing `)`.
/// THREAT[TM-DOS-044]: `subst_depth` tracks nesting to prevent stack overflow.
fn read_command_subst_into(&mut self, content: &mut String) {
self.read_command_subst_into_depth(content, 0);
}
fn read_command_subst_into_depth(&mut self, content: &mut String, subst_depth: usize) {
if subst_depth >= self.max_subst_depth {
// Depth limit exceeded — consume until matching ')' and emit error token
let mut depth = 1;
while let Some(c) = self.peek_char() {
self.advance();
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
content.push(')');
return;
}
}
_ => {}
}
}
return;
}
let mut depth = 1;
while let Some(c) = self.peek_char() {
match c {
'(' => {
depth += 1;
content.push(c);
self.advance();
}
')' => {
depth -= 1;
self.advance();
if depth == 0 {
content.push(')');
break;
}
content.push(c);
}
'"' => {
// Nested double-quoted string inside $()
content.push('"');
self.advance();
while let Some(qc) = self.peek_char() {
match qc {
'"' => {
content.push('"');
self.advance();
break;
}
'\\' => {
content.push('\\');
self.advance();
if let Some(esc) = self.peek_char() {
content.push(esc);
self.advance();
}
}
'$' => {
content.push('$');
self.advance();
if self.peek_char() == Some('(') {
content.push('(');
self.advance();
self.read_command_subst_into_depth(content, subst_depth + 1);
}
}
_ => {
content.push(qc);
self.advance();
}
}
}
}
'\'' => {
// Single-quoted string inside $()
content.push('\'');
self.advance();
while let Some(qc) = self.peek_char() {
content.push(qc);
self.advance();
if qc == '\'' {
break;
}
}
}
'\\' => {
content.push('\\');
self.advance();
if let Some(esc) = self.peek_char() {
content.push(esc);
self.advance();
}
}
_ => {
content.push(c);
self.advance();
}
}
}
}
/// Read parameter expansion content after `${`, handling nested braces and quotes.
/// In bash, quotes inside `${...}` (e.g. `${arr["key"]}`) don't terminate the
/// outer double-quoted string. Appends chars including closing `}` to `content`.
fn read_param_expansion_into(&mut self, content: &mut String) {
let mut depth = 1;
while let Some(c) = self.peek_char() {
match c {
'{' => {
depth += 1;
content.push(c);
self.advance();
}
'}' => {
depth -= 1;
self.advance();
content.push('}');
if depth == 0 {
break;
}
}
'"' => {
// Quotes inside ${...} are part of the expansion, not string delimiters
content.push('"');
self.advance();
}
'\'' => {
content.push('\'');
self.advance();
}
'\\' => {
// Inside ${...} within double quotes, same escape rules apply:
// \", \\, \$, \` produce the escaped char; others keep backslash
self.advance();
if let Some(esc) = self.peek_char() {
match esc {
'"' | '\\' | '$' | '`' => {
content.push(esc);
self.advance();
}
'}' => {
// \} should be a literal } without closing the expansion
content.push('\\');
content.push('}');
self.advance();
}
_ => {
content.push('\\');
content.push(esc);
self.advance();
}
}
} else {
content.push('\\');
}
}
'$' => {
content.push('$');
self.advance();
if self.peek_char() == Some('(') {
content.push('(');
self.advance();
self.read_command_subst_into(content);
} else if self.peek_char() == Some('{') {
content.push('{');
self.advance();
self.read_param_expansion_into(content);
}
}
_ => {
content.push(c);
self.advance();
}
}
}
}
/// Check if the content starting with { looks like a brace expansion
/// Brace expansion: {a,b,c} or {1..5} (contains , or ..)
/// Brace group: { cmd; } (contains spaces, semicolons, newlines)
fn looks_like_brace_expansion(&self) -> bool {
// Clone the iterator to peek ahead without consuming
let mut chars = self.chars.clone();
// Skip the opening {
if chars.next() != Some('{') {
return false;
}
let mut depth = 1;
let mut has_comma = false;
let mut has_dot_dot = false;
let mut prev_char = None;
for ch in chars {
match ch {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
// Found matching }, check if we have brace expansion markers
return has_comma || has_dot_dot;
}
}
',' if depth == 1 => has_comma = true,
'.' if prev_char == Some('.') && depth == 1 => has_dot_dot = true,
// Brace groups have whitespace/newlines/semicolons at depth 1
' ' | '\t' | '\n' | ';' if depth == 1 => return false,
_ => {}
}
prev_char = Some(ch);
}
false
}
/// Check if { is followed by whitespace (brace group start)
fn is_brace_group_start(&self) -> bool {
let mut chars = self.chars.clone();
// Skip the opening {
if chars.next() != Some('{') {
return false;
}
// If next char is whitespace or newline, it's a brace group
matches!(chars.next(), Some(' ') | Some('\t') | Some('\n') | None)
}
/// Read a {literal} pattern without comma/dot-dot as a word
fn read_brace_literal_word(&mut self) -> Option<Token> {
let mut word = String::new();
// Read the opening {
if let Some('{') = self.peek_char() {
word.push('{');
self.advance();
} else {
return None;
}
// Read until matching }
let mut depth = 1;
while let Some(ch) = self.peek_char() {
word.push(ch);
self.advance();
match ch {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
}
// Continue reading any suffix
while let Some(ch) = self.peek_char() {
if self.is_word_char(ch) {
word.push(ch);
self.advance();
} else {
break;
}
}
Some(Token::Word(word))
}
/// Read a brace expansion pattern as a word
fn read_brace_expansion_word(&mut self) -> Option<Token> {
let mut word = String::new();
// Read the opening {
if let Some('{') = self.peek_char() {
word.push('{');
self.advance();
} else {
return None;
}
// Read until matching }
let mut depth = 1;
while let Some(ch) = self.peek_char() {
word.push(ch);
self.advance();
match ch {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
}
// Continue reading any suffix after the brace pattern
while let Some(ch) = self.peek_char() {
if self.is_word_char(ch) || ch == '{' {
if ch == '{' {
// Another brace pattern - include it
word.push(ch);
self.advance();
let mut inner_depth = 1;
while let Some(c) = self.peek_char() {
word.push(c);
self.advance();
match c {
'{' => inner_depth += 1,
'}' => {
inner_depth -= 1;
if inner_depth == 0 {
break;
}
}
_ => {}
}
}
} else {
word.push(ch);
self.advance();
}
} else {
break;
}
}
Some(Token::Word(word))
}
/// Read a word starting with [ (glob bracket expression like [abc] or [a-z])
/// The opening [ has already been consumed
fn read_bracket_word(&mut self) -> Option<Token> {
let mut word = String::from("[");
// Read until we find the closing ] (handle nested correctly)
while let Some(ch) = self.peek_char() {
word.push(ch);
self.advance();
if ch == ']' {
break;
}
}
// Continue reading any remaining word characters (e.g., [abc]def)
while let Some(ch) = self.peek_char() {
if self.is_word_char(ch) {
word.push(ch);
self.advance();
} else {
break;
}
}
Some(Token::Word(word))
}
/// Peek ahead (without consuming) to see if `=(` starts an associative
/// compound assignment like `([key]=val ...)`. Returns true when the
/// first non-whitespace char after `(` is `[`.
fn looks_like_assoc_assign(&self) -> bool {
let mut chars = self.chars.clone();
// Skip the `(` we haven't consumed yet
if chars.next() != Some('(') {
return false;
}
// Skip optional whitespace
for ch in chars {
match ch {
' ' | '\t' => continue,
'[' => return true,
_ => return false,
}
}
false
}
fn is_word_char(&self, ch: char) -> bool {
!matches!(
ch,
' ' | '\t'
| '\n'
| ';'
| '|'
| '&'
| '>'
| '<'
| '('
| ')'
| '{'
| '}'
| '\''
| '"'
| '#'
)
}
/// Read here document content until the delimiter line is found
pub fn read_heredoc(&mut self, delimiter: &str) -> String {
let mut content = String::new();
let mut current_line = String::new();
// Save rest of current line (after the delimiter token on the command line).
// For `cat <<EOF | sort`, this captures ` | sort` so the parser can
// tokenize the pipe and subsequent command after the heredoc body.
//
// Quoted strings may span multiple lines (e.g., `cat <<EOF; echo "two\nthree"`),
// so we track quoting state and continue across newlines until quotes close.
let mut rest_of_line = String::new();
let mut in_double_quote = false;
let mut in_single_quote = false;
while let Some(ch) = self.peek_char() {
self.advance();
if ch == '\n' && !in_double_quote && !in_single_quote {
break;
}
if ch == '"' && !in_single_quote {
in_double_quote = !in_double_quote;
} else if ch == '\'' && !in_double_quote {
in_single_quote = !in_single_quote;
} else if ch == '\\' && in_double_quote {
// Escaped char inside double quotes — skip the next char too
rest_of_line.push(ch);
if let Some(next) = self.peek_char() {
rest_of_line.push(next);
self.advance();
}
continue;
}
rest_of_line.push(ch);
}
// Read lines until we find the delimiter
loop {
match self.peek_char() {
Some('\n') => {
self.advance();
// Check if current line matches delimiter
if current_line.trim() == delimiter {
break;
}
content.push_str(¤t_line);
content.push('\n');
current_line.clear();
}
Some(ch) => {
current_line.push(ch);
self.advance();
}
None => {
// End of input - check last line
if current_line.trim() == delimiter {
break;
}
if !current_line.is_empty() {
content.push_str(¤t_line);
}
break;
}
}
}
// Re-inject saved rest-of-line so subsequent tokens (pipes, commands, etc.)
// are visible to the parser. Add a newline so the tokenizer sees the line break.
if !rest_of_line.is_empty() {
for ch in rest_of_line.chars() {
self.reinject_buf.push_back(ch);
}
self.reinject_buf.push_back('\n');
}
content
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_words() {
let mut lexer = Lexer::new("echo hello world");
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("hello".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("world".to_string())));
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_single_quoted_string() {
let mut lexer = Lexer::new("echo 'hello world'");
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
// Single-quoted strings return LiteralWord (no variable expansion)
assert_eq!(
lexer.next_token(),
Some(Token::LiteralWord("hello world".to_string()))
);
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_double_quoted_string() {
let mut lexer = Lexer::new("echo \"hello world\"");
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
assert_eq!(
lexer.next_token(),
Some(Token::QuotedWord("hello world".to_string()))
);
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_operators() {
let mut lexer = Lexer::new("a | b && c || d; e &");
assert_eq!(lexer.next_token(), Some(Token::Word("a".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Pipe));
assert_eq!(lexer.next_token(), Some(Token::Word("b".to_string())));
assert_eq!(lexer.next_token(), Some(Token::And));
assert_eq!(lexer.next_token(), Some(Token::Word("c".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Or));
assert_eq!(lexer.next_token(), Some(Token::Word("d".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Semicolon));
assert_eq!(lexer.next_token(), Some(Token::Word("e".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Background));
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_redirects() {
let mut lexer = Lexer::new("a > b >> c < d << e <<< f");
assert_eq!(lexer.next_token(), Some(Token::Word("a".to_string())));
assert_eq!(lexer.next_token(), Some(Token::RedirectOut));
assert_eq!(lexer.next_token(), Some(Token::Word("b".to_string())));
assert_eq!(lexer.next_token(), Some(Token::RedirectAppend));
assert_eq!(lexer.next_token(), Some(Token::Word("c".to_string())));
assert_eq!(lexer.next_token(), Some(Token::RedirectIn));
assert_eq!(lexer.next_token(), Some(Token::Word("d".to_string())));
assert_eq!(lexer.next_token(), Some(Token::HereDoc));
assert_eq!(lexer.next_token(), Some(Token::Word("e".to_string())));
assert_eq!(lexer.next_token(), Some(Token::HereString));
assert_eq!(lexer.next_token(), Some(Token::Word("f".to_string())));
}
#[test]
fn test_comment() {
let mut lexer = Lexer::new("echo hello # this is a comment\necho world");
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("hello".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Newline));
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("world".to_string())));
}
#[test]
fn test_variable_words() {
let mut lexer = Lexer::new("echo $HOME $USER");
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("$HOME".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("$USER".to_string())));
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_pipeline_tokens() {
let mut lexer = Lexer::new("echo hello | cat");
assert_eq!(lexer.next_token(), Some(Token::Word("echo".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Word("hello".to_string())));
assert_eq!(lexer.next_token(), Some(Token::Pipe));
assert_eq!(lexer.next_token(), Some(Token::Word("cat".to_string())));
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_read_heredoc() {
// Simulate state after reading "cat <<EOF" - positioned at newline before content
let mut lexer = Lexer::new("\nhello\nworld\nEOF");
let content = lexer.read_heredoc("EOF");
assert_eq!(content, "hello\nworld\n");
}
#[test]
fn test_read_heredoc_single_line() {
let mut lexer = Lexer::new("\ntest\nEOF");
let content = lexer.read_heredoc("EOF");
assert_eq!(content, "test\n");
}
#[test]
fn test_read_heredoc_full_scenario() {
// Full scenario: "cat <<EOF\nhello\nworld\nEOF"
let mut lexer = Lexer::new("cat <<EOF\nhello\nworld\nEOF");
// Parser would read these tokens
assert_eq!(lexer.next_token(), Some(Token::Word("cat".to_string())));
assert_eq!(lexer.next_token(), Some(Token::HereDoc));
assert_eq!(lexer.next_token(), Some(Token::Word("EOF".to_string())));
// Now read heredoc content
let content = lexer.read_heredoc("EOF");
assert_eq!(content, "hello\nworld\n");
}
#[test]
fn test_read_heredoc_with_redirect() {
// Rest-of-line (> file.txt) is re-injected into the lexer buffer
let mut lexer = Lexer::new("cat <<EOF > file.txt\nhello\nEOF");
assert_eq!(lexer.next_token(), Some(Token::Word("cat".to_string())));
assert_eq!(lexer.next_token(), Some(Token::HereDoc));
assert_eq!(lexer.next_token(), Some(Token::Word("EOF".to_string())));
let content = lexer.read_heredoc("EOF");
assert_eq!(content, "hello\n");
// The redirect tokens are now available from the lexer
assert_eq!(lexer.next_token(), Some(Token::RedirectOut));
assert_eq!(
lexer.next_token(),
Some(Token::Word("file.txt".to_string()))
);
}
#[test]
fn test_assoc_compound_assignment() {
// declare -A m=([foo]="bar" [baz]="qux") should keep the compound
// assignment as a single Word token
let mut lexer = Lexer::new(r#"m=([foo]="bar" [baz]="qux")"#);
assert_eq!(
lexer.next_token(),
Some(Token::Word(r#"m=([foo]="bar" [baz]="qux")"#.to_string()))
);
assert_eq!(lexer.next_token(), None);
}
#[test]
fn test_indexed_array_not_collapsed() {
// arr=("hello world") should NOT be collapsed — parser handles
// quoted elements token-by-token via the LeftParen path
let mut lexer = Lexer::new(r#"arr=("hello world")"#);
assert_eq!(lexer.next_token(), Some(Token::Word("arr=".to_string())));
assert_eq!(lexer.next_token(), Some(Token::LeftParen));
}
/// Regression test for fuzz crash: single digit at EOF should not panic
/// (crash-13c5f6f887a11b2296d67f9857975d63b205ac4b)
#[test]
fn test_digit_at_eof_no_panic() {
// A lone digit with no following redirect operator must not panic
let mut lexer = Lexer::new("2");
let token = lexer.next_token();
assert!(token.is_some());
}
/// Issue #599: Nested ${...} inside unquoted ${...} must be a single token.
#[test]
fn test_nested_brace_expansion_single_token() {
// ${arr[${#arr[@]} - 1]} should be ONE word token, not split at inner }
let mut lexer = Lexer::new("${arr[${#arr[@]} - 1]}");
let token = lexer.next_token();
assert_eq!(
token,
Some(Token::Word("${arr[${#arr[@]} - 1]}".to_string()))
);
// No more tokens — everything was consumed
assert_eq!(lexer.next_token(), None);
}
/// Simple ${var} still works after brace depth change.
#[test]
fn test_simple_brace_expansion_unchanged() {
let mut lexer = Lexer::new("${foo}");
assert_eq!(lexer.next_token(), Some(Token::Word("${foo}".to_string())));
assert_eq!(lexer.next_token(), None);
}
}