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
1846 lines (1715 loc) · 69.2 KB
/
mod.rs
File metadata and controls
1846 lines (1715 loc) · 69.2 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
//! Parser module for the Rush shell.
//!
//! This module provides functionality to parse tokenized shell input into an Abstract
//! Syntax Tree (AST) that can be executed by the executor module.
pub mod ast;
mod control_flow;
pub use ast::{Ast, Redirection, ShellCommand};
use control_flow::*;
use super::lexer::Token;
/// Helper function to validate if a string is a valid variable name.
/// Returns true if the name starts with a letter or underscore.
fn is_valid_variable_name(name: &str) -> bool {
if let Some(first_char) = name.chars().next() {
first_char.is_alphabetic() || first_char == '_'
} else {
false
}
}
/// Helper function to create an empty body AST (a no-op that returns success).
/// Used for empty then/else branches, empty loop bodies, and empty function bodies.
pub(crate) fn create_empty_body_ast() -> Ast {
Ast::Pipeline(vec![ShellCommand {
args: vec!["true".to_string()],
redirections: Vec::new(),
compound: None,
}])
}
pub fn parse(tokens: Vec<Token>) -> Result<Ast, String> {
// First, try to detect and parse function definitions that span multiple lines
if tokens.len() >= 4
&& let (Token::Word(_), Token::LeftParen, Token::RightParen, Token::LeftBrace) =
(&tokens[0], &tokens[1], &tokens[2], &tokens[3])
{
// Look for the matching RightBrace
// Start from the opening brace (token 3) and find its match
let mut brace_depth = 1; // We've already seen the opening brace at position 3
let mut function_end = tokens.len();
let mut j = 4; // Start after the opening brace
while j < tokens.len() {
match &tokens[j] {
Token::LeftBrace => {
brace_depth += 1;
j += 1;
}
Token::RightBrace => {
brace_depth -= 1;
if brace_depth == 0 {
function_end = j + 1; // Include the closing brace
break;
}
j += 1;
}
Token::If => {
// Skip to matching fi to avoid confusion
let mut if_depth = 1;
j += 1;
while j < tokens.len() && if_depth > 0 {
match tokens[j] {
Token::If => if_depth += 1,
Token::Fi => if_depth -= 1,
_ => {}
}
j += 1;
}
}
Token::For | Token::While | Token::Until => {
// Skip to matching done
let mut for_depth = 1;
j += 1;
while j < tokens.len() && for_depth > 0 {
match tokens[j] {
Token::For | Token::While | Token::Until => for_depth += 1,
Token::Done => for_depth -= 1,
_ => {}
}
j += 1;
}
}
Token::Case => {
// Skip to matching esac
j += 1;
while j < tokens.len() {
if tokens[j] == Token::Esac {
j += 1;
break;
}
j += 1;
}
}
_ => {
j += 1;
}
}
}
if brace_depth == 0 && function_end <= tokens.len() {
// We found the complete function definition
let function_tokens = &tokens[0..function_end];
let remaining_tokens = &tokens[function_end..];
let function_ast = parse_function_definition(function_tokens)?;
return if remaining_tokens.is_empty() {
Ok(function_ast)
} else {
// There are more commands after the function
let remaining_ast = parse_commands_sequentially(remaining_tokens)?;
Ok(Ast::Sequence(vec![function_ast, remaining_ast]))
};
}
}
// Also check for legacy function definition format (word with parentheses followed by brace)
if tokens.len() >= 2
&& let Token::Word(ref word) = tokens[0]
&& let Some(paren_pos) = word.find('(')
&& word.ends_with(')')
&& paren_pos > 0
&& tokens[1] == Token::LeftBrace
{
return parse_function_definition(&tokens);
}
// Fall back to normal parsing
parse_commands_sequentially(&tokens)
}
/// Parses a single top-level command slice into an AST.
///
/// Recognizes assignments, local assignments, `return`, negation (`!`), control constructs
/// (`if`, `case`, `for`, `while`, `until`), function definitions, and otherwise falls back to
/// pipeline parsing to produce an `Ast` for the provided token slice.
///
/// # Returns
///
/// `Ok(Ast)` on success, `Err(String)` with a descriptive error message on failure (for example,
/// when the slice is empty or a `!` is not followed by a command).
///
/// # Examples
///
/// ```
/// // Note: parse_slice is a private function
/// // This example is for documentation only
/// ```
fn parse_slice(tokens: &[Token]) -> Result<Ast, String> {
if tokens.is_empty() {
return Err("No commands found".to_string());
}
// Check if it's an assignment
if tokens.len() == 2 {
// Check for pattern: VAR= VALUE
if let (Token::Word(var_eq), Token::Word(value)) = (&tokens[0], &tokens[1])
&& let Some(eq_pos) = var_eq.find('=')
&& eq_pos > 0
&& eq_pos < var_eq.len()
{
let var = var_eq[..eq_pos].to_string();
let full_value = format!("{}{}", &var_eq[eq_pos + 1..], value);
// Basic validation: variable name should start with letter or underscore
if is_valid_variable_name(&var) {
return Ok(Ast::Assignment {
var,
value: full_value,
});
}
}
}
// Check if it's an assignment (VAR= VALUE)
if tokens.len() == 2
&& let (Token::Word(var_eq), Token::Word(value)) = (&tokens[0], &tokens[1])
&& let Some(eq_pos) = var_eq.find('=')
&& eq_pos > 0
&& eq_pos == var_eq.len() - 1
{
let var = var_eq[..eq_pos].to_string();
// Basic validation: variable name should start with letter or underscore
if is_valid_variable_name(&var) {
return Ok(Ast::Assignment {
var,
value: value.clone(),
});
}
}
// Check if it's a local assignment (local VAR VALUE or local VAR= VALUE)
if tokens.len() == 3
&& let (Token::Local, Token::Word(var), Token::Word(value)) =
(&tokens[0], &tokens[1], &tokens[2])
{
// Strip trailing = if present (handles "local var= value" format)
let clean_var = if var.ends_with('=') {
&var[..var.len() - 1]
} else {
var
};
// Basic validation: variable name should start with letter or underscore
if is_valid_variable_name(clean_var) {
return Ok(Ast::LocalAssignment {
var: clean_var.to_string(),
value: value.clone(),
});
} else {
return Err(format!("Invalid variable name: {}", clean_var));
}
}
// Check if it's a return statement
if !tokens.is_empty()
&& tokens.len() <= 2
&& let Token::Return = &tokens[0]
{
if tokens.len() == 1 {
// return (with no value, defaults to 0)
return Ok(Ast::Return { value: None });
} else if let Token::Word(word) = &tokens[1] {
// return value
return Ok(Ast::Return {
value: Some(word.clone()),
});
}
}
// Check if it's a local assignment (local VAR=VALUE)
if tokens.len() == 2
&& let (Token::Local, Token::Word(var_eq)) = (&tokens[0], &tokens[1])
&& let Some(eq_pos) = var_eq.find('=')
&& eq_pos > 0
&& eq_pos < var_eq.len()
{
let var = var_eq[..eq_pos].to_string();
let value = var_eq[eq_pos + 1..].to_string();
// Basic validation: variable name should start with letter or underscore
if is_valid_variable_name(&var) {
return Ok(Ast::LocalAssignment { var, value });
} else {
return Err(format!("Invalid variable name: {}", var));
}
}
// Check if it's a local assignment (local VAR) with no initial value
if tokens.len() == 2
&& let (Token::Local, Token::Word(var)) = (&tokens[0], &tokens[1])
&& !var.contains('=')
{
// Basic validation: variable name should start with letter or underscore
if is_valid_variable_name(var) {
return Ok(Ast::LocalAssignment {
var: var.clone(),
value: String::new(),
});
} else {
return Err(format!("Invalid variable name: {}", var));
}
}
// Check if it's an assignment (single token with =)
if tokens.len() == 1
&& let Token::Word(ref word) = tokens[0]
&& let Some(eq_pos) = word.find('=')
&& eq_pos > 0
&& eq_pos < word.len()
{
let var = word[..eq_pos].to_string();
let value = word[eq_pos + 1..].to_string();
// Basic validation: variable name should start with letter or underscore
if is_valid_variable_name(&var) {
return Ok(Ast::Assignment { var, value });
}
}
// Check if it's an if statement
if let Token::If = tokens[0] {
return parse_if(tokens);
}
// Check if it's a case statement
if let Token::Case = tokens[0] {
return parse_case(tokens);
}
// Check if it's a for loop
if let Token::For = tokens[0] {
return parse_for(tokens);
}
// Check if it's a while loop
if let Token::While = tokens[0] {
return parse_while(tokens);
}
// Check if it's an until loop
if let Token::Until = tokens[0] {
return parse_until(tokens);
}
// Check if it's a function definition
// Pattern: Word LeftParen RightParen LeftBrace
if tokens.len() >= 4
&& let (Token::Word(word), Token::LeftParen, Token::RightParen, Token::LeftBrace) =
(&tokens[0], &tokens[1], &tokens[2], &tokens[3])
&& is_valid_variable_name(word)
{
return parse_function_definition(tokens);
}
// Also check for function definition with parentheses in the word (legacy support)
if tokens.len() >= 2
&& let Token::Word(ref word) = tokens[0]
&& let Some(paren_pos) = word.find('(')
&& word.ends_with(')')
&& paren_pos > 0
{
let func_name = &word[..paren_pos];
if is_valid_variable_name(func_name) && tokens[1] == Token::LeftBrace {
return parse_function_definition(tokens);
}
}
// Check if it's a function call (word followed by arguments)
// For Phase 1, we'll parse as regular pipeline and handle function calls in executor
// Otherwise, parse as pipeline
parse_pipeline(tokens)
}
/// Helper function to parse a single command without operators.
/// Returns the parsed AST and the number of tokens consumed.
fn parse_single_command(tokens: &[Token]) -> Result<(Ast, usize), String> {
if tokens.is_empty() {
return Err("Expected command".to_string());
}
let mut i = 0;
// Skip leading newlines
while i < tokens.len() && tokens[i] == Token::Newline {
i += 1;
}
if i >= tokens.len() {
return Err("Expected command".to_string());
}
// Handle negation first - recursively parse what comes after !
if tokens[i] == Token::Bang {
i += 1; // Skip the bang
// Skip any newlines after the bang
while i < tokens.len() && tokens[i] == Token::Newline {
i += 1;
}
if i >= tokens.len() {
return Err("Expected command after !".to_string());
}
// Recursively parse the negated command
// IMPORTANT: This should only consume a single atomic command,
// not a chain with logical operators
let (negated_ast, consumed) = parse_single_command(&tokens[i..])?;
i += consumed;
// Negation only applies to the immediately following command
// Return immediately without consuming any following operators
return Ok((
Ast::Negation {
command: Box::new(negated_ast),
},
i,
));
}
let start = i;
// Handle special constructs that have their own boundaries
match &tokens[i] {
Token::LeftParen => {
// Subshell - find matching paren
let mut paren_depth = 1;
i += 1;
while i < tokens.len() && paren_depth > 0 {
match tokens[i] {
Token::LeftParen => paren_depth += 1,
Token::RightParen => paren_depth -= 1,
_ => {}
}
i += 1;
}
if paren_depth != 0 {
return Err("Unmatched parenthesis".to_string());
}
}
Token::LeftBrace => {
// Command group - find matching brace
let mut brace_depth = 1;
i += 1;
while i < tokens.len() && brace_depth > 0 {
match tokens[i] {
Token::LeftBrace => brace_depth += 1,
Token::RightBrace => brace_depth -= 1,
_ => {}
}
i += 1;
}
if brace_depth != 0 {
return Err("Unmatched brace".to_string());
}
}
Token::If => {
// Find matching fi
let mut if_depth = 1;
i += 1;
while i < tokens.len() && if_depth > 0 {
match tokens[i] {
Token::If => if_depth += 1,
Token::Fi => {
if_depth -= 1;
if if_depth == 0 {
i += 1;
break;
}
}
_ => {}
}
i += 1;
}
}
Token::For | Token::While | Token::Until => {
// Find matching done
let mut loop_depth = 1;
i += 1;
while i < tokens.len() && loop_depth > 0 {
match tokens[i] {
Token::For | Token::While | Token::Until => loop_depth += 1,
Token::Done => {
loop_depth -= 1;
if loop_depth == 0 {
i += 1;
break;
}
}
_ => {}
}
i += 1;
}
}
Token::Case => {
// Find matching esac
i += 1;
while i < tokens.len() {
if tokens[i] == Token::Esac {
i += 1;
break;
}
i += 1;
}
}
_ => {
// Regular command/pipeline - stop at sequence separators
let mut brace_depth = 0;
let mut paren_depth = 0;
let mut last_was_pipe = false;
while i < tokens.len() {
// Check if we should stop before processing this token
// For logical operators (&&, ||), always stop at depth 0 after consuming at least one token
// For other separators, only stop after consuming at least one token
if i > start {
match &tokens[i] {
Token::And | Token::Or => {
if brace_depth == 0 && paren_depth == 0 {
if last_was_pipe {
return Err("Expected command after |".to_string());
}
break;
}
}
Token::Newline | Token::Semicolon | Token::Ampersand => {
if brace_depth == 0 && paren_depth == 0 && !last_was_pipe {
break;
}
}
Token::RightBrace if brace_depth == 0 => break,
Token::RightParen if paren_depth == 0 => break,
_ => {}
}
}
// Now process the token
match &tokens[i] {
Token::LeftBrace => {
brace_depth += 1;
last_was_pipe = false;
}
Token::RightBrace => {
if brace_depth > 0 {
brace_depth -= 1;
last_was_pipe = false;
}
}
Token::LeftParen => {
paren_depth += 1;
last_was_pipe = false;
}
Token::RightParen => {
if paren_depth > 0 {
paren_depth -= 1;
last_was_pipe = false;
}
}
Token::Pipe => last_was_pipe = true,
Token::Word(_) => last_was_pipe = false,
_ => last_was_pipe = false,
}
i += 1;
}
}
}
let command_tokens = &tokens[start..i];
// Safety check: ensure we consumed at least one token to prevent infinite loops
if i == start {
return Err("Internal parser error: parse_single_command consumed no tokens".to_string());
}
let mut ast = parse_slice(command_tokens)?;
// Check if this command should be executed asynchronously (ends with &)
if i < tokens.len() && tokens[i] == Token::Ampersand {
i += 1; // Consume the &
ast = Ast::AsyncCommand {
command: Box::new(ast),
};
}
Ok((ast, i))
}
/// Helper function to parse commands with && and || operators.
/// This builds a left-associative chain of operators.
/// Returns the parsed AST and the number of tokens consumed.
fn parse_next_command(tokens: &[Token]) -> Result<(Ast, usize), String> {
// Parse the first command
let (mut ast, mut i) = parse_single_command(tokens)?;
// Build left-associative chain of && and || operators iteratively
loop {
// Check if there's an && or || operator after this command
if i >= tokens.len() || (tokens[i] != Token::And && tokens[i] != Token::Or) {
break;
}
let operator = tokens[i].clone();
i += 1; // Skip the operator
// Skip any newlines after the operator
while i < tokens.len() && tokens[i] == Token::Newline {
i += 1;
}
if i >= tokens.len() {
return Err("Expected command after operator".to_string());
}
// Parse the next single command (without chaining)
let (right_ast, consumed) = parse_single_command(&tokens[i..])?;
i += consumed;
// Build left-associative structure
ast = match operator {
Token::And => Ast::And {
left: Box::new(ast),
right: Box::new(right_ast),
},
Token::Or => Ast::Or {
left: Box::new(ast),
right: Box::new(right_ast),
},
_ => unreachable!(),
};
}
Ok((ast, i))
}
/// Parses a slice of tokens into a top-level AST representing one or more sequential shell commands.
///
/// This function consumes the provided token sequence and produces an `Ast` that represents either a
/// single command/pipeline/compound construct or a `Sequence` of commands joined by semicolons/newlines
/// and conditional operators. It recognizes subshells, command groups, pipelines, redirections,
/// negation (`!`), function definitions, and control-flow blocks, and composes appropriate AST nodes.
///
/// # Errors
///
/// Returns an `Err(String)` when the tokens contain a syntactic problem that prevents building a valid AST,
/// for example unmatched braces/parentheses, an empty subshell or command group, or when no commands are present.
///
/// # Examples
///
/// ```
/// // Note: parse_commands_sequentially is a private function
/// // This example is for documentation only
/// ```
fn parse_commands_sequentially(tokens: &[Token]) -> Result<Ast, String> {
let mut i = 0;
let mut commands = Vec::new();
while i < tokens.len() {
// Skip whitespace and comments
while i < tokens.len() {
match &tokens[i] {
Token::Newline => {
i += 1;
}
Token::Word(word) if word.starts_with('#') => {
// Skip comment line
while i < tokens.len() && tokens[i] != Token::Newline {
i += 1;
}
if i < tokens.len() {
i += 1; // Skip the newline
}
}
_ => break,
}
}
if i >= tokens.len() {
break;
}
// Find the end of this command
let start = i;
// Check for subshell: LeftParen at start of command
// Must check BEFORE function definition to avoid ambiguity
if tokens[i] == Token::LeftParen {
// This is a subshell - find the matching RightParen
let mut paren_depth = 1;
let mut j = i + 1;
while j < tokens.len() && paren_depth > 0 {
match tokens[j] {
Token::LeftParen => paren_depth += 1,
Token::RightParen => paren_depth -= 1,
_ => {}
}
j += 1;
}
if paren_depth != 0 {
return Err("Unmatched parenthesis in subshell".to_string());
}
// Extract subshell body (tokens between parens)
let subshell_tokens = &tokens[i + 1..j - 1];
// Parse the subshell body recursively
// Empty subshells are not allowed
let body_ast = if subshell_tokens.is_empty() {
return Err("Empty subshell".to_string());
} else {
parse_commands_sequentially(subshell_tokens)?
};
let mut subshell_ast = Ast::Subshell {
body: Box::new(body_ast),
};
i = j; // Move past the closing paren
// Check for redirections after subshell
let mut redirections = Vec::new();
while i < tokens.len() {
match &tokens[i] {
Token::RedirOut => {
i += 1;
if i < tokens.len()
&& let Token::Word(file) = &tokens[i]
{
redirections.push(Redirection::Output(file.clone()));
i += 1;
}
}
Token::RedirOutClobber => {
i += 1;
if i >= tokens.len() {
return Err("expected filename after >|".to_string());
}
if let Token::Word(file) = &tokens[i] {
redirections.push(Redirection::OutputClobber(file.clone()));
i += 1;
} else {
return Err("expected filename after >|".to_string());
}
}
Token::RedirIn => {
i += 1;
if i < tokens.len()
&& let Token::Word(file) = &tokens[i]
{
redirections.push(Redirection::Input(file.clone()));
i += 1;
}
}
Token::RedirAppend => {
i += 1;
if i < tokens.len()
&& let Token::Word(file) = &tokens[i]
{
redirections.push(Redirection::Append(file.clone()));
i += 1;
}
}
Token::RedirectFdOut(fd, file) => {
redirections.push(Redirection::FdOutput(*fd, file.clone()));
i += 1;
}
Token::RedirectFdOutClobber(fd, file) => {
redirections.push(Redirection::FdOutputClobber(*fd, file.clone()));
i += 1;
}
Token::RedirectFdIn(fd, file) => {
redirections.push(Redirection::FdInput(*fd, file.clone()));
i += 1;
}
Token::RedirectFdAppend(fd, file) => {
redirections.push(Redirection::FdAppend(*fd, file.clone()));
i += 1;
}
Token::RedirectFdDup(from_fd, to_fd) => {
redirections.push(Redirection::FdDuplicate(*from_fd, *to_fd));
i += 1;
}
Token::RedirectFdClose(fd) => {
redirections.push(Redirection::FdClose(*fd));
i += 1;
}
Token::RedirectFdInOut(fd, file) => {
redirections.push(Redirection::FdInputOutput(*fd, file.clone()));
i += 1;
}
Token::RedirHereDoc(delimiter, quoted) => {
redirections
.push(Redirection::HereDoc(delimiter.clone(), quoted.to_string()));
i += 1;
}
Token::RedirHereString(content) => {
redirections.push(Redirection::HereString(content.clone()));
i += 1;
}
_ => break,
}
}
// Check if this subshell is part of a pipeline
if i < tokens.len() && tokens[i] == Token::Pipe {
// Find end of pipeline
let mut end = i;
let mut brace_depth = 0;
let mut paren_depth = 0;
let mut last_was_pipe = true; // Started with a pipe
while end < tokens.len() {
match &tokens[end] {
Token::Pipe => last_was_pipe = true,
Token::LeftBrace => {
brace_depth += 1;
last_was_pipe = false;
}
Token::RightBrace => {
if brace_depth > 0 {
brace_depth -= 1;
} else {
break;
}
last_was_pipe = false;
}
Token::LeftParen => {
paren_depth += 1;
last_was_pipe = false;
}
Token::RightParen => {
if paren_depth > 0 {
paren_depth -= 1;
} else {
break;
}
last_was_pipe = false;
}
Token::Newline | Token::Semicolon => {
if brace_depth == 0 && paren_depth == 0 && !last_was_pipe {
break;
}
}
Token::Word(_) => last_was_pipe = false,
_ => {}
}
end += 1;
}
let pipeline_ast = parse_pipeline(&tokens[start..end])?;
commands.push(pipeline_ast);
i = end;
continue;
}
// If not part of a pipeline, apply redirections to the subshell itself
if !redirections.is_empty() {
subshell_ast = Ast::Pipeline(vec![ShellCommand {
args: Vec::new(),
redirections,
compound: Some(Box::new(subshell_ast)),
}]);
}
// Check if this subshell should be executed asynchronously (ends with &)
if i < tokens.len() && tokens[i] == Token::Ampersand {
i += 1; // Consume the &
subshell_ast = Ast::AsyncCommand {
command: Box::new(subshell_ast),
};
commands.push(subshell_ast);
// Skip semicolon or newline after async subshell
if i < tokens.len() && (tokens[i] == Token::Newline || tokens[i] == Token::Semicolon) {
i += 1;
}
continue;
}
// Handle operators after subshell (&&, ||, ;, newline)
if i < tokens.len() && (tokens[i] == Token::And || tokens[i] == Token::Or) {
let operator = tokens[i].clone();
i += 1; // Skip the operator
// Skip any newlines after the operator
while i < tokens.len() && tokens[i] == Token::Newline {
i += 1;
}
// Parse only the next command (not the entire remaining sequence)
let (right_ast, consumed) = parse_next_command(&tokens[i..])?;
i += consumed;
// Create And or Or node
let combined_ast = match operator {
Token::And => Ast::And {
left: Box::new(subshell_ast),
right: Box::new(right_ast),
},
Token::Or => Ast::Or {
left: Box::new(subshell_ast),
right: Box::new(right_ast),
},
_ => unreachable!(),
};
commands.push(combined_ast);
// Skip semicolon or newline after the combined command
if i < tokens.len()
&& (tokens[i] == Token::Newline || tokens[i] == Token::Semicolon)
{
i += 1;
}
continue;
} else {
commands.push(subshell_ast);
}
// Skip semicolon or newline after subshell
if i < tokens.len() && (tokens[i] == Token::Newline || tokens[i] == Token::Semicolon) {
i += 1;
}
continue;
}
// Check for command group: LeftBrace at start of command
if tokens[i] == Token::LeftBrace {
// This is a command group - find the matching RightBrace
let mut brace_depth = 1;
let mut j = i + 1;
while j < tokens.len() && brace_depth > 0 {
match tokens[j] {
Token::LeftBrace => brace_depth += 1,
Token::RightBrace => brace_depth -= 1,
_ => {}
}
j += 1;
}
if brace_depth != 0 {
return Err("Unmatched brace in command group".to_string());
}
// Extract group body (tokens between braces)
let group_tokens = &tokens[i + 1..j - 1];
// Parse the group body recursively
// Empty groups are not allowed
let body_ast = if group_tokens.is_empty() {
return Err("Empty command group".to_string());
} else {
parse_commands_sequentially(group_tokens)?
};
let mut group_ast = Ast::CommandGroup {
body: Box::new(body_ast),
};
i = j; // Move past the closing brace
// Check for redirections after command group
let mut redirections = Vec::new();
while i < tokens.len() {
match &tokens[i] {
Token::RedirOut => {
i += 1;
if i < tokens.len()
&& let Token::Word(file) = &tokens[i]
{
redirections.push(Redirection::Output(file.clone()));
i += 1;
}
}
Token::RedirOutClobber => {
i += 1;
if i >= tokens.len() {
return Err("expected filename after >|".to_string());
}
if let Token::Word(file) = &tokens[i] {
redirections.push(Redirection::OutputClobber(file.clone()));
i += 1;
} else {
return Err("expected filename after >|".to_string());
}
}
Token::RedirIn => {
i += 1;
if i < tokens.len()
&& let Token::Word(file) = &tokens[i]
{
redirections.push(Redirection::Input(file.clone()));
i += 1;
}
}
Token::RedirAppend => {
i += 1;
if i < tokens.len()
&& let Token::Word(file) = &tokens[i]
{
redirections.push(Redirection::Append(file.clone()));
i += 1;
}
}
Token::RedirectFdOut(fd, file) => {
redirections.push(Redirection::FdOutput(*fd, file.clone()));
i += 1;
}
Token::RedirectFdIn(fd, file) => {
redirections.push(Redirection::FdInput(*fd, file.clone()));
i += 1;
}
Token::RedirectFdAppend(fd, file) => {
redirections.push(Redirection::FdAppend(*fd, file.clone()));
i += 1;
}
Token::RedirectFdDup(from_fd, to_fd) => {
redirections.push(Redirection::FdDuplicate(*from_fd, *to_fd));
i += 1;
}
Token::RedirectFdClose(fd) => {
redirections.push(Redirection::FdClose(*fd));
i += 1;
}
Token::RedirectFdInOut(fd, file) => {
redirections.push(Redirection::FdInputOutput(*fd, file.clone()));
i += 1;
}
Token::RedirHereDoc(delimiter, quoted) => {
redirections
.push(Redirection::HereDoc(delimiter.clone(), quoted.to_string()));
i += 1;
}
Token::RedirHereString(content) => {
redirections.push(Redirection::HereString(content.clone()));
i += 1;
}
_ => break,