From de900a725acd01a0fd7c1a5a978c8449c47d3a85 Mon Sep 17 00:00:00 2001 From: Hippolyte Chauvin Date: Sat, 28 Oct 2023 14:35:43 +0200 Subject: [PATCH] =?UTF-8?q?Premi=C3=A8re=20version=20du=20parser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Capable de découper des mots en fonction des whitespaces --- src/main.rs | 8 +++++++- src/parser.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index e7a11a9..71ac746 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,9 @@ +mod parser; + fn main() { - println!("Hello, world!"); + let command_line = String::from("ls -l"); + + let command_line_as_array: Vec = parser::parse(&command_line); + + println!("{:?}", command_line_as_array); } diff --git a/src/parser.rs b/src/parser.rs index ebf7ac5..97a4bf6 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,3 +1,47 @@ -pub fn parse(command_line: String) -> Vec { - todo!(); +fn parse_after_whitespace(char_splitted_command_line: &mut Vec, argv: &mut Vec) -> Vec { + let current_char_option = char_splitted_command_line.pop(); + + if current_char_option.is_none() { + argv.to_vec() + } else { + let current_char = current_char_option.unwrap(); + + if current_char.is_whitespace() { + parse_after_whitespace(char_splitted_command_line, argv) + } else { + parse_initial_state(char_splitted_command_line, &mut String::from(current_char.to_string()), argv) + } + } +} + +fn parse_initial_state(char_splitted_command_line: &mut Vec, current_arg: &mut String, argv: &mut Vec) -> Vec { + let current_char_option = char_splitted_command_line.pop(); + + if current_char_option.is_none() { + argv.push(current_arg.to_string()); + argv.to_vec() + } else { + let current_char = current_char_option.unwrap(); + if current_char.is_whitespace() { + argv.push(current_arg.to_string()); + parse_after_whitespace(char_splitted_command_line, argv) + } else { + current_arg.push(current_char); + parse_initial_state(char_splitted_command_line, current_arg, argv) + } + } +} + +fn split_string_in_chars(string_to_split: &String) -> Vec { + string_to_split.chars().rev().collect() +} + +pub fn parse(command_line: &String) -> Vec { + let mut argv: Vec = Vec::new(); + let mut char_splitted_command_line: Vec = split_string_in_chars(&command_line); + let mut new_arg = String::new(); + + argv = parse_initial_state(&mut char_splitted_command_line, &mut new_arg, &mut argv); + + argv }