forked from drewwalton19216801/rush-sh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
1378 lines (1297 loc) · 62.4 KB
/
Copy pathmod.rs
File metadata and controls
1378 lines (1297 loc) · 62.4 KB
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
//! Lexical analysis for the Rush shell.
//!
//! This module provides tokenization of shell input, converting raw text into
//! a stream of tokens that can be parsed into an Abstract Syntax Tree (AST).
pub mod token;
use token::is_keyword;
pub use token::{Token, is_shell_keyword};
use std::collections::HashSet;
use std::env;
use super::parameter_expansion::{expand_parameter, parse_parameter_expansion};
use super::state::ShellState;
/// Skip whitespace characters (space and tab) in the character stream
fn skip_whitespace(chars: &mut std::iter::Peekable<std::str::Chars>) {
while let Some(&ch) = chars.peek() {
if ch == ' ' || ch == '\t' {
chars.next();
} else {
break;
}
}
}
/// Flush the current word buffer into tokens, checking for keywords only if not quoted
fn flush_current_token(current: &mut String, tokens: &mut Vec<Token>, was_quoted: bool) {
if !current.is_empty() {
// Only check for keywords if the word was NOT quoted
// Quoted strings like "done" should always be Word tokens, not keyword tokens
if !was_quoted && let Some(keyword) = is_keyword(current) {
tokens.push(keyword);
current.clear();
return;
}
tokens.push(Token::Word(current.clone()));
current.clear();
}
}
/// Collect characters until a closing brace '}' is found
/// Returns the collected content (without the closing brace)
fn collect_until_closing_brace(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
let mut content = String::new();
while let Some(&ch) = chars.peek() {
if ch == '}' {
chars.next(); // consume }
break;
} else {
content.push(ch);
chars.next();
}
}
content
}
/// Collect characters within parentheses, tracking depth
/// Returns the collected content (without the closing parenthesis)
/// The closing parenthesis is consumed from the stream
/// This is used for command substitution $(...) and arithmetic expansion $((...))
fn collect_with_paren_depth(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
let mut content = String::new();
let mut paren_depth = 1; // We start after the opening paren
let mut in_single_quote = false;
let mut in_double_quote = false;
while let Some(&ch) = chars.peek() {
if ch == '\'' && !in_double_quote {
// Toggle single quote state (unless we're in double quotes)
in_single_quote = !in_single_quote;
content.push(ch);
chars.next();
} else if ch == '"' && !in_single_quote {
// Toggle double quote state (unless we're in single quotes)
in_double_quote = !in_double_quote;
content.push(ch);
chars.next();
} else if ch == '(' && !in_single_quote && !in_double_quote {
paren_depth += 1;
content.push(ch);
chars.next();
} else if ch == ')' && !in_single_quote && !in_double_quote {
paren_depth -= 1;
if paren_depth == 0 {
chars.next(); // consume the closing ")"
break;
} else {
content.push(ch);
chars.next();
}
} else {
content.push(ch);
chars.next();
}
}
content
}
/// Parse a variable name from the character stream
/// Handles special single-character variables ($?, $$, $0, etc.)
/// and regular multi-character variable names
/// IMPORTANT: This function does NOT consume the terminating character
fn parse_variable_name(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
let mut var_name = String::new();
// Check for special single-character variables first
if let Some(&ch) = chars.peek() {
if ch == '?'
|| ch == '$'
|| ch == '0'
|| ch == '#'
|| ch == '@'
|| ch == '*'
|| ch == '!'
|| ch.is_ascii_digit()
{
var_name.push(ch);
chars.next();
} else {
// Regular variable name - use manual loop to avoid consuming the terminating character
// Note: take_while() would consume the first non-matching character, which is wrong
while let Some(&ch) = chars.peek() {
if ch.is_alphanumeric() || ch == '_' {
var_name.push(ch);
chars.next();
} else {
break;
}
}
}
}
var_name
}
fn expand_variables_in_command(command: &str, shell_state: &ShellState) -> String {
// If the command contains command substitution syntax, don't expand variables
if command.contains("$(") || command.contains('`') {
return command.to_string();
}
let mut chars = command.chars().peekable();
let mut current = String::new();
while let Some(&ch) = chars.peek() {
if ch == '$' {
chars.next(); // consume $
if let Some(&'{') = chars.peek() {
// Parameter expansion ${VAR} or ${VAR:modifier}
chars.next(); // consume {
let param_content = collect_until_closing_brace(&mut chars);
if !param_content.is_empty() {
// Handle special case of ${#VAR} (length)
if param_content.starts_with('#') && param_content.len() > 1 {
let var_name = ¶m_content[1..];
if let Some(val) = shell_state.get_var(var_name) {
current.push_str(&val.len().to_string());
} else {
current.push('0');
}
} else {
// Parse and expand the parameter
match parse_parameter_expansion(¶m_content) {
Ok(expansion) => {
match expand_parameter(&expansion, shell_state) {
Ok(expanded) => {
current.push_str(&expanded);
}
Err(_) => {
// On error, keep the literal
current.push_str("${");
current.push_str(¶m_content);
current.push('}');
}
}
}
Err(_) => {
// On parse error, keep the literal
current.push_str("${");
current.push_str(¶m_content);
current.push('}');
}
}
}
} else {
// Empty braces, keep literal
current.push_str("${}");
}
} else if let Some(&'(') = chars.peek() {
// Command substitution - don't expand here
current.push('$');
current.push('(');
chars.next();
} else if let Some(&'`') = chars.peek() {
// Backtick substitution - don't expand here
current.push('$');
current.push('`');
chars.next();
} else {
// Variable expansion
let var_name = parse_variable_name(&mut chars);
if !var_name.is_empty() {
if let Some(val) = shell_state.get_var(&var_name) {
current.push_str(&val);
} else {
current.push('$');
current.push_str(&var_name);
}
} else {
current.push('$');
}
}
} else if ch == '`' {
// Backtick - don't expand variables inside
current.push(ch);
chars.next();
} else {
current.push(ch);
chars.next();
}
}
// Process the result to handle any remaining expansions
if current.contains('$') {
// Simple variable expansion for remaining $VAR patterns
let mut final_result = String::new();
let mut chars = current.chars().peekable();
while let Some(&ch) = chars.peek() {
if ch == '$' {
chars.next(); // consume $
if let Some(&'{') = chars.peek() {
// Parameter expansion ${VAR} or ${VAR:modifier}
chars.next(); // consume {
let param_content = collect_until_closing_brace(&mut chars);
if !param_content.is_empty() {
// Handle special case of ${#VAR} (length)
if param_content.starts_with('#') && param_content.len() > 1 {
let var_name = ¶m_content[1..];
if let Some(val) = shell_state.get_var(var_name) {
final_result.push_str(&val.len().to_string());
} else {
final_result.push('0');
}
} else {
// Parse and expand the parameter
match parse_parameter_expansion(¶m_content) {
Ok(expansion) => {
match expand_parameter(&expansion, shell_state) {
Ok(expanded) => {
if expanded.is_empty() {
// For empty expansions in the second pass, we need to handle this differently
// since we're building a final string, we'll just not add anything
// The empty token creation happens at the main lexing level
} else {
final_result.push_str(&expanded);
}
}
Err(_) => {
// On error, keep the literal
final_result.push_str("${");
final_result.push_str(¶m_content);
final_result.push('}');
}
}
}
Err(_) => {
// On parse error, keep the literal
final_result.push_str("${");
final_result.push_str(¶m_content);
final_result.push('}');
}
}
}
} else {
// Empty braces, keep literal
final_result.push_str("${}");
}
} else {
let var_name = parse_variable_name(&mut chars);
if !var_name.is_empty() {
if let Some(val) = shell_state.get_var(&var_name) {
final_result.push_str(&val);
} else {
final_result.push('$');
final_result.push_str(&var_name);
}
} else {
final_result.push('$');
}
}
} else {
final_result.push(ch);
chars.next();
}
}
final_result
} else {
current
}
}
/// Tokenizes a shell-like input string into a sequence of lexer `Token`s.
///
/// The lexer recognizes words, quoting (single/double), parameter and arithmetic
/// expansions (kept as literals for runtime expansion), command substitutions,
/// pipes and logical operators, parentheses and braces (including brace expansion
/// detection), tilde expansion, a wide range of redirection forms (including
/// file-descriptor-aware redirections, here-documents/strings, and the `>|`
/// noclobber override), aliases, and control-flow keywords. Returns `Err` with a
/// diagnostic string for syntax errors (for example, invalid redirection forms
/// or missing filenames).
///
/// # Examples
///
/// ```
/// use rush_sh::lexer::{lex, Token};
/// use rush_sh::state::ShellState;
///
/// let state = ShellState::default();
/// let toks = lex("echo hello | cat > out.txt", &state).unwrap();
/// assert!(matches!(toks[0], Token::Word(ref s) if s == "echo"));
/// assert_eq!(toks.last().unwrap(), &Token::Word("out.txt".to_string()));
/// ```
pub fn lex(input: &str, shell_state: &ShellState) -> Result<Vec<Token>, String> {
let mut tokens = Vec::new();
let mut chars = input.chars().peekable();
let mut current = String::new();
let mut in_double_quote = false;
let mut in_single_quote = false;
let mut just_closed_quote = false; // Track if we just closed a quote with empty content
let mut was_quoted = false; // Track if current token contains any quoted content
while let Some(&ch) = chars.peek() {
match ch {
' ' | '\t' if !in_double_quote && !in_single_quote => {
// Handle the case where we just closed an empty quoted string
if just_closed_quote && current.is_empty() {
tokens.push(Token::Word("".to_string()));
just_closed_quote = false;
was_quoted = false; // Reset after pushing empty quoted string
} else {
flush_current_token(&mut current, &mut tokens, was_quoted);
was_quoted = false; // Reset after flushing
}
chars.next();
}
'\n' if !in_double_quote && !in_single_quote => {
// Handle the case where we just closed an empty quoted string
if just_closed_quote && current.is_empty() {
tokens.push(Token::Word("".to_string()));
just_closed_quote = false;
was_quoted = false; // Reset after pushing empty quoted string
} else {
flush_current_token(&mut current, &mut tokens, was_quoted);
was_quoted = false; // Reset after flushing
}
tokens.push(Token::Newline);
chars.next();
}
'"' if !in_single_quote => {
// Check if this quote is escaped (preceded by backslash in current)
let is_escaped = current.ends_with('\\');
if is_escaped && in_double_quote {
// This is an escaped quote inside double quotes - treat as literal
current.pop(); // Remove the backslash
current.push('"'); // Add the literal quote
chars.next(); // consume the quote
just_closed_quote = false;
} else {
chars.next(); // consume the quote
if in_double_quote {
// End of double quote - the content stays in current
// We don't push it yet - it might be part of a larger word
// like in: alias ls="ls --color"
// But we need to track if it was empty
just_closed_quote = current.is_empty();
in_double_quote = false;
was_quoted = true; // Mark that this token was quoted
} else {
// Start of double quote - don't push current yet
// The quoted content will be appended to current
in_double_quote = true;
just_closed_quote = false;
}
}
}
'\\' if in_double_quote => {
// Handle backslash escaping inside double quotes
chars.next(); // consume the backslash
if let Some(&next_ch) = chars.peek() {
// In double quotes, backslash only escapes: $ ` " \ and newline
if next_ch == '$'
|| next_ch == '`'
|| next_ch == '"'
|| next_ch == '\\'
|| next_ch == '\n'
{
// Escape the next character - just add it literally
current.push(next_ch);
chars.next(); // consume the escaped character
} else {
// Backslash doesn't escape this character, keep both
current.push('\\');
current.push(next_ch);
chars.next();
}
} else {
// Backslash at end of input
current.push('\\');
}
}
'\'' => {
if in_single_quote {
// End of single quote - the content stays in current
// We don't push it yet - it might be part of a larger word
// like in: trap 'echo "..."' EXIT
just_closed_quote = current.is_empty();
in_single_quote = false;
was_quoted = true; // Mark that this token was quoted
} else if !in_double_quote {
// Start of single quote - don't push current yet
// The quoted content will be appended to current
in_single_quote = true;
just_closed_quote = false;
}
chars.next();
}
'$' if !in_single_quote => {
just_closed_quote = false; // Reset flag when we add content
chars.next(); // consume $
if let Some(&'{') = chars.peek() {
// Handle parameter expansion ${VAR} by consuming the entire pattern
chars.next(); // consume {
let param_content = collect_until_closing_brace(&mut chars);
if !param_content.is_empty() {
// Handle special case of ${#VAR} (length)
if param_content.starts_with('#') && param_content.len() > 1 {
let var_name = ¶m_content[1..];
if let Some(val) = shell_state.get_var(var_name) {
current.push_str(&val.len().to_string());
} else {
current.push('0');
}
} else {
// Parse and expand the parameter
match parse_parameter_expansion(¶m_content) {
Ok(expansion) => {
match expand_parameter(&expansion, shell_state) {
Ok(expanded) => {
if expanded.is_empty() {
// If we're inside quotes, just continue building the current token
// Don't create a separate empty token
if !in_double_quote && !in_single_quote {
// Only create empty token if we're not in quotes
if !current.is_empty() {
if let Some(keyword) = is_keyword(¤t)
{
tokens.push(keyword);
} else {
let word = expand_variables_in_command(
¤t,
shell_state,
);
tokens.push(Token::Word(word));
}
current.clear();
}
// Create an empty token for the empty expansion
tokens.push(Token::Word("".to_string()));
}
// If in quotes, the empty expansion just contributes nothing to current
} else {
current.push_str(&expanded);
}
}
Err(_) => {
// On error, fall back to literal syntax but split into separate tokens
if !current.is_empty() {
if let Some(keyword) = is_keyword(¤t) {
tokens.push(keyword);
} else {
let word = expand_variables_in_command(
¤t,
shell_state,
);
tokens.push(Token::Word(word));
}
current.clear();
}
// For the error case, we need to split at the space to match test expectations
if let Some(space_pos) = param_content.find(' ') {
// Split at the first space, but keep the closing brace with the first part
let first_part =
format!("${{{}}}", ¶m_content[..space_pos]);
let second_part = format!(
"{}}}",
¶m_content[space_pos + 1..]
);
tokens.push(Token::Word(first_part));
tokens.push(Token::Word(second_part));
} else {
let literal = format!("${{{}}}", param_content);
tokens.push(Token::Word(literal));
}
}
}
}
Err(_) => {
// On parse error, keep the literal
current.push_str("${");
current.push_str(¶m_content);
current.push('}');
}
}
}
} else {
// Empty braces, keep literal
current.push_str("${}");
}
} else if let Some(&'(') = chars.peek() {
chars.next(); // consume (
if let Some(&'(') = chars.peek() {
// Arithmetic expansion $((...)) - keep as literal for execution-time expansion
chars.next(); // consume second (
let arithmetic_expr = collect_with_paren_depth(&mut chars);
// Check if we have the second closing paren
let found_closing = if let Some(&')') = chars.peek() {
chars.next(); // consume the second ")"
true
} else {
false
};
// Keep as literal for execution-time expansion
current.push_str("$((");
current.push_str(&arithmetic_expr);
if found_closing {
current.push_str("))");
}
} else {
// Command substitution $(...) - keep as literal for runtime expansion
// This will be expanded by the executor using execute_and_capture_output()
let sub_command = collect_with_paren_depth(&mut chars);
// Keep the command substitution as literal - it will be expanded at execution time
current.push_str("$(");
current.push_str(&sub_command);
current.push(')');
}
} else {
// Variable expansion - collect var name without consuming the terminating character
let var_name = parse_variable_name(&mut chars);
if !var_name.is_empty() {
// For now, keep all variables as literals - they will be expanded during execution
current.push('$');
current.push_str(&var_name);
} else {
current.push('$');
}
}
}
'|' if !in_double_quote && !in_single_quote => {
flush_current_token(&mut current, &mut tokens, false);
chars.next(); // consume first |
// Check if this is || (OR operator)
if let Some(&'|') = chars.peek() {
chars.next(); // consume second |
tokens.push(Token::Or);
} else {
tokens.push(Token::Pipe);
}
// Skip any whitespace after the pipe/or
skip_whitespace(&mut chars);
}
'&' if !in_double_quote && !in_single_quote => {
flush_current_token(&mut current, &mut tokens, false);
chars.next(); // consume first &
// Check if this is && (AND operator)
if let Some(&'&') = chars.peek() {
chars.next(); // consume second &
tokens.push(Token::And);
// Skip any whitespace after &&
skip_whitespace(&mut chars);
} else {
// Single & for background execution
tokens.push(Token::Ampersand);
// Skip any whitespace after &
skip_whitespace(&mut chars);
}
}
'!' if !in_double_quote && !in_single_quote => {
// Only emit Token::Bang if ! appears at command start position
// Command start is: beginning of input, after whitespace/newline/semicolon, or after operators
let is_command_start = current.is_empty()
&& (tokens.is_empty()
|| matches!(
tokens.last(),
Some(
Token::Newline
| Token::Semicolon
| Token::And
| Token::Or
| Token::Then
| Token::Else
| Token::Elif
| Token::Do
| Token::While
| Token::Until
| Token::If
| Token::LeftParen
| Token::LeftBrace
)
));
if is_command_start {
flush_current_token(&mut current, &mut tokens, false);
chars.next(); // consume !
tokens.push(Token::Bang);
// Skip any whitespace after the bang
skip_whitespace(&mut chars);
} else {
// Not at command start - treat as regular character
just_closed_quote = false;
current.push(ch);
chars.next();
}
}
'>' if !in_double_quote && !in_single_quote => {
// Check if this is a file descriptor redirection like 2>&1 or 2>file
// Look back to see if current ends with a digit
let fd_num = if !current.is_empty() {
if let Some(last_char) = current.chars().last() {
if last_char.is_ascii_digit() {
// Extract the fd number
let fd = last_char.to_digit(10).unwrap() as i32;
// Remove the fd digit from current
current.pop();
Some(fd)
} else {
None
}
} else {
None
}
} else {
None
};
// Flush any remaining content before the fd number
flush_current_token(&mut current, &mut tokens, false);
chars.next(); // consume >
// Check what follows the >
if let Some(&'|') = chars.peek() {
// This is >| (noclobber override)
chars.next(); // consume |
skip_whitespace(&mut chars);
// Collect the filename (handle quotes)
let mut filename = String::new();
let mut in_filename_quote = false;
let mut filename_quote_char = ' ';
while let Some(&ch) = chars.peek() {
if !in_filename_quote && (ch == '"' || ch == '\'') {
in_filename_quote = true;
filename_quote_char = ch;
chars.next(); // consume quote but don't add to filename
} else if in_filename_quote && ch == filename_quote_char {
in_filename_quote = false;
chars.next(); // consume quote but don't add to filename
} else if !in_filename_quote
&& (ch == ' '
|| ch == '\t'
|| ch == '\n'
|| ch == ';'
|| ch == '|'
|| ch == '&'
|| ch == '>'
|| ch == '<')
{
break;
} else {
filename.push(ch);
chars.next();
}
}
if !filename.is_empty() {
if let Some(fd) = fd_num {
// With fd number, use RedirectFdOutClobber for proper noclobber override
tokens.push(Token::RedirectFdOutClobber(fd, filename));
} else {
// Without fd number, use RedirOutClobber
tokens.push(Token::RedirOutClobber);
tokens.push(Token::Word(filename));
}
} else {
// No filename provided - error
return Err("Invalid redirection: expected filename after >|".to_string());
}
} else if let Some(&'&') = chars.peek() {
chars.next(); // consume &
// Collect the target fd or '-'
let mut target = String::new();
while let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() || ch == '-' {
target.push(ch);
chars.next();
} else {
break;
}
}
if !target.is_empty() {
let source_fd = fd_num.unwrap_or(1); // Default to stdout
if target == "-" {
// Close fd: N>&-
tokens.push(Token::RedirectFdClose(source_fd));
} else if let Ok(target_fd) = target.parse::<i32>() {
// Duplicate fd: N>&M
tokens.push(Token::RedirectFdDup(source_fd, target_fd));
} else {
// Invalid target, treat as error
return Err(format!("Invalid file descriptor: {}", target));
}
skip_whitespace(&mut chars);
} else {
// Invalid syntax: >& with nothing after
return Err(
"Invalid redirection syntax: expected fd number or '-' after >&"
.to_string(),
);
}
} else if let Some(&'>') = chars.peek() {
// Append redirection: >> or N>>
chars.next(); // consume second >
skip_whitespace(&mut chars);
// Collect the filename (handle quotes)
let mut filename = String::new();
let mut in_filename_quote = false;
let mut filename_quote_char = ' ';
while let Some(&ch) = chars.peek() {
if !in_filename_quote && (ch == '"' || ch == '\'') {
in_filename_quote = true;
filename_quote_char = ch;
chars.next(); // consume quote but don't add to filename
} else if in_filename_quote && ch == filename_quote_char {
in_filename_quote = false;
chars.next(); // consume quote but don't add to filename
} else if !in_filename_quote
&& (ch == ' '
|| ch == '\t'
|| ch == '\n'
|| ch == ';'
|| ch == '|'
|| ch == '&'
|| ch == '>'
|| ch == '<')
{
break;
} else {
filename.push(ch);
chars.next();
}
}
if !filename.is_empty() {
if let Some(fd) = fd_num {
tokens.push(Token::RedirectFdAppend(fd, filename));
} else {
tokens.push(Token::RedirAppend);
tokens.push(Token::Word(filename));
}
} else {
// No filename provided - error
return Err("Invalid redirection: expected filename after >>".to_string());
}
} else {
// Regular output redirection: > or N>
skip_whitespace(&mut chars);
// Collect the filename (handle quotes)
let mut filename = String::new();
let mut in_filename_quote = false;
let mut filename_quote_char = ' ';
while let Some(&ch) = chars.peek() {
if !in_filename_quote && (ch == '"' || ch == '\'') {
in_filename_quote = true;
filename_quote_char = ch;
chars.next(); // consume quote but don't add to filename
} else if in_filename_quote && ch == filename_quote_char {
in_filename_quote = false;
chars.next(); // consume quote but don't add to filename
} else if !in_filename_quote
&& (ch == ' '
|| ch == '\t'
|| ch == '\n'
|| ch == ';'
|| ch == '|'
|| ch == '&'
|| ch == '>'
|| ch == '<')
{
break;
} else {
filename.push(ch);
chars.next();
}
}
if !filename.is_empty() {
if let Some(fd) = fd_num {
tokens.push(Token::RedirectFdOut(fd, filename));
} else {
tokens.push(Token::RedirOut);
tokens.push(Token::Word(filename));
}
} else {
// No filename provided - error
return Err("Invalid redirection: expected filename after >".to_string());
}
}
}
'<' if !in_double_quote && !in_single_quote => {
// Check if this is a file descriptor redirection like 3<file or 0<&1
let fd_num = if !current.is_empty() {
if let Some(last_char) = current.chars().last() {
if last_char.is_ascii_digit() {
// Extract the fd number
let fd = last_char.to_digit(10).unwrap() as i32;
// Remove the fd digit from current
current.pop();
Some(fd)
} else {
None
}
} else {
None
}
} else {
None
};
// Flush any remaining content before the fd number
flush_current_token(&mut current, &mut tokens, false);
chars.next(); // consume <
// Check what follows the <
if let Some(&'&') = chars.peek() {
chars.next(); // consume &
// Collect the target fd or '-'
let mut target = String::new();
while let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() || ch == '-' {
target.push(ch);
chars.next();
} else {
break;
}
}
if !target.is_empty() {
let source_fd = fd_num.unwrap_or(0); // Default to stdin
if target == "-" {
// Close fd: N<&-
tokens.push(Token::RedirectFdClose(source_fd));
} else if let Ok(target_fd) = target.parse::<i32>() {
// Duplicate fd: N<&M
tokens.push(Token::RedirectFdDup(source_fd, target_fd));
} else {
// Invalid target
return Err(format!("Invalid file descriptor: {}", target));
}
skip_whitespace(&mut chars);
} else {
// Invalid syntax: <& with nothing after
return Err(
"Invalid redirection syntax: expected fd number or '-' after <&"
.to_string(),
);
}
} else if let Some(&'<') = chars.peek() {
// Here-document or here-string
chars.next(); // consume second <
if let Some(&'<') = chars.peek() {
chars.next(); // consume third <
// Here-string: skip whitespace, then collect content
skip_whitespace(&mut chars);
let mut content = String::new();
let mut in_quote = false;
let mut quote_char = ' ';
while let Some(&ch) = chars.peek() {
if ch == '\n' && !in_quote {
break;
}
if (ch == '"' || ch == '\'') && !in_quote {
in_quote = true;
quote_char = ch;
chars.next(); // consume quote but don't add to content
} else if in_quote && ch == quote_char {
in_quote = false;
chars.next(); // consume quote but don't add to content
} else if !in_quote && (ch == ' ' || ch == '\t') {
break;
} else {
content.push(ch);
chars.next();
}
}
if !content.is_empty() {
tokens.push(Token::RedirHereString(content));
} else {
return Err("Invalid here-string syntax: expected content after <<<"
.to_string());
}
} else {
// Here-document: skip whitespace, then collect delimiter
skip_whitespace(&mut chars);
let mut delimiter = String::new();
let mut in_quote = false;
let mut quote_char = ' ';
let mut was_quoted = false; // Track if any quotes were found
while let Some(&ch) = chars.peek() {
if ch == '\n' && !in_quote {
break;
}
if (ch == '"' || ch == '\'') && !in_quote {
in_quote = true;
quote_char = ch;
was_quoted = true; // Mark that we found a quote
chars.next(); // consume quote but don't add to delimiter
} else if in_quote && ch == quote_char {
in_quote = false;
chars.next(); // consume quote but don't add to delimiter
} else if !in_quote && (ch == ' ' || ch == '\t') {
break;
} else {
delimiter.push(ch);
chars.next();
}
}
if !delimiter.is_empty() {
// Pass both delimiter and whether it was quoted
tokens.push(Token::RedirHereDoc(delimiter, was_quoted));
} else {
return Err(
"Invalid here-document syntax: expected delimiter after <<"
.to_string(),
);
}
}
} else if let Some(&'>') = chars.peek() {
// Read/write redirection: N<>
chars.next(); // consume >
skip_whitespace(&mut chars);
// Collect the filename (handle quotes)
let mut filename = String::new();
let mut in_filename_quote = false;
let mut filename_quote_char = ' ';
while let Some(&ch) = chars.peek() {
if !in_filename_quote && (ch == '"' || ch == '\'') {
in_filename_quote = true;
filename_quote_char = ch;
chars.next(); // consume quote but don't add to filename
} else if in_filename_quote && ch == filename_quote_char {
in_filename_quote = false;
chars.next(); // consume quote but don't add to filename
} else if !in_filename_quote
&& (ch == ' '
|| ch == '\t'