rash/src/parser.rs

72 lines
2.1 KiB
Rust
Raw Normal View History

2024-04-11 19:09:19 +02:00
use crate::command::command_builder::CommandBuilder;
2024-04-11 10:16:09 +02:00
use crate::command::command_sequence::CommandSequence;
2024-04-10 12:31:29 +02:00
fn parse_quote(characters: &mut Vec<char>) -> Result<String, UnmatchedQuoteError> {
if characters.is_empty() {
Err(UnmatchedQuoteError)
} else {
let mut quoted_arg = String::default();
let mut current_char = characters.pop().unwrap();
while !characters.is_empty() && current_char != '\'' {
quoted_arg.push(current_char);
current_char = characters.pop().unwrap();
}
Ok(quoted_arg)
}
}
2024-04-14 16:18:46 +02:00
fn parse_main(characters: &mut Vec<char>, current_arg: &mut String) -> Vec<String> {
2024-04-14 12:07:42 +02:00
if characters.is_empty() {
vec![]
} else {
let current_char = characters.pop().unwrap();
if current_char.is_whitespace() {
if !current_arg.is_empty() {
let mut argv: Vec<String> = vec![current_arg.clone()];
2024-04-14 16:18:46 +02:00
argv.append(&mut parse_main(characters, &mut String::from("")));
2024-04-14 12:07:42 +02:00
argv
} else {
2024-04-14 16:18:46 +02:00
parse_main(characters, current_arg)
2024-04-14 12:07:42 +02:00
}
/*
2024-04-14 17:18:41 +02:00
} else if current_char == '\\' {
current_arg.push(characters.pop().unwrap());
parse_main(characters, current_arg)
*/
} else if current_char == '\'' {
let mut argv = vec![parse_quote(characters).unwrap()];
2024-04-14 16:18:46 +02:00
argv.append(&mut parse_main(characters, &mut String::default()));
argv
2024-04-14 17:06:51 +02:00
} else if current_char == ';' {
vec![]
2024-04-14 12:07:42 +02:00
} else {
current_arg.push(current_char);
2024-04-14 16:18:46 +02:00
parse_main(characters, current_arg)
2024-04-14 12:07:42 +02:00
}
}
}
2024-04-14 17:06:51 +02:00
pub fn parse(line: String) -> CommandSequence {
2024-04-14 12:07:42 +02:00
let mut characters: Vec<char> = line.chars().rev().collect();
2024-04-14 17:06:51 +02:00
let mut command_sequence = CommandSequence::new();
2024-04-14 16:18:46 +02:00
2024-04-14 17:06:51 +02:00
while !characters.is_empty() {
let argv = parse_main(&mut characters, &mut String::default());
2024-04-10 12:31:29 +02:00
2024-04-14 17:06:51 +02:00
if !argv.is_empty() {
let command = CommandBuilder::new(argv).build();
command_sequence.add(command);
}
}
2024-04-14 17:06:51 +02:00
command_sequence
2024-04-10 12:31:29 +02:00
}
#[derive(Debug)]
struct UnmatchedQuoteError;