-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rs
More file actions
5208 lines (4648 loc) · 171 KB
/
Copy pathparser.rs
File metadata and controls
5208 lines (4648 loc) · 171 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Command Parser
//!
//! Parses shell input into structured commands.
//! Distinguishes between built-in commands and external programs.
//! Supports I/O redirections (>, <, >>, 2>, etc.)
use anyhow::{anyhow, Context, Result};
use crate::redirection::Redirection;
/// Quote type for a word or word part
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QuoteType {
/// No quotes
None,
/// Single quotes '...' - no expansion
Single,
/// Double quotes "..." - expansion allowed
Double,
}
/// Type of process substitution
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessSubType {
/// Input: <(cmd) - command output as readable file
Input,
/// Output: >(cmd) - command input as writable file
Output,
}
/// Part of a word that may contain literals and variable references
#[derive(Debug, Clone, PartialEq)]
enum WordPart {
/// Literal text (no expansion)
Literal(String),
/// Variable reference $VAR
Variable(String),
/// Braced variable reference ${VAR}
BracedVariable(String),
/// Command substitution $(cmd) or `cmd`
CommandSub(String),
/// Process substitution <(cmd) or >(cmd)
ProcessSub(ProcessSubType, String),
}
/// Parameter expansion operations supported in ${VAR...} syntax
#[derive(Debug, Clone, PartialEq)]
enum ExpansionOp {
/// Simple expansion: ${VAR}
Simple,
/// Use default value: ${VAR:-default} or ${VAR-default}
Default {
value: String,
check_null: bool, // true for :-, false for -
},
/// Assign default value: ${VAR:=default} or ${VAR=default}
AssignDefault { value: String, check_null: bool },
/// Use alternative value: ${VAR:+value} or ${VAR+value}
UseAlternative { value: String, check_null: bool },
/// Error if unset: ${VAR:?message} or ${VAR?message}
ErrorIfUnset {
message: Option<String>,
check_null: bool,
},
/// String length: ${#VAR}
Length,
/// Substring extraction: ${VAR:offset} or ${VAR:offset:length}
Substring { offset: i32, length: Option<usize> },
}
/// Parsed parameter expansion from ${VAR...} syntax
#[derive(Debug, Clone, PartialEq)]
struct ParameterExpansion {
var_name: String,
operation: ExpansionOp,
}
/// Word with quote information for expansion
#[derive(Debug, Clone, PartialEq)]
struct QuotedWord {
parts: Vec<WordPart>,
quote_type: QuoteType,
}
impl QuotedWord {
fn new() -> Self {
Self {
parts: Vec::new(),
quote_type: QuoteType::None,
}
}
fn is_empty(&self) -> bool {
self.parts.is_empty()
}
fn push_literal(&mut self, s: String) {
if !s.is_empty() {
self.parts.push(WordPart::Literal(s));
}
}
fn push_variable(&mut self, name: String) {
self.parts.push(WordPart::Variable(name));
}
fn push_braced_variable(&mut self, name: String) {
self.parts.push(WordPart::BracedVariable(name));
}
fn push_command_sub(&mut self, cmd: String) {
self.parts.push(WordPart::CommandSub(cmd));
}
fn push_process_sub(&mut self, sub_type: ProcessSubType, cmd: String) {
self.parts.push(WordPart::ProcessSub(sub_type, cmd));
}
}
/// Token from lexical analysis
#[derive(Debug, Clone, PartialEq)]
enum Token {
/// Word with potential quoting and variables
Word(QuotedWord),
/// Output redirection operator: >
OutputRedirect,
/// Append redirection operator: >>
AppendRedirect,
/// Input redirection operator: <
InputRedirect,
/// Error output redirection operator: 2>
ErrorRedirect,
/// Error append redirection operator: 2>>
ErrorAppendRedirect,
/// Error to output redirection: 2>&1
ErrorToOutput,
/// Both output redirection (bash extension): &>
BothRedirect,
/// Pipeline operator: |
Pipe,
/// Here document: <<
HereDoc,
/// Here document with tab stripping: <<-
HereDocDash,
/// Here string: <<<
HereString,
/// Background operator: &
Background,
/// Logical AND operator: &&
And,
/// Logical OR operator: ||
Or,
/// Extended test open: [[
ExtendedTestOpen,
/// Extended test close: ]]
ExtendedTestClose,
}
/// Parsed command with arguments and redirections.
///
/// Represents all built-in and external commands that can be executed.
/// Built-in commands are variants of this enum; external commands use
/// [`Command::External`].
///
/// # Examples
/// ```
/// use vsh::parser::{parse_command, Command};
///
/// let cmd = parse_command("mkdir test")?;
/// match cmd {
/// Command::Mkdir { path, .. } => assert_eq!(path, "test"),
/// _ => panic!("Wrong command"),
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
#[derive(Debug, PartialEq)]
pub enum Command {
// Built-ins (existing)
Mkdir {
path: String,
redirects: Vec<Redirection>,
},
Rmdir {
path: String,
redirects: Vec<Redirection>,
},
Touch {
path: String,
redirects: Vec<Redirection>,
},
Rm {
path: String,
redirects: Vec<Redirection>,
},
/// Copy file (reversible — proven in CopyMoveOperations.lean)
Cp {
src: String,
dst: String,
redirects: Vec<Redirection>,
},
/// Move/rename (reversible — proven in CopyMoveOperations.lean)
Mv {
src: String,
dst: String,
redirects: Vec<Redirection>,
},
/// Create symbolic link (reversible — proven in SymlinkOperations.lean)
Ln {
target: String,
link: String,
redirects: Vec<Redirection>,
},
/// Change file permissions (reversible — proven in PermissionOperations.lean)
Chmod {
mode: String,
path: String,
redirects: Vec<Redirection>,
},
/// Change file ownership (reversible — proven in PermissionOperations.lean)
Chown {
owner: String,
path: String,
redirects: Vec<Redirection>,
},
Undo {
count: usize,
},
Redo {
count: usize,
},
History {
count: usize,
show_proofs: bool,
},
Exit,
Quit,
// Transactions
Begin {
name: String,
},
Commit,
Rollback,
// Display commands
Graph,
Proofs,
Ls {
path: Option<String>,
redirects: Vec<Redirection>,
},
Pwd {
redirects: Vec<Redirection>,
},
Cd {
path: Option<String>,
},
// Shell builtins
/// Echo: write arguments to stdout
Echo {
args: Vec<String>,
no_newline: bool,
interpret_escapes: bool,
redirects: Vec<Redirection>,
},
/// true: always returns exit code 0
True,
/// false: always returns exit code 1
False,
/// read: read a line from stdin, split by IFS, assign to variables
Read {
var_names: Vec<String>,
prompt: Option<String>,
redirects: Vec<Redirection>,
},
/// source/.: execute commands from a file in current shell
Source {
file: String,
},
/// set: set shell options or positional parameters
Set {
args: Vec<String>,
},
/// unset: remove a variable
Unset {
name: String,
},
/// eval: evaluate a string as a command
Eval {
args: Vec<String>,
},
// Conditionals
Test {
args: Vec<String>,
redirects: Vec<Redirection>,
},
Bracket {
args: Vec<String>,
redirects: Vec<Redirection>,
},
/// Extended test [[ ... ]] - bash-style with pattern/regex matching
ExtendedTest {
args: Vec<String>,
redirects: Vec<Redirection>,
},
// External command
External {
program: String,
args: Vec<String>,
redirects: Vec<Redirection>,
background: bool,
},
/// Pipeline of external commands (cmd1 | cmd2 | cmd3)
///
/// Each stage is a (program, args) pair. Intermediate stages use piped stdio.
/// Final redirections apply to the last stage only.
Pipeline {
stages: Vec<(String, Vec<String>)>,
redirects: Vec<Redirection>,
background: bool,
},
/// Variable assignment (VAR=value)
///
/// Sets a shell variable. If followed by a command, the assignment is
/// temporary for that command only (not yet implemented).
Assignment {
name: String,
value: String,
},
/// Array assignment (arr=(val1 val2 val3))
///
/// Sets an indexed array variable with initial values
ArrayAssignment {
name: String,
elements: Vec<String>,
},
/// Array element assignment (`arr[index]=value`)
///
/// Sets a single array element at the specified index (supports sparse arrays)
ArrayElementAssignment {
name: String,
index: usize,
value: String,
},
/// Array append (arr+=(val1 val2))
///
/// Appends elements to an existing array
ArrayAppend {
name: String,
elements: Vec<String>,
},
/// Export command (export VAR or export VAR=value)
Export {
name: String,
value: Option<String>,
},
// Job control
/// List jobs
Jobs {
long: bool,
},
/// Bring job to foreground
Fg {
job_spec: Option<String>,
},
/// Continue job in background
Bg {
job_spec: Option<String>,
},
/// Kill a job
Kill {
signal: Option<String>,
job_spec: String,
},
/// Logical operation (cmd1 && cmd2 or cmd1 || cmd2)
LogicalOp {
operator: LogicalOperator,
left: Box<Command>,
right: Box<Command>,
},
// Control structures
/// If/then/elif/else/fi conditional
If {
condition: Box<Command>,
then_body: Vec<Command>,
elif_parts: Vec<(Box<Command>, Vec<Command>)>,
else_body: Option<Vec<Command>>,
},
/// While loop: while condition; do body; done
WhileLoop {
condition: Box<Command>,
body: Vec<Command>,
},
/// For loop: for var in words...; do body; done
ForLoop {
var: String,
words: Vec<String>,
body: Vec<Command>,
},
/// Case statement: case word in pattern) body;; esac
CaseStatement {
word: String,
arms: Vec<CaseArm>,
},
// Wow-factor features (unique to verified reversible shell)
/// Explain: proof-annotated dry run showing preconditions, state transition,
/// inverse operation, and proof references across all 6 verification systems
Explain {
inner: Box<Command>,
},
/// Checkpoint: save a named snapshot of the current history position
Checkpoint {
name: String,
},
/// Restore: undo back to a named checkpoint, printing proof certificates
Restore {
name: String,
},
/// Checkpoints: list all named checkpoints
Checkpoints,
/// Diff: show what would change if we undo back to a given state
Diff {
target_op: usize,
},
/// Replay: animated replay of operation history with proof narration
Replay {
start: usize,
end: usize,
},
// Shell functions and related builtins
/// Function definition: `fname() { commands; }` or `function fname { commands; }`
FunctionDef {
name: String,
body: Vec<String>,
/// Raw text between the outermost `{` and `}`, preserving control
/// structures that the naive `;`/`\n` split in `body` fragments.
raw_body: String,
},
/// Return from a function with optional exit code
Return {
code: Option<i32>,
},
/// Local variable declaration within a function: `local var=value` or `local var`
Local {
assignments: Vec<(String, Option<String>)>,
},
// POSIX builtins (trap, alias, unalias)
/// trap builtin: register signal handlers
/// `trap 'command' SIGNAL...` or `trap - SIGNAL...` or `trap` (list)
Trap {
action: Option<String>,
signals: Vec<String>,
},
/// alias builtin: define or list aliases
/// `alias name=value` or `alias` (list all)
Alias {
definitions: Vec<(String, String)>,
},
/// unalias builtin: remove aliases
/// `unalias name...` or `unalias -a` (remove all)
Unalias {
names: Vec<String>,
all: bool,
},
}
/// A single arm of a case statement: pattern) commands ;;
#[derive(Debug, PartialEq)]
pub struct CaseArm {
pub patterns: Vec<String>,
pub body: Vec<Command>,
}
/// Logical operators for command chaining
#[derive(Debug, Clone, PartialEq)]
pub enum LogicalOperator {
/// AND (&&) - execute right only if left succeeds
And,
/// OR (||) - execute right only if left fails
Or,
}
/// Quote state during tokenization
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QuoteState {
None,
SingleQuote, // Inside '...'
DoubleQuote, // Inside "..."
Backslash, // After \ (escape next char)
}
/// Tokenize input string into words and redirection operators
///
/// Handles:
/// - Single quotes '...' (no expansion)
/// - Double quotes "..." (expansion allowed)
/// - Backslash escaping \
/// - Redirection operators: >, >>, <, 2>, 2>>, 2>&1, &>
/// - Pipeline operator: |
fn tokenize(input: &str) -> Result<Vec<Token>> {
let mut tokens = Vec::new();
let mut chars = input.chars().peekable();
let mut current_word = QuotedWord::new();
let mut current_literal = String::new();
let mut quote_state = QuoteState::None;
/// Helper to push current literal to word if not empty
macro_rules! push_literal {
() => {
if !current_literal.is_empty() {
current_word.push_literal(current_literal.clone());
current_literal.clear();
}
};
}
/// Helper to push current word to tokens if not empty
macro_rules! push_word {
() => {
push_literal!();
if !current_word.is_empty() {
tokens.push(Token::Word(current_word.clone()));
#[allow(unused_assignments)]
{
current_word = QuotedWord::new();
}
}
};
}
while let Some(ch) = chars.next() {
match quote_state {
QuoteState::Backslash => {
// After backslash: take character literally
// If escaping $, keep the backslash so expand_variables() skips it
if ch == '$' {
current_literal.push('\\');
}
current_literal.push(ch);
quote_state = QuoteState::None;
}
QuoteState::SingleQuote => {
// Inside single quotes: everything is literal except closing '
if ch == '\'' {
push_literal!();
quote_state = QuoteState::None;
} else {
current_literal.push(ch);
}
}
QuoteState::DoubleQuote => {
// Inside double quotes: expansion allowed, escape with \
match ch {
'"' => {
// End double quote
push_literal!();
quote_state = QuoteState::None;
}
'\\' => {
// Backslash in double quotes
if let Some(&next_ch) = chars.peek() {
if matches!(next_ch, '"' | '$' | '\\' | '\n') {
// Escape these special chars
chars.next();
// If escaping $, keep backslash so expand_variables() skips it
if next_ch == '$' {
current_literal.push('\\');
}
current_literal.push(next_ch);
} else {
// Not a special char, keep backslash
current_literal.push('\\');
}
} else {
current_literal.push('\\');
}
}
'$' => {
// Variable expansion in double quotes
push_literal!();
parse_variable(&mut chars, &mut current_word)?;
}
'`' => {
// Backtick command substitution in double quotes
push_literal!();
let cmd = parse_command_sub_backtick(&mut chars)?;
current_word.push_command_sub(cmd);
}
_ => {
current_literal.push(ch);
}
}
}
QuoteState::None => {
// Outside quotes
match ch {
// Quotes
'\'' => {
push_literal!();
current_word.quote_type = QuoteType::Single;
quote_state = QuoteState::SingleQuote;
}
'"' => {
push_literal!();
current_word.quote_type = QuoteType::Double;
quote_state = QuoteState::DoubleQuote;
}
'\\' => {
push_literal!();
quote_state = QuoteState::Backslash;
}
// Variable expansion
'$' => {
push_literal!();
parse_variable(&mut chars, &mut current_word)?;
}
// Backtick command substitution
'`' => {
push_literal!();
let cmd = parse_command_sub_backtick(&mut chars)?;
current_word.push_command_sub(cmd);
}
// Whitespace: end current word
' ' | '\t' => {
push_word!();
}
// Redirection operators and process substitution
'>' => {
if chars.peek() == Some(&'(') {
// Process substitution: >(cmd)
push_literal!();
let cmd = parse_process_sub_output(&mut chars)?;
current_word.push_process_sub(ProcessSubType::Output, cmd);
} else {
// Regular redirection: > or >>
push_word!();
if chars.peek() == Some(&'>') {
chars.next();
tokens.push(Token::AppendRedirect);
} else {
tokens.push(Token::OutputRedirect);
}
}
}
'<' => {
if chars.peek() == Some(&'<') {
// Could be << or <<<
chars.next(); // consume second <
if chars.peek() == Some(&'<') {
// Here string: <<<
chars.next(); // consume third <
push_word!();
tokens.push(Token::HereString);
} else if chars.peek() == Some(&'-') {
// Here document with tab stripping: <<-
chars.next(); // consume -
push_word!();
tokens.push(Token::HereDocDash);
} else {
// Here document: <<
push_word!();
tokens.push(Token::HereDoc);
}
} else if chars.peek() == Some(&'(') {
// Process substitution: <(cmd)
push_literal!();
let cmd = parse_process_sub_input(&mut chars)?;
current_word.push_process_sub(ProcessSubType::Input, cmd);
} else {
// Input redirection: <
push_word!();
tokens.push(Token::InputRedirect);
}
}
'2' => {
// Check if this is start of 2> or 2>&1
// Only treat as redirect if '2' is the start of a new token
// (not part of a word like "file2>out")
if current_literal.is_empty()
&& current_word.is_empty()
&& chars.peek() == Some(&'>')
{
chars.next(); // consume >
match chars.peek() {
Some(&'>') => {
chars.next();
tokens.push(Token::ErrorAppendRedirect);
}
Some(&'&') => {
chars.next();
if chars.peek() == Some(&'1') {
chars.next();
tokens.push(Token::ErrorToOutput);
} else {
// Invalid: 2>&[not 1]
current_literal.push_str("2>&");
}
}
_ => {
tokens.push(Token::ErrorRedirect);
}
}
} else {
// Regular '2' character, part of word
current_literal.push(ch);
}
}
'&' => {
// Check for &&, &>, or &
if chars.peek() == Some(&'&') {
push_word!();
chars.next();
tokens.push(Token::And);
} else if chars.peek() == Some(&'>') {
push_word!();
chars.next();
tokens.push(Token::BothRedirect);
} else {
// Background job operator: &
push_word!();
tokens.push(Token::Background);
}
}
'|' => {
// Check for || or |
if chars.peek() == Some(&'|') {
push_word!();
chars.next();
tokens.push(Token::Or);
} else {
push_word!();
tokens.push(Token::Pipe);
}
}
'[' => {
// Check for [[ (extended test) or [ (regular test/bracket)
if chars.peek() == Some(&'[') {
push_word!();
chars.next();
tokens.push(Token::ExtendedTestOpen);
} else {
// Regular '[' character, part of word
current_literal.push(ch);
}
}
']' => {
// Check for ]] (extended test close) or ] (regular bracket)
if chars.peek() == Some(&']') {
push_word!();
chars.next();
tokens.push(Token::ExtendedTestClose);
} else {
// Regular ']' character, part of word
current_literal.push(ch);
}
}
// Regular character
_ => {
current_literal.push(ch);
}
}
}
}
}
// Check for unclosed quotes
match quote_state {
QuoteState::SingleQuote => {
return Err(anyhow!("Unclosed single quote"));
}
QuoteState::DoubleQuote => {
return Err(anyhow!("Unclosed double quote"));
}
_ => {}
}
// Add final word if any
push_word!();
Ok(tokens)
}
/// Parse a variable reference ($VAR or ${VAR}) from the character stream
fn parse_variable(
chars: &mut std::iter::Peekable<std::str::Chars>,
word: &mut QuotedWord,
) -> Result<()> {
if chars.peek() == Some(&'(') {
// Command substitution: $(cmd)
chars.next(); // consume '('
let cmd = parse_command_sub_dollar(chars)?;
word.push_command_sub(cmd);
} else if chars.peek() == Some(&'{') {
// Braced form: ${VAR}
chars.next(); // consume '{'
let mut var_name = String::new();
loop {
match chars.peek() {
Some(&'}') => {
chars.next(); // consume '}'
break;
}
Some(&ch) => {
var_name.push(ch);
chars.next();
}
None => {
return Err(anyhow!("Unclosed braced variable reference"));
}
}
}
word.push_braced_variable(var_name);
} else if let Some(&next_ch) = chars.peek() {
// Simple form: $VAR or special variables. The peek above already
// bound next_ch by value; chars.next() is called purely to advance
// the iterator and the bound value is used directly. This removes
// three previous panic sites.
if next_ch == '?' || next_ch == '$' || next_ch == '#' {
// Single-character special variable
chars.next();
word.push_variable(next_ch.to_string());
} else if next_ch.is_ascii_digit() {
// Positional parameter: $0, $1, $2, etc.
chars.next();
word.push_variable(next_ch.to_string());
} else if next_ch.is_alphabetic() || next_ch == '_' {
// Variable name
let mut var_name = String::new();
while let Some(&c) = chars.peek() {
if c.is_alphanumeric() || c == '_' {
var_name.push(c);
chars.next();
} else {
break;
}
}
word.push_variable(var_name);
} else if next_ch == '@' || next_ch == '*' {
// Special positional parameters: $@ or $*
chars.next();
word.push_variable(next_ch.to_string());
} else {
// $ not followed by variable, treat as literal
word.push_literal("$".to_string());
}
} else {
// $ at end of string
word.push_literal("$".to_string());
}
Ok(())
}
/// Parse command substitution in $(cmd) form
fn parse_command_sub_dollar(chars: &mut std::iter::Peekable<std::str::Chars>) -> Result<String> {
let mut cmd = String::new();
let mut depth = 1; // Track nesting depth for nested $()
for ch in chars.by_ref() {
match ch {
'(' => {
// Check if it's $( to track nested command substitution
if cmd.ends_with('$') {
depth += 1;
}
cmd.push(ch);
}
')' => {
depth -= 1;
if depth == 0 {
return Ok(cmd);
}
cmd.push(ch);
}
_ => cmd.push(ch),
}
}
Err(anyhow!("Unclosed command substitution: $("))
}
/// Parse command substitution in `cmd` form
fn parse_command_sub_backtick(chars: &mut std::iter::Peekable<std::str::Chars>) -> Result<String> {
let mut cmd = String::new();
let mut escaped = false;
for ch in chars.by_ref() {
match (ch, escaped) {
('\\', false) => escaped = true,
('`', false) => return Ok(cmd),
('`', true) => {
cmd.push('`');
escaped = false;
}
('\\', true) => {
cmd.push('\\');
escaped = false;
}
('$', true) => {
cmd.push('$');
escaped = false;
}
(_, true) => {
// Other escaped characters: keep backslash
cmd.push('\\');
cmd.push(ch);
escaped = false;
}
(_, false) => cmd.push(ch),
}
}
Err(anyhow!("Unclosed command substitution: `"))
}
/// Parse process substitution in <(cmd) form (input)
fn parse_process_sub_input(chars: &mut std::iter::Peekable<std::str::Chars>) -> Result<String> {
// Expects that '<(' has been detected and < consumed
chars.next(); // consume '('
let mut cmd = String::new();
let mut depth = 1; // Track nesting depth
for ch in chars.by_ref() {
match ch {
'(' => {
depth += 1;
cmd.push(ch);
}
')' => {
depth -= 1;
if depth == 0 {
return Ok(cmd);